blob: 3c4f500a4fe37d93fe4837f1e8db4205c0c0d78d [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>
Eric Laurentf1047e82018-04-16 19:18:20 -070031#include <cutils/multiuser.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070033#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070035#include <media/audiohal/DeviceHalInterface.h>
36#include <media/audiohal/DevicesFactoryHalInterface.h>
37#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070038#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070040#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <utils/String16.h>
42#include <utils/threads.h>
43
Steven Morelandf0c02ce2018-02-23 14:53:55 -080044#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_visualizer.h>
55#include <system/audio_effects/effect_ns.h>
56#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten9e58b552013-01-18 15:09:48 -080062#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070063#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080064#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070066#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.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),
Eric Laurent72e3f392015-05-20 14:43:50 -0700162 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700163{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700164 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
165 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
166 // zero ID has a special meaning, so unavailable
167 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
168 }
169
Glenn Kasten949a9262013-04-16 12:35:20 -0700170 getpid_cached = getpid();
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 Laurent1c333e22014-05-20 10:48:17 -0700228 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700229
Eric Laurenta4c5a552012-03-29 10:12:40 -0700230 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800231
232 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233}
234
235AudioFlinger::~AudioFlinger()
236{
237 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700238 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700239 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240 }
241 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700242 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700243 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700245
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800246 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
247 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700248 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700250
251 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700252 if (sMediaLogService != 0) {
253 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
254 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
255 mUnregisteredWriters.pop();
256 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700257 }
258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259}
260
Eric Laurentfc235202016-12-20 18:48:17 -0800261//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800262__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800263status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
264 const audio_attributes_t *attr,
265 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700266 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800267 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800268 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800269 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700270 sp<MmapStreamInterface>& interface,
271 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800272{
273 sp<AudioFlinger> af;
274 {
275 Mutex::Autolock _l(gLock);
276 af = gAudioFlinger.promote();
277 }
278 status_t ret = NO_INIT;
279 if (af != 0) {
280 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800281 direction, attr, config, client, deviceId,
282 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800283 }
284 return ret;
285}
286
Eric Laurent6acd1d42017-01-04 14:23:29 -0800287status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
288 const audio_attributes_t *attr,
289 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700290 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800291 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800292 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800293 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700294 sp<MmapStreamInterface>& interface,
295 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800296{
297 status_t ret = initCheck();
298 if (ret != NO_ERROR) {
299 return ret;
300 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800301 audio_session_t actualSessionId = *sessionId;
302 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
303 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
304 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800305 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700306 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800307 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
308 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
309 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
310 fullConfig.sample_rate = config->sample_rate;
311 fullConfig.channel_mask = config->channel_mask;
312 fullConfig.format = config->format;
313 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800314 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200315 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800316 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800317 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
318 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700319 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800320 } else {
321 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800322 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800323 client.clientPid,
324 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800325 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800326 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700327 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800328 }
329 if (ret != NO_ERROR) {
330 return ret;
331 }
332
333 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
334 // audio policy manager and we can retrieve it
335 sp<MmapThread> thread = mMmapThreads.valueFor(io);
336 if (thread != 0) {
337 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800338 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700339 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800340 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800341 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700342 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800343 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700344 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800345 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700346 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800347 ret = NO_INIT;
348 }
349
350 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
351
Eric Laurentfc235202016-12-20 18:48:17 -0800352 return ret;
353}
354
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355static const char * const audio_interfaces[] = {
356 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
357 AUDIO_HARDWARE_MODULE_ID_A2DP,
358 AUDIO_HARDWARE_MODULE_ID_USB,
359};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700360
Phil Burk062e67a2015-02-11 13:40:50 -0800361AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700362 audio_module_handle_t module,
363 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700364{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700365 // if module is 0, the request comes from an old policy manager and we should load
366 // well known modules
367 if (module == 0) {
368 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700369 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700370 loadHwModule_l(audio_interfaces[i]);
371 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700372 // then try to find a module supporting the requested device.
373 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
374 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700375 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
376 uint32_t supportedDevices;
377 if (dev->getSupportedDevices(&supportedDevices) == OK &&
378 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700379 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700380 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700381 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700382 } else {
383 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700384 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
385 if (audioHwDevice != NULL) {
386 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700387 }
388 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700389
Dima Zavin799a70e2011-04-18 16:57:27 -0700390 return NULL;
391}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392
Glenn Kasten0f11b512014-01-31 16:18:54 -0800393void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700394{
395 const size_t SIZE = 256;
396 char buffer[SIZE];
397 String8 result;
398
399 result.append("Clients:\n");
400 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800401 sp<Client> client = mClients.valueAt(i).promote();
402 if (client != 0) {
403 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
404 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 }
406 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700407
Eric Laurentd1b28d42013-09-18 18:47:13 -0700408 result.append("Notification Clients:\n");
409 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
410 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
411 result.append(buffer);
412 }
413
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700414 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800415 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700416 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
417 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800418 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700419 result.append(buffer);
420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422}
423
424
Glenn Kasten0f11b512014-01-31 16:18:54 -0800425void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426{
427 const size_t SIZE = 256;
428 char buffer[SIZE];
429 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800430 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431
John Grossman4ff14ba2012-02-08 16:37:41 -0800432 snprintf(buffer, SIZE, "Hardware status: %d\n"
433 "Standby Time mSec: %u\n",
434 hardwareStatus,
435 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 result.append(buffer);
437 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438}
439
Glenn Kasten0f11b512014-01-31 16:18:54 -0800440void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441{
442 const size_t SIZE = 256;
443 char buffer[SIZE];
444 String8 result;
445 snprintf(buffer, SIZE, "Permission Denial: "
446 "can't dump AudioFlinger from pid=%d, uid=%d\n",
447 IPCThreadState::self()->getCallingPid(),
448 IPCThreadState::self()->getCallingUid());
449 result.append(buffer);
450 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451}
452
Eric Laurent81784c32012-11-19 14:55:58 -0800453bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454{
455 bool locked = false;
456 for (int i = 0; i < kDumpLockRetries; ++i) {
457 if (mutex.tryLock() == NO_ERROR) {
458 locked = true;
459 break;
460 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800461 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 }
463 return locked;
464}
465
466status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
467{
Glenn Kasten44deb052012-02-05 18:09:08 -0800468 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 dumpPermissionDenial(fd, args);
470 } else {
471 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800472 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 if (!hardwareLocked) {
474 String8 result(kHardwareLockedString);
475 write(fd, result.string(), result.size());
476 } else {
477 mHardwareLock.unlock();
478 }
479
Eric Laurent81784c32012-11-19 14:55:58 -0800480 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481
482 // failed to lock - AudioFlinger is probably deadlocked
483 if (!locked) {
484 String8 result(kDeadlockedString);
485 write(fd, result.string(), result.size());
486 }
487
Eric Laurent021cf962014-05-13 10:18:14 -0700488 bool clientLocked = dumpTryLock(mClientLock);
489 if (!clientLocked) {
490 String8 result(kClientLockedString);
491 write(fd, result.string(), result.size());
492 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700493
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700494 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700495 mEffectsFactoryHal->dumpEffects(fd);
496 } else {
497 String8 result(kNoEffectsFactory);
498 write(fd, result.string(), result.size());
499 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700500
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700502 if (clientLocked) {
503 mClientLock.unlock();
504 }
505
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 dumpInternals(fd, args);
507
508 // dump playback threads
509 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
510 mPlaybackThreads.valueAt(i)->dump(fd, args);
511 }
512
513 // dump record threads
514 for (size_t i = 0; i < mRecordThreads.size(); i++) {
515 mRecordThreads.valueAt(i)->dump(fd, args);
516 }
517
Eric Laurent6acd1d42017-01-04 14:23:29 -0800518 // dump mmap threads
519 for (size_t i = 0; i < mMmapThreads.size(); i++) {
520 mMmapThreads.valueAt(i)->dump(fd, args);
521 }
522
Eric Laurentaaa44472014-09-12 17:41:50 -0700523 // dump orphan effect chains
524 if (mOrphanEffectChains.size() != 0) {
525 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
526 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
527 mOrphanEffectChains.valueAt(i)->dump(fd, args);
528 }
529 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700530 // dump all hardware devs
531 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700532 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
533 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700535
Glenn Kasten46909e72013-02-26 09:20:22 -0800536#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700537 // dump the serially shared record tee sink
538 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700539 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700540 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800541#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700542
rago3bd1c872016-09-26 12:58:14 -0700543 BUFLOG_RESET;
544
Glenn Kastend65d73c2012-06-22 17:21:07 -0700545 if (locked) {
546 mLock.unlock();
547 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800548
549 // append a copy of media.log here by forwarding fd to it, but don't attempt
550 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700551 if (sMediaLogServiceAsBinder != 0) {
552 dprintf(fd, "\nmedia.log:\n");
553 Vector<String16> args;
554 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800555 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700556
557 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700558 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700559 bool unreachableMemory = false;
560 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700561 if (arg == String16("-m")) {
562 dumpMem = true;
563 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700564 unreachableMemory = true;
565 }
566 }
567
Andy Hung07b745e2016-05-23 16:21:07 -0700568 if (dumpMem) {
569 dprintf(fd, "\nDumping memory:\n");
570 std::string s = dumpMemoryAddresses(100 /* limit */);
571 write(fd, s.c_str(), s.size());
572 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700573 if (unreachableMemory) {
574 dprintf(fd, "\nDumping unreachable memory:\n");
575 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700576 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700577 write(fd, s.c_str(), s.size());
578 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 }
580 return NO_ERROR;
581}
582
Eric Laurent021cf962014-05-13 10:18:14 -0700583sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800584{
Eric Laurent021cf962014-05-13 10:18:14 -0700585 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800586 // If pid is already in the mClients wp<> map, then use that entry
587 // (for which promote() is always != 0), otherwise create a new entry and Client.
588 sp<Client> client = mClients.valueFor(pid).promote();
589 if (client == 0) {
590 client = new Client(this, pid);
591 mClients.add(pid, client);
592 }
593
594 return client;
595}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596
Glenn Kasten9e58b552013-01-18 15:09:48 -0800597sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
598{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700599 // If there is no memory allocated for logs, return a dummy writer that does nothing.
600 // Similarly if we can't contact the media.log service, also return a dummy writer.
601 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800602 return new NBLog::Writer();
603 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700604 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
605 // If allocation fails, consult the vector of previously unregistered writers
606 // and garbage-collect one or more them until an allocation succeeds
607 if (shared == 0) {
608 Mutex::Autolock _l(mUnregisteredWritersLock);
609 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
610 {
611 // Pick the oldest stale writer to garbage-collect
612 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
613 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700614 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700615 // Now the media.log remote reference to IMemory is gone. When our last local
616 // reference to IMemory also drops to zero at end of this block,
617 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
618 }
619 // Re-attempt the allocation
620 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
621 if (shared != 0) {
622 goto success;
623 }
624 }
625 // Even after garbage-collecting all old writers, there is still not enough memory,
626 // so return a dummy writer
627 return new NBLog::Writer();
628 }
629success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800630 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
631 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
632 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700633 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800634 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800635}
636
637void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
638{
Glenn Kasten685ef092013-02-04 08:15:34 -0800639 if (writer == 0) {
640 return;
641 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800642 sp<IMemory> iMemory(writer->getIMemory());
643 if (iMemory == 0) {
644 return;
645 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700646 // Rather than removing the writer immediately, append it to a queue of old writers to
647 // be garbage-collected later. This allows us to continue to view old logs for a while.
648 Mutex::Autolock _l(mUnregisteredWritersLock);
649 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800650}
651
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652// IAudioFlinger interface
653
Eric Laurent21da6472017-11-09 16:29:26 -0800654sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
655 CreateTrackOutput& output,
656 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657{
658 sp<PlaybackThread::Track> track;
659 sp<TrackHandle> trackHandle;
660 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800662 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800663 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664
Eric Laurent21da6472017-11-09 16:29:26 -0800665 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700666 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800667 uid_t clientUid = input.clientInfo.clientUid;
668 if (!isTrustedCallingUid(callingUid)) {
669 ALOGW_IF(clientUid != callingUid,
670 "%s uid %d tried to pass itself off as %d",
671 __FUNCTION__, callingUid, clientUid);
672 clientUid = callingUid;
673 updatePid = true;
674 }
675 pid_t clientPid = input.clientInfo.clientPid;
676 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700677 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800678 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700679 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800680 __func__, callingUid, callingPid, clientPid);
681 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700682 }
683
Eric Laurent21da6472017-11-09 16:29:26 -0800684 audio_session_t sessionId = input.sessionId;
685 if (sessionId == AUDIO_SESSION_ALLOCATE) {
686 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800687 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
688 lStatus = BAD_VALUE;
689 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800690 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800691
Eric Laurent21da6472017-11-09 16:29:26 -0800692 output.sessionId = sessionId;
693 output.outputId = AUDIO_IO_HANDLE_NONE;
694 output.selectedDeviceId = input.selectedDeviceId;
695
696 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200697 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800698 &output.selectedDeviceId, &portId);
699
700 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
701 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
702 goto Exit;
703 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800704 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
705 // but if someone uses binder directly they could bypass that and cause us to crash
706 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000707 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 lStatus = BAD_VALUE;
709 goto Exit;
710 }
711
Glenn Kasten53b5d092014-02-05 10:00:23 -0800712 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800713 if (!audio_is_output_channel(input.config.channel_mask)) {
714 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800715 lStatus = BAD_VALUE;
716 goto Exit;
717 }
718
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700719 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800720 if (!audio_is_valid_format(input.config.format)) {
721 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700722 lStatus = BAD_VALUE;
723 goto Exit;
724 }
725
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726 {
727 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800728 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800730 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 lStatus = BAD_VALUE;
732 goto Exit;
733 }
734
Eric Laurent21da6472017-11-09 16:29:26 -0800735 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736
Glenn Kastene848bd92014-03-13 15:00:32 -0700737 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800738 // check if an effect chain with the same session ID is present on another
739 // output thread and move it here.
740 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
741 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
742 if (mPlaybackThreads.keyAt(i) != output.outputId) {
743 uint32_t sessions = t->hasAudioSession(sessionId);
744 if (sessions & ThreadBase::EFFECT_SESSION) {
745 effectThread = t.get();
746 break;
Eric Laurentde070132010-07-13 04:45:46 -0700747 }
748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 }
Eric Laurent21da6472017-11-09 16:29:26 -0800750 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751
Eric Laurent21da6472017-11-09 16:29:26 -0800752 output.sampleRate = input.config.sample_rate;
753 output.frameCount = input.frameCount;
754 output.notificationFrameCount = input.notificationFrameCount;
755 output.flags = input.flags;
756
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700757 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
758 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800759 &output.frameCount, &output.notificationFrameCount,
760 input.notificationsPerBuffer, input.speed,
761 input.sharedBuffer, sessionId, &output.flags,
762 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800763 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700764 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700765
Eric Laurent21da6472017-11-09 16:29:26 -0800766 output.afFrameCount = thread->frameCount();
767 output.afSampleRate = thread->sampleRate();
768 output.afLatencyMs = thread->latency();
769
Eric Laurent39e94f82010-07-28 01:32:47 -0700770 // move effect chain to this output thread if an effect on same session was waiting
771 // for a track to be created
772 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700773 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700774 Mutex::Autolock _dl(thread->mLock);
775 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800776 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700777 }
Eric Laurenta011e352012-03-29 15:51:43 -0700778
779 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700780 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800781 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700782 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700783 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700784 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700785 } else {
786 mPendingSyncEvents[i]->cancel();
787 }
Eric Laurenta011e352012-03-29 15:51:43 -0700788 mPendingSyncEvents.removeAt(i);
789 i--;
790 }
791 }
792 }
Glenn Kastene198c362013-08-13 09:13:36 -0700793
Eric Laurent21da6472017-11-09 16:29:26 -0800794 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 }
Glenn Kastene198c362013-08-13 09:13:36 -0700796
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700797 if (lStatus != NO_ERROR) {
798 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700799 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700800 // Don't hold mClientLock when releasing the reference on the track as the
801 // destructor will acquire it.
802 {
803 Mutex::Autolock _cl(mClientLock);
804 client.clear();
805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700807 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 }
809
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700810 // return handle to client
811 trackHandle = new TrackHandle(track);
812
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800814 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
815 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
816 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700817 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 return trackHandle;
819}
820
Glenn Kasten2c073da2016-02-26 09:14:08 -0800821uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822{
823 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800824 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800826 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 return 0;
828 }
829 return thread->sampleRate();
830}
831
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800832audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833{
834 Mutex::Autolock _l(mLock);
835 PlaybackThread *thread = checkPlaybackThread_l(output);
836 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000837 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800838 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839 }
840 return thread->format();
841}
842
Glenn Kasten2c073da2016-02-26 09:14:08 -0800843size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844{
845 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800846 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800848 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 return 0;
850 }
Glenn Kasten58912562012-04-03 10:45:00 -0700851 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
852 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 return thread->frameCount();
854}
855
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700856size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
857{
858 Mutex::Autolock _l(mLock);
859 ThreadBase *thread = checkThread_l(ioHandle);
860 if (thread == NULL) {
861 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
862 return 0;
863 }
864 return thread->frameCountHAL();
865}
866
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800867uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868{
869 Mutex::Autolock _l(mLock);
870 PlaybackThread *thread = checkPlaybackThread_l(output);
871 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800872 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873 return 0;
874 }
875 return thread->latency();
876}
877
878status_t AudioFlinger::setMasterVolume(float value)
879{
Eric Laurenta1884f92011-08-23 08:25:03 -0700880 status_t ret = initCheck();
881 if (ret != NO_ERROR) {
882 return ret;
883 }
884
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885 // check calling permissions
886 if (!settingsAllowed()) {
887 return PERMISSION_DENIED;
888 }
889
Eric Laurenta4c5a552012-03-29 10:12:40 -0700890 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700891 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700892
John Grossmanee578c02012-07-23 17:05:46 -0700893 // Set master volume in the HALs which support it.
894 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
895 AutoMutex lock(mHardwareLock);
896 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800897
John Grossmanee578c02012-07-23 17:05:46 -0700898 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
899 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700900 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800901 }
John Grossmanee578c02012-07-23 17:05:46 -0700902 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904
John Grossmanee578c02012-07-23 17:05:46 -0700905 // Now set the master volume in each playback thread. Playback threads
906 // assigned to HALs which do not have master volume support will apply
907 // master volume during the mix operation. Threads with HALs which do
908 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700909 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
910 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
911 continue;
912 }
John Grossmanee578c02012-07-23 17:05:46 -0700913 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915
916 return NO_ERROR;
917}
918
Glenn Kastenf78aee72012-01-04 11:00:47 -0800919status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920{
Eric Laurenta1884f92011-08-23 08:25:03 -0700921 status_t ret = initCheck();
922 if (ret != NO_ERROR) {
923 return ret;
924 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925
926 // check calling permissions
927 if (!settingsAllowed()) {
928 return PERMISSION_DENIED;
929 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800930 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000931 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 return BAD_VALUE;
933 }
934
935 { // scope for the lock
936 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700937 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700939 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 mHardwareStatus = AUDIO_HW_IDLE;
941 }
942
943 if (NO_ERROR == ret) {
944 Mutex::Autolock _l(mLock);
945 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800946 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700947 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 }
949
950 return ret;
951}
952
953status_t AudioFlinger::setMicMute(bool state)
954{
Eric Laurenta1884f92011-08-23 08:25:03 -0700955 status_t ret = initCheck();
956 if (ret != NO_ERROR) {
957 return ret;
958 }
959
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960 // check calling permissions
961 if (!settingsAllowed()) {
962 return PERMISSION_DENIED;
963 }
964
965 AutoMutex lock(mHardwareLock);
966 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700967 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700968 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
969 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700970 if (result != NO_ERROR) {
971 ret = result;
972 }
973 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974 mHardwareStatus = AUDIO_HW_IDLE;
975 return ret;
976}
977
978bool AudioFlinger::getMicMute() const
979{
Eric Laurenta1884f92011-08-23 08:25:03 -0700980 status_t ret = initCheck();
981 if (ret != NO_ERROR) {
982 return false;
983 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800984 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700985 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800986 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800988 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700989 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
990 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800991 if (result == NO_ERROR) {
992 mute = mute && state;
993 }
994 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800996
997 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998}
999
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001000void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1001{
1002 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1003
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001004 AutoMutex lock(mLock);
1005 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001006 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1007 }
1008 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1009 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001010 }
1011}
1012
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013status_t AudioFlinger::setMasterMute(bool muted)
1014{
John Grossmand8f178d2012-07-20 14:51:35 -07001015 status_t ret = initCheck();
1016 if (ret != NO_ERROR) {
1017 return ret;
1018 }
1019
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020 // check calling permissions
1021 if (!settingsAllowed()) {
1022 return PERMISSION_DENIED;
1023 }
1024
John Grossmanee578c02012-07-23 17:05:46 -07001025 Mutex::Autolock _l(mLock);
1026 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001027
John Grossmanee578c02012-07-23 17:05:46 -07001028 // Set master mute in the HALs which support it.
1029 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1030 AutoMutex lock(mHardwareLock);
1031 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001032
John Grossmanee578c02012-07-23 17:05:46 -07001033 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1034 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001035 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001036 }
John Grossmanee578c02012-07-23 17:05:46 -07001037 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001038 }
1039
John Grossmanee578c02012-07-23 17:05:46 -07001040 // Now set the master mute in each playback thread. Playback threads
1041 // assigned to HALs which do not have master mute support will apply master
1042 // mute during the mix operation. Threads with HALs which do support master
1043 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001044 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1045 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1046 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001047 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048
1049 return NO_ERROR;
1050}
1051
1052float AudioFlinger::masterVolume() const
1053{
Glenn Kasten98067102011-12-13 11:47:54 -08001054 Mutex::Autolock _l(mLock);
1055 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056}
1057
1058bool AudioFlinger::masterMute() const
1059{
Glenn Kasten98067102011-12-13 11:47:54 -08001060 Mutex::Autolock _l(mLock);
1061 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062}
1063
John Grossman4ff14ba2012-02-08 16:37:41 -08001064float AudioFlinger::masterVolume_l() const
1065{
John Grossman4ff14ba2012-02-08 16:37:41 -08001066 return mMasterVolume;
1067}
1068
John Grossmand8f178d2012-07-20 14:51:35 -07001069bool AudioFlinger::masterMute_l() const
1070{
John Grossmanee578c02012-07-23 17:05:46 -07001071 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001072}
1073
Eric Laurent223fd5c2014-11-11 13:43:36 -08001074status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1075{
1076 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001077 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001078 return BAD_VALUE;
1079 }
1080 pid_t caller = IPCThreadState::self()->getCallingPid();
1081 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001082 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001083 return PERMISSION_DENIED;
1084 }
1085
1086 return NO_ERROR;
1087}
1088
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001089status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1090 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092 // check calling permissions
1093 if (!settingsAllowed()) {
1094 return PERMISSION_DENIED;
1095 }
1096
Eric Laurent223fd5c2014-11-11 13:43:36 -08001097 status_t status = checkStreamType(stream);
1098 if (status != NO_ERROR) {
1099 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 }
Eric Laurent98e38192018-02-15 18:31:53 -08001101 if (output == AUDIO_IO_HANDLE_NONE) {
1102 return BAD_VALUE;
1103 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001104 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105
1106 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001107 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1108 if (volumeInterface == NULL) {
1109 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110 }
Eric Laurent98e38192018-02-15 18:31:53 -08001111 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112
1113 return NO_ERROR;
1114}
1115
Glenn Kastenfff6d712012-01-12 16:38:12 -08001116status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117{
1118 // check calling permissions
1119 if (!settingsAllowed()) {
1120 return PERMISSION_DENIED;
1121 }
1122
Eric Laurent223fd5c2014-11-11 13:43:36 -08001123 status_t status = checkStreamType(stream);
1124 if (status != NO_ERROR) {
1125 return status;
1126 }
1127 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1128
1129 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001130 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 return BAD_VALUE;
1132 }
1133
Eric Laurent93575202011-01-18 18:39:02 -08001134 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001136 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1137 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1138 volumeInterfaces[i]->setStreamMute(stream, muted);
1139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140
1141 return NO_ERROR;
1142}
1143
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001144float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001146 status_t status = checkStreamType(stream);
1147 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 return 0.0f;
1149 }
Eric Laurent98e38192018-02-15 18:31:53 -08001150 if (output == AUDIO_IO_HANDLE_NONE) {
1151 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152 }
1153
Eric Laurent98e38192018-02-15 18:31:53 -08001154 AutoMutex lock(mLock);
1155 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1156 if (volumeInterface == NULL) {
1157 return 0.0f;
1158 }
1159
1160 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161}
1162
Glenn Kastenfff6d712012-01-12 16:38:12 -08001163bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001165 status_t status = checkStreamType(stream);
1166 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 return true;
1168 }
1169
Glenn Kasten6637baa2012-01-09 09:40:36 -08001170 AutoMutex lock(mLock);
1171 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172}
1173
Eric Laurent054d9d32015-04-24 08:48:48 -07001174
1175void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1176{
1177 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1178 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1179 }
1180}
1181
Eric Laurentf1047e82018-04-16 19:18:20 -07001182// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1183// Some keys are used for audio routing and audio path configuration and should be reserved for use
1184// by audio policy and audio flinger for functional, privacy and security reasons.
1185void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1186{
1187 static const String8 kReservedParameters[] = {
1188 String8(AudioParameter::keyRouting),
1189 String8(AudioParameter::keySamplingRate),
1190 String8(AudioParameter::keyFormat),
1191 String8(AudioParameter::keyChannels),
1192 String8(AudioParameter::keyFrameCount),
1193 String8(AudioParameter::keyInputSource),
1194 String8(AudioParameter::keyMonoOutput),
1195 String8(AudioParameter::keyStreamConnect),
1196 String8(AudioParameter::keyStreamDisconnect),
1197 String8(AudioParameter::keyStreamSupportedFormats),
1198 String8(AudioParameter::keyStreamSupportedChannels),
1199 String8(AudioParameter::keyStreamSupportedSamplingRates),
1200 };
1201
1202 // multiuser friendly app ID check for requests coming from audioserver
1203 if (multiuser_get_app_id(callingUid) == AID_AUDIOSERVER) {
1204 return;
1205 }
1206
1207 AudioParameter param = AudioParameter(keyValuePairs);
1208 String8 value;
1209 for (auto& key : kReservedParameters) {
1210 if (param.get(key, value) == NO_ERROR) {
1211 ALOGW("%s: filtering key %s value %s from uid %d",
1212 __func__, key.string(), value.string(), callingUid);
1213 param.remove(key);
1214 }
1215 }
1216 keyValuePairs = param.toString();
1217}
1218
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001219status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220{
Eric Laurentf1047e82018-04-16 19:18:20 -07001221 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1222 ioHandle, keyValuePairs.string(),
1223 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001224
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 // check calling permissions
1226 if (!settingsAllowed()) {
1227 return PERMISSION_DENIED;
1228 }
1229
Eric Laurentf1047e82018-04-16 19:18:20 -07001230 String8 filteredKeyValuePairs = keyValuePairs;
1231 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1232
1233 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1234
Glenn Kasten142f5192014-03-25 17:44:59 -07001235 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1236 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001237 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001238 // result will remain NO_INIT if no audio device is present
1239 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001240 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001241 AutoMutex lock(mHardwareLock);
1242 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1243 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001244 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001245 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001246 // return success if at least one audio device accepts the parameters as not all
1247 // HALs are requested to support all parameters. If no audio device supports the
1248 // requested parameters, the last error is reported.
1249 if (final_result != NO_ERROR) {
1250 final_result = result;
1251 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001252 }
1253 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001254 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001255 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001256 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001257 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001258 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1259 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001260 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001261 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001262 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001263 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001264 }
1265 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001266 String8 screenState;
1267 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001268 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001269 if (isOff != (AudioFlinger::mScreenState & 1)) {
1270 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001271 }
1272 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001273 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 }
1275
1276 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1277 // and the thread is exited once the lock is released
1278 sp<ThreadBase> thread;
1279 {
1280 Mutex::Autolock _l(mLock);
1281 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001282 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001284 if (thread == 0) {
1285 thread = checkMmapThread_l(ioHandle);
1286 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001287 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001288 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001289 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001290 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001291 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1292 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001293 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295 }
1296 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001297 if (thread != 0) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001298 return thread->setParameters(filteredKeyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299 }
1300 return BAD_VALUE;
1301}
1302
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001303String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001305 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1306 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307
Eric Laurenta4c5a552012-03-29 10:12:40 -07001308 Mutex::Autolock _l(mLock);
1309
Glenn Kasten142f5192014-03-25 17:44:59 -07001310 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001311 String8 out_s8;
1312
Dima Zavin799a70e2011-04-18 16:57:27 -07001313 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001314 String8 s;
1315 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001316 {
1317 AutoMutex lock(mHardwareLock);
1318 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001319 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1320 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001321 mHardwareStatus = AUDIO_HW_IDLE;
1322 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001323 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001324 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001325 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001326 }
1327
Eric Laurent6acd1d42017-01-04 14:23:29 -08001328 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1329 if (thread == NULL) {
1330 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1331 if (thread == NULL) {
1332 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1333 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001334 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001335 }
1336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001338 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339}
1340
Glenn Kastendd8104c2012-07-02 12:42:44 -07001341size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1342 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001343{
Eric Laurenta1884f92011-08-23 08:25:03 -07001344 status_t ret = initCheck();
1345 if (ret != NO_ERROR) {
1346 return 0;
1347 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001348 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001349 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001350 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001351 return 0;
1352 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001353
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001354 AutoMutex lock(mHardwareLock);
1355 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001356 audio_config_t config, proposed;
1357 memset(&proposed, 0, sizeof(proposed));
1358 proposed.sample_rate = sampleRate;
1359 proposed.channel_mask = channelMask;
1360 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001361
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001362 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001363 size_t frames;
1364 for (;;) {
1365 // Note: config is currently a const parameter for get_input_buffer_size()
1366 // but we use a copy from proposed in case config changes from the call.
1367 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001368 status_t result = dev->getInputBufferSize(&config, &frames);
1369 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001370 break; // hal success, config is the result
1371 }
1372 // change one parameter of the configuration each iteration to a more "common" value
1373 // to see if the device will support it.
1374 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1375 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1376 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1377 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1378 } else {
1379 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1380 "format %#x, channelMask 0x%X",
1381 sampleRate, format, channelMask);
1382 break; // retries failed, break out of loop with frames == 0.
1383 }
1384 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001385 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001386 if (frames > 0 && config.sample_rate != sampleRate) {
1387 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1388 }
1389 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390}
1391
Glenn Kasten5f972c02014-01-13 09:59:31 -08001392uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394 Mutex::Autolock _l(mLock);
1395
1396 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1397 if (recordThread != NULL) {
1398 return recordThread->getInputFramesLost();
1399 }
1400 return 0;
1401}
1402
1403status_t AudioFlinger::setVoiceVolume(float value)
1404{
Eric Laurenta1884f92011-08-23 08:25:03 -07001405 status_t ret = initCheck();
1406 if (ret != NO_ERROR) {
1407 return ret;
1408 }
1409
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 // check calling permissions
1411 if (!settingsAllowed()) {
1412 return PERMISSION_DENIED;
1413 }
1414
1415 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001416 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001417 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001418 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001419 mHardwareStatus = AUDIO_HW_IDLE;
1420
1421 return ret;
1422}
1423
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001424status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001425 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 Mutex::Autolock _l(mLock);
1428
1429 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1430 if (playbackThread != NULL) {
1431 return playbackThread->getRenderPosition(halFrames, dspFrames);
1432 }
1433
1434 return BAD_VALUE;
1435}
1436
1437void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1438{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001440 if (client == 0) {
1441 return;
1442 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001443 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001444 {
1445 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001446 if (mNotificationClients.indexOfKey(pid) < 0) {
1447 sp<NotificationClient> notificationClient = new NotificationClient(this,
1448 client,
1449 pid);
1450 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451
Eric Laurent021cf962014-05-13 10:18:14 -07001452 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453
Marco Nelissen06b46062014-11-14 07:58:25 -08001454 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001455 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001456 }
1457 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458
Eric Laurent021cf962014-05-13 10:18:14 -07001459 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001460 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001461 // the config change is always sent from playback or record threads to avoid deadlock
1462 // with AudioSystem::gLock
1463 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001464 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001467 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001468 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 }
1470}
1471
1472void AudioFlinger::removeNotificationClient(pid_t pid)
1473{
1474 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001475 {
1476 Mutex::Autolock _cl(mClientLock);
1477 mNotificationClients.removeItem(pid);
1478 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001479
Steve Block3856b092011-10-20 11:56:00 +01001480 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001481 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001482 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001483 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001484 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001485 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001486 if (ref->mPid == pid) {
1487 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001488 mAudioSessionRefs.removeAt(i);
1489 delete ref;
1490 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001491 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001492 } else {
1493 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001494 }
1495 }
1496 if (removed) {
1497 purgeStaleEffects_l();
1498 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499}
1500
Eric Laurent73e26b62015-04-27 16:55:58 -07001501void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001502 const sp<AudioIoDescriptor>& ioDesc,
1503 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504{
Eric Laurent021cf962014-05-13 10:18:14 -07001505 Mutex::Autolock _l(mClientLock);
1506 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001508 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1509 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 }
1512}
1513
Eric Laurent021cf962014-05-13 10:18:14 -07001514// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515void AudioFlinger::removeClient_l(pid_t pid)
1516{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001517 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001518 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519 mClients.removeItem(pid);
1520}
1521
Eric Laurent717e1282012-06-29 16:36:52 -07001522// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001523sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1524 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001525{
1526 sp<PlaybackThread> thread;
1527
1528 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1529 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1530 ALOG_ASSERT(thread == 0);
1531 thread = mPlaybackThreads.valueAt(i);
1532 }
1533 }
1534
1535 return thread;
1536}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539
1540// ----------------------------------------------------------------------------
1541
1542AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1543 : RefBase(),
1544 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001545 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546{
Andy Hung6f248bb2018-01-23 14:04:37 -08001547 mMemoryDealer = new MemoryDealer(
1548 audioFlinger->getClientSharedHeapSize(),
1549 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550}
1551
Eric Laurent021cf962014-05-13 10:18:14 -07001552// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553AudioFlinger::Client::~Client()
1554{
1555 mAudioFlinger->removeClient_l(mPid);
1556}
1557
Glenn Kasten435dbe62012-01-30 10:15:48 -08001558sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559{
1560 return mMemoryDealer;
1561}
1562
1563// ----------------------------------------------------------------------------
1564
1565AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1566 const sp<IAudioFlingerClient>& client,
1567 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001568 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569{
1570}
1571
1572AudioFlinger::NotificationClient::~NotificationClient()
1573{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574}
1575
Glenn Kasten0f11b512014-01-31 16:18:54 -08001576void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577{
1578 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001579 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580}
1581
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001582// ----------------------------------------------------------------------------
1583AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1584 : mPendingRequests(false) {}
1585
1586
1587void AudioFlinger::MediaLogNotifier::requestMerge() {
1588 AutoMutex _l(mMutex);
1589 mPendingRequests = true;
1590 mCond.signal();
1591}
1592
1593bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001594 // Should already have been checked, but just in case
1595 if (sMediaLogService == 0) {
1596 return false;
1597 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001598 // Wait until there are pending requests
1599 {
1600 AutoMutex _l(mMutex);
1601 mPendingRequests = false; // to ignore past requests
1602 while (!mPendingRequests) {
1603 mCond.wait(mMutex);
1604 // TODO may also need an exitPending check
1605 }
1606 mPendingRequests = false;
1607 }
1608 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001609 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001610 usleep(kPostTriggerSleepPeriod);
1611 return true;
1612}
1613
1614void AudioFlinger::requestLogMerge() {
1615 mMediaLogNotifier->requestMerge();
1616}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617
1618// ----------------------------------------------------------------------------
1619
Eric Laurentf14db3c2017-12-08 14:20:36 -08001620sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1621 CreateRecordOutput& output,
1622 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623{
1624 sp<RecordThread::RecordTrack> recordTrack;
1625 sp<RecordHandle> recordHandle;
1626 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001628 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001629 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630
Eric Laurentf14db3c2017-12-08 14:20:36 -08001631 output.cblk.clear();
1632 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001633 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001634
Eric Laurentf14db3c2017-12-08 14:20:36 -08001635 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001636 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001637 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001638 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001639 ALOGW_IF(clientUid != callingUid,
1640 "%s uid %d tried to pass itself off as %d",
1641 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001642 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001643 updatePid = true;
1644 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001645 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001646 if (updatePid) {
1647 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001648 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001649 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001650 __func__, callingUid, callingPid, clientPid);
1651 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001652 }
1653
Andy Hung6770c6f2015-04-07 13:43:36 -07001654 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001655 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1656 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001657 lStatus = BAD_VALUE;
1658 goto Exit;
1659 }
1660
Glenn Kasten53b5d092014-02-05 10:00:23 -08001661 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001662 if (!audio_is_input_channel(input.config.channel_mask)) {
1663 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001664 lStatus = BAD_VALUE;
1665 goto Exit;
1666 }
1667
Eric Laurentf14db3c2017-12-08 14:20:36 -08001668 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1669 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1670 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1671 lStatus = BAD_VALUE;
1672 goto Exit;
1673 }
1674
1675 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001676 output.selectedDeviceId = input.selectedDeviceId;
1677 output.flags = input.flags;
1678
1679 client = registerPid(clientPid);
1680
1681 // Not a conventional loop, but a retry loop for at most two iterations total.
1682 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1683 // Exits loop via break on no error of got exit on error
1684 // The sp<> references will be dropped when re-entering scope.
1685 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1686 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001687 // release previously opened input if retrying.
1688 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1689 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001690 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001691 output.inputId = AUDIO_IO_HANDLE_NONE;
Eric Laurent77881cd2018-02-09 16:01:31 -08001692 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001693 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001694 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1695 sessionId,
1696 // FIXME compare to AudioTrack
1697 clientPid,
1698 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001699 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001700 &input.config,
1701 output.flags, &output.selectedDeviceId, &portId);
1702
Glenn Kasten05997e22014-03-13 15:08:33 -07001703 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001705 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001707 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 lStatus = BAD_VALUE;
1709 goto Exit;
1710 }
1711
Eric Laurentf14db3c2017-12-08 14:20:36 -08001712 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713
Eric Laurentf14db3c2017-12-08 14:20:36 -08001714 output.sampleRate = input.config.sample_rate;
1715 output.frameCount = input.frameCount;
1716 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001717
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001718 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001719 input.config.format, input.config.channel_mask,
1720 &output.frameCount, sessionId,
1721 &output.notificationFrameCount,
1722 clientUid, &output.flags,
1723 input.clientInfo.clientTid,
1724 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001725 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001726
Eric Laurentf14db3c2017-12-08 14:20:36 -08001727 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1728 // audio policy manager without FAST constraint
1729 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001730 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001731 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001732
1733 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001734 goto Exit;
1735 }
1736
1737 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1738 // session and move it to this thread.
1739 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1740 if (chain != 0) {
1741 Mutex::Autolock _l(thread->mLock);
1742 thread->addEffectChain_l(chain);
1743 }
1744 break;
1745 }
1746 // End of retry loop.
1747 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 }
Glenn Kastene198c362013-08-13 09:13:36 -07001749
Eric Laurentf14db3c2017-12-08 14:20:36 -08001750 output.cblk = recordTrack->getCblk();
1751 output.buffers = recordTrack->getBuffers();
1752
1753 // return handle to client
1754 recordHandle = new RecordHandle(recordTrack);
1755
1756Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001757 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001758 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001759 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001760 // Don't hold mClientLock when releasing the reference on the track as the
1761 // destructor will acquire it.
1762 {
1763 Mutex::Autolock _cl(mClientLock);
1764 client.clear();
1765 }
Eric Laurent896c9672017-12-08 14:08:45 -08001766 recordTrack.clear();
1767 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001768 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770 }
1771
Glenn Kasten9156ef32013-08-06 15:39:08 -07001772 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 return recordHandle;
1774}
1775
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001776
1777
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778// ----------------------------------------------------------------------------
1779
Eric Laurenta4c5a552012-03-29 10:12:40 -07001780audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1781{
Eric Laurent44622db2014-08-01 19:00:33 -07001782 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001783 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001784 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001785 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001786 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001787 }
1788 Mutex::Autolock _l(mLock);
1789 return loadHwModule_l(name);
1790}
1791
1792// loadHwModule_l() must be called with AudioFlinger::mLock held
1793audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1794{
1795 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1796 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1797 ALOGW("loadHwModule() module %s already loaded", name);
1798 return mAudioHwDevs.keyAt(i);
1799 }
1800 }
1801
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001802 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001803
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001804 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001805 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001806 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001807 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001808 }
1809
1810 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001811 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001812 mHardwareStatus = AUDIO_HW_IDLE;
1813 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001814 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001815 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001816 }
1817
John Grossmanee578c02012-07-23 17:05:46 -07001818 // Check and cache this HAL's level of support for master mute and master
1819 // volume. If this is the first HAL opened, and it supports the get
1820 // methods, use the initial values provided by the HAL as the current
1821 // master mute and volume settings.
1822
1823 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1824 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001825 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001826
1827 if (0 == mAudioHwDevs.size()) {
1828 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001829 float mv;
1830 if (OK == dev->getMasterVolume(&mv)) {
1831 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001832 }
1833
1834 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001835 bool mm;
1836 if (OK == dev->getMasterMute(&mm)) {
1837 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001838 }
1839 }
1840
Eric Laurenta4c5a552012-03-29 10:12:40 -07001841 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001842 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001843 flags = static_cast<AudioHwDevice::Flags>(flags |
1844 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1845 }
1846
1847 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001848 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001849 flags = static_cast<AudioHwDevice::Flags>(flags |
1850 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1851 }
1852
Eric Laurenta4c5a552012-03-29 10:12:40 -07001853 mHardwareStatus = AUDIO_HW_IDLE;
1854 }
1855
Glenn Kastena13cde92016-03-28 15:26:02 -07001856 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001857 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001858
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001859 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001860
1861 return handle;
1862
1863}
1864
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001865// ----------------------------------------------------------------------------
1866
Glenn Kasten3b16c762012-11-14 08:44:39 -08001867uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001868{
1869 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001870 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001871 return thread != NULL ? thread->sampleRate() : 0;
1872}
1873
Glenn Kastene33054e2012-11-14 12:54:39 -08001874size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001875{
1876 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001877 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001878 return thread != NULL ? thread->frameCountHAL() : 0;
1879}
1880
1881// ----------------------------------------------------------------------------
1882
Andy Hung6f248bb2018-01-23 14:04:37 -08001883status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001884{
1885 uid_t uid = IPCThreadState::self()->getCallingUid();
1886 if (uid != AID_SYSTEM) {
1887 return PERMISSION_DENIED;
1888 }
1889 Mutex::Autolock _l(mLock);
1890 if (mIsDeviceTypeKnown) {
1891 return INVALID_OPERATION;
1892 }
1893 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001894 mTotalMemory = totalMemory;
1895 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1896 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1897 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1898 // though actual setting is determined through device configuration.
1899 constexpr int64_t GB = 1024 * 1024 * 1024;
1900 mClientSharedHeapSize =
1901 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1902 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1903 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1904 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1905 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001906 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001907
1908 // TODO: Cache the client shared heap size in a persistent property.
1909 // It's possible that a native process or Java service or app accesses audioserver
1910 // after it is registered by system server, but before AudioService updates
1911 // the memory info. This would occur immediately after boot or an audioserver
1912 // crash and restore. Before update from AudioService, the client would get the
1913 // minimum heap size.
1914
1915 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1916 (isLowRamDevice ? "true" : "false"),
1917 (long long)mTotalMemory,
1918 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001919 return NO_ERROR;
1920}
1921
Andy Hung6f248bb2018-01-23 14:04:37 -08001922size_t AudioFlinger::getClientSharedHeapSize() const
1923{
1924 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1925 if (heapSizeInBytes != 0) { // read-only property overrides all.
1926 return heapSizeInBytes;
1927 }
1928 return mClientSharedHeapSize;
1929}
1930
Eric Laurent93c3d412014-08-01 14:48:35 -07001931audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1932{
1933 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001934
1935 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1936 if (index >= 0) {
1937 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1938 mHwAvSyncIds.valueAt(index), sessionId);
1939 return mHwAvSyncIds.valueAt(index);
1940 }
1941
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001942 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001943 if (dev == NULL) {
1944 return AUDIO_HW_SYNC_INVALID;
1945 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001946 String8 reply;
1947 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001948 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001949 param = AudioParameter(reply);
1950 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001951
1952 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001953 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001954 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1955 return AUDIO_HW_SYNC_INVALID;
1956 }
1957
1958 // allow only one session for a given HW A/V sync ID.
1959 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1960 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1961 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1962 value, mHwAvSyncIds.keyAt(i));
1963 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001964 break;
1965 }
1966 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001967
1968 mHwAvSyncIds.add(sessionId, value);
1969
1970 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1971 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1972 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001973 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001974 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001975 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001976 thread->setParameters(param.toString());
1977 break;
1978 }
1979 }
1980
1981 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1982 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001983}
1984
Eric Laurent72e3f392015-05-20 14:43:50 -07001985status_t AudioFlinger::systemReady()
1986{
1987 Mutex::Autolock _l(mLock);
1988 ALOGI("%s", __FUNCTION__);
1989 if (mSystemReady) {
1990 ALOGW("%s called twice", __FUNCTION__);
1991 return NO_ERROR;
1992 }
1993 mSystemReady = true;
1994 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1995 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1996 thread->systemReady();
1997 }
1998 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1999 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2000 thread->systemReady();
2001 }
2002 return NO_ERROR;
2003}
2004
jiabin46a76fa2018-01-05 10:18:21 -08002005status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2006{
jiabin9ff780e2018-03-19 18:19:52 -07002007 AutoMutex lock(mHardwareLock);
2008 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2009 status_t status = dev->getMicrophones(microphones);
2010 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002011}
2012
Eric Laurentfa90e842014-10-17 18:12:31 -07002013// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2014void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2015{
2016 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2017 if (index >= 0) {
2018 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2019 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2020 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002021 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002022 thread->setParameters(param.toString());
2023 }
2024}
2025
2026
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002027// ----------------------------------------------------------------------------
2028
Eric Laurent83b88082014-06-20 18:31:16 -07002029
Eric Laurent6acd1d42017-01-04 14:23:29 -08002030sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002031 audio_io_handle_t *output,
2032 audio_config_t *config,
2033 audio_devices_t devices,
2034 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002035 audio_output_flags_t flags)
2036{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002037 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002038 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002039 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002040 }
2041
Eric Laurentcf2c0212014-07-25 16:20:43 -07002042 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002043 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2044 } else {
2045 // Audio Policy does not currently request a specific output handle.
2046 // If this is ever needed, see openInput_l() for example code.
2047 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2048 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002049 }
Eric Laurent83b88082014-06-20 18:31:16 -07002050
2051 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2052
Eric Laurent83b88082014-06-20 18:31:16 -07002053 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002054 // This if statement allows overriding the audio policy settings
2055 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2056 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2057 // Check only for Normal Mixing mode
2058 if (kEnableExtendedPrecision) {
2059 // Specify format (uncomment one below to choose)
2060 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2061 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2062 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2063 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002064 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002065 }
2066 if (kEnableExtendedChannels) {
2067 // Specify channel mask (uncomment one below to choose)
2068 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2069 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2070 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2071 }
Eric Laurent83b88082014-06-20 18:31:16 -07002072 }
2073
Phil Burk062e67a2015-02-11 13:40:50 -08002074 AudioStreamOut *outputStream = NULL;
2075 status_t status = outHwDev->openOutputStream(
2076 &outputStream,
2077 *output,
2078 devices,
2079 flags,
2080 config,
2081 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002082
2083 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002084
Phil Burk062e67a2015-02-11 13:40:50 -08002085 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002086 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2087 sp<MmapPlaybackThread> thread =
2088 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2089 devices, AUDIO_DEVICE_NONE, mSystemReady);
2090 mMmapThreads.add(*output, thread);
2091 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2092 *output, thread.get());
2093 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002094 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002095 sp<PlaybackThread> thread;
2096 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2097 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2098 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2099 *output, thread.get());
2100 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2101 || !isValidPcmSinkFormat(config->format)
2102 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2103 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2104 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2105 *output, thread.get());
2106 } else {
2107 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2108 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2109 *output, thread.get());
2110 }
2111 mPlaybackThreads.add(*output, thread);
2112 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002113 }
Eric Laurent83b88082014-06-20 18:31:16 -07002114 }
2115
2116 return 0;
2117}
2118
Eric Laurentcf2c0212014-07-25 16:20:43 -07002119status_t AudioFlinger::openOutput(audio_module_handle_t module,
2120 audio_io_handle_t *output,
2121 audio_config_t *config,
2122 audio_devices_t *devices,
2123 const String8& address,
2124 uint32_t *latencyMs,
2125 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002127 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2128 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002129 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002130 (devices != NULL) ? *devices : 0,
2131 config->sample_rate,
2132 config->format,
2133 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002134 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002136 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002137 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002139
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 Mutex::Autolock _l(mLock);
2141
Eric Laurent6acd1d42017-01-04 14:23:29 -08002142 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002143 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002144 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2145 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2146 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147
Eric Laurent6acd1d42017-01-04 14:23:29 -08002148 // notify client processes of the new output creation
2149 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002150
Eric Laurent6acd1d42017-01-04 14:23:29 -08002151 // the first primary output opened designates the primary hw device
2152 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002153 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002154 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002155
Eric Laurent6acd1d42017-01-04 14:23:29 -08002156 AutoMutex lock(mHardwareLock);
2157 mHardwareStatus = AUDIO_HW_SET_MODE;
2158 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2159 mHardwareStatus = AUDIO_HW_IDLE;
2160 }
2161 } else {
2162 MmapThread *mmapThread = (MmapThread *)thread.get();
2163 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002164 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002165 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 }
2167
Eric Laurentcf2c0212014-07-25 16:20:43 -07002168 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169}
2170
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002171audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2172 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173{
2174 Mutex::Autolock _l(mLock);
2175 MixerThread *thread1 = checkMixerThread_l(output1);
2176 MixerThread *thread2 = checkMixerThread_l(output2);
2177
2178 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002179 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2180 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002181 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 }
2183
Glenn Kasteneeecb982016-02-26 10:44:04 -08002184 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002185 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186 thread->addOutputTrack(thread2);
2187 mPlaybackThreads.add(id, thread);
2188 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002189 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 return id;
2191}
2192
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002193status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194{
Glenn Kastend96c5722012-04-25 13:44:49 -07002195 return closeOutput_nonvirtual(output);
2196}
2197
2198status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2199{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 // keep strong reference on the playback thread so that
2201 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002202 sp<PlaybackThread> playbackThread;
2203 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 {
2205 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002206 playbackThread = checkPlaybackThread_l(output);
2207 if (playbackThread != NULL) {
2208 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209
Eric Laurent6acd1d42017-01-04 14:23:29 -08002210 if (playbackThread->type() == ThreadBase::MIXER) {
2211 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2212 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2213 DuplicatingThread *dupThread =
2214 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2215 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2216 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217 }
2218 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002219
2220
Eric Laurent6acd1d42017-01-04 14:23:29 -08002221 mPlaybackThreads.removeItem(output);
2222 // save all effects to the default thread
2223 if (mPlaybackThreads.size()) {
2224 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2225 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002226 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002227 Mutex::Autolock _dl(dstThread->mLock);
2228 Mutex::Autolock _sl(playbackThread->mLock);
2229 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2230 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002231 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2232 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 }
2235 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002236 } else {
2237 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2238 if (mmapThread == 0) {
2239 return BAD_VALUE;
2240 }
2241 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002242 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002244 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2245 ioDesc->mIoHandle = output;
2246 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002248 // The thread entity (active unit of execution) is no longer running here,
2249 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250
Eric Laurent6acd1d42017-01-04 14:23:29 -08002251 if (playbackThread != 0) {
2252 playbackThread->exit();
2253 if (!playbackThread->isDuplicating()) {
2254 closeOutputFinish(playbackThread);
2255 }
2256 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002257 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002258 mmapThread->exit();
2259 AudioStreamOut *out = mmapThread->clearOutput();
2260 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2261 // from now on thread->mOutput is NULL
2262 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 }
2264 return NO_ERROR;
2265}
2266
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002267void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002268{
2269 AudioStreamOut *out = thread->clearOutput();
2270 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2271 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002272 delete out;
2273}
2274
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002275void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002276{
2277 mPlaybackThreads.removeItem(thread->mId);
2278 thread->exit();
2279 closeOutputFinish(thread);
2280}
2281
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002282status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283{
2284 Mutex::Autolock _l(mLock);
2285 PlaybackThread *thread = checkPlaybackThread_l(output);
2286
2287 if (thread == NULL) {
2288 return BAD_VALUE;
2289 }
2290
Steve Block3856b092011-10-20 11:56:00 +01002291 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 thread->suspend();
2293
2294 return NO_ERROR;
2295}
2296
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002297status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298{
2299 Mutex::Autolock _l(mLock);
2300 PlaybackThread *thread = checkPlaybackThread_l(output);
2301
2302 if (thread == NULL) {
2303 return BAD_VALUE;
2304 }
2305
Steve Block3856b092011-10-20 11:56:00 +01002306 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307
2308 thread->restore();
2309
2310 return NO_ERROR;
2311}
2312
Eric Laurentcf2c0212014-07-25 16:20:43 -07002313status_t AudioFlinger::openInput(audio_module_handle_t module,
2314 audio_io_handle_t *input,
2315 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002316 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002317 const String8& address,
2318 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002319 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320{
Eric Laurent83b88082014-06-20 18:31:16 -07002321 Mutex::Autolock _l(mLock);
2322
Glenn Kastene7d66712015-03-05 13:46:52 -08002323 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002324 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002325 }
2326
Eric Laurent6acd1d42017-01-04 14:23:29 -08002327 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002328
2329 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002330 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002331 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002332 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002334 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002335}
Dima Zavin799a70e2011-04-18 16:57:27 -07002336
Eric Laurent6acd1d42017-01-04 14:23:29 -08002337sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002338 audio_io_handle_t *input,
2339 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002340 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002341 const String8& address,
2342 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002343 audio_input_flags_t flags)
2344{
Glenn Kastene7d66712015-03-05 13:46:52 -08002345 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002346 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002347 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002348 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002349 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002350
Glenn Kasteneeecb982016-02-26 10:44:04 -08002351 // Audio Policy can request a specific handle for hardware hotword.
2352 // The goal here is not to re-open an already opened input.
2353 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002354 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002355 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2356 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2357 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2358 return 0;
2359 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2360 // This should not happen in a transient state with current design.
2361 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2362 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002363 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002364
Eric Laurentcf2c0212014-07-25 16:20:43 -07002365 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002366 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002367 sp<StreamInHalInterface> inStream;
2368 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002369 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002370 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2371 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002372 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002373 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002374 halconfig.sample_rate,
2375 halconfig.format,
2376 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002377 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002378 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002380 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002381 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002382 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002383 audio_is_linear_pcm(config->format) &&
2384 audio_is_linear_pcm(halconfig.format) &&
2385 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002386 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2387 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002388 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002389 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002390 inStream.clear();
2391 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002392 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002393 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394 }
2395
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002396 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002397 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002398 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2399 sp<MmapCaptureThread> thread =
2400 new MmapCaptureThread(this, *input,
2401 inHwDev, inputStream,
2402 primaryOutputDevice_l(), devices, mSystemReady);
2403 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002404 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2405 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002406 return thread;
2407 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002408#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002409 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2410 // or (re-)create if current Pipe is idle and does not match the new format
2411 sp<NBAIO_Sink> teeSink;
2412 enum {
2413 TEE_SINK_NO, // don't copy input
2414 TEE_SINK_NEW, // copy input using a new pipe
2415 TEE_SINK_OLD, // copy input using an existing pipe
2416 } kind;
2417 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2418 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2419 if (!mTeeSinkInputEnabled) {
2420 kind = TEE_SINK_NO;
2421 } else if (!Format_isValid(format)) {
2422 kind = TEE_SINK_NO;
2423 } else if (mRecordTeeSink == 0) {
2424 kind = TEE_SINK_NEW;
2425 } else if (mRecordTeeSink->getStrongCount() != 1) {
2426 kind = TEE_SINK_NO;
2427 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2428 kind = TEE_SINK_OLD;
2429 } else {
2430 kind = TEE_SINK_NEW;
2431 }
2432 switch (kind) {
2433 case TEE_SINK_NEW: {
2434 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2435 size_t numCounterOffers = 0;
2436 const NBAIO_Format offers[1] = {format};
2437 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2438 ALOG_ASSERT(index == 0);
2439 PipeReader *pipeReader = new PipeReader(*pipe);
2440 numCounterOffers = 0;
2441 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2442 ALOG_ASSERT(index == 0);
2443 mRecordTeeSink = pipe;
2444 mRecordTeeSource = pipeReader;
2445 teeSink = pipe;
2446 }
2447 break;
2448 case TEE_SINK_OLD:
2449 teeSink = mRecordTeeSink;
2450 break;
2451 case TEE_SINK_NO:
2452 default:
2453 break;
2454 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002455#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002456
2457 // Start record thread
2458 // RecordThread requires both input and output device indication to forward to audio
2459 // pre processing modules
2460 sp<RecordThread> thread = new RecordThread(this,
2461 inputStream,
2462 *input,
2463 primaryOutputDevice_l(),
2464 devices,
2465 mSystemReady
2466#ifdef TEE_SINK
2467 , teeSink
2468#endif
2469 );
2470 mRecordThreads.add(*input, thread);
2471 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2472 return thread;
2473 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474 }
2475
Eric Laurentcf2c0212014-07-25 16:20:43 -07002476 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 return 0;
2478}
2479
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002480status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481{
Glenn Kastend96c5722012-04-25 13:44:49 -07002482 return closeInput_nonvirtual(input);
2483}
2484
2485status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2486{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 // keep strong reference on the record thread so that
2488 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002489 sp<RecordThread> recordThread;
2490 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491 {
2492 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002493 recordThread = checkRecordThread_l(input);
2494 if (recordThread != 0) {
2495 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496
Eric Laurent6acd1d42017-01-04 14:23:29 -08002497 // If we still have effect chains, it means that a client still holds a handle
2498 // on at least one effect. We must either move the chain to an existing thread with the
2499 // same session ID or put it aside in case a new record thread is opened for a
2500 // new capture on the same session
2501 sp<EffectChain> chain;
2502 {
2503 Mutex::Autolock _sl(recordThread->mLock);
2504 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2505 // Note: maximum one chain per record thread
2506 if (effectChains.size() != 0) {
2507 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002508 }
2509 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002510 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002511 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002512 // This should only happen in case of overlap between one thread tear down and the
2513 // creation of its replacement
2514 size_t i;
2515 for (i = 0; i < mRecordThreads.size(); i++) {
2516 sp<RecordThread> t = mRecordThreads.valueAt(i);
2517 if (t == recordThread) {
2518 continue;
2519 }
2520 if (t->hasAudioSession(chain->sessionId()) != 0) {
2521 Mutex::Autolock _l(t->mLock);
2522 ALOGV("closeInput() found thread %d for effect session %d",
2523 t->id(), chain->sessionId());
2524 t->addEffectChain_l(chain);
2525 break;
2526 }
2527 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002528 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 if (i == mRecordThreads.size()) {
2530 putOrphanEffectChain_l(chain);
2531 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002532 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002533 mRecordThreads.removeItem(input);
2534 } else {
2535 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2536 if (mmapThread == 0) {
2537 return BAD_VALUE;
2538 }
2539 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002540 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002541 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2542 ioDesc->mIoHandle = input;
2543 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 }
Eric Laurent83b88082014-06-20 18:31:16 -07002545 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2546 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002547 if (recordThread != 0) {
2548 closeInputFinish(recordThread);
2549 } else if (mmapThread != 0) {
2550 mmapThread->exit();
2551 AudioStreamIn *in = mmapThread->clearInput();
2552 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2553 // from now on thread->mInput is NULL
2554 delete in;
2555 }
Eric Laurent83b88082014-06-20 18:31:16 -07002556 return NO_ERROR;
2557}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002559void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002560{
2561 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002562 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002563 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002564 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002565 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002566}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002568void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002569{
2570 mRecordThreads.removeItem(thread->mId);
2571 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572}
2573
Glenn Kastend2304db2014-02-03 07:40:31 -08002574status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575{
2576 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002577 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578
2579 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2580 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002581 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002582 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2584 mMmapThreads[i]->invalidateTracks(stream);
2585 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586 return NO_ERROR;
2587}
2588
2589
Glenn Kasteneeecb982016-02-26 10:44:04 -08002590audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591{
Glenn Kasten9d003132016-04-06 14:38:09 -07002592 // This is a binder API, so a malicious client could pass in a bad parameter.
2593 // Check for that before calling the internal API nextUniqueId().
2594 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2595 ALOGE("newAudioUniqueId invalid use %d", use);
2596 return AUDIO_UNIQUE_ID_ALLOCATE;
2597 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002598 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599}
2600
Glenn Kastend848eb42016-03-08 13:42:11 -08002601void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002602{
2603 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002604 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002605 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2606 if (pid != -1 && (caller == getpid_cached)) {
2607 caller = pid;
2608 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002609
Eric Laurent021cf962014-05-13 10:18:14 -07002610 {
2611 Mutex::Autolock _cl(mClientLock);
2612 // Ignore requests received from processes not known as notification client. The request
2613 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2614 // called from a different pid leaving a stale session reference. Also we don't know how
2615 // to clear this reference if the client process dies.
2616 if (mNotificationClients.indexOfKey(caller) < 0) {
2617 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2618 return;
2619 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002620 }
2621
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002622 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002623 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002624 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002625 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2626 ref->mCnt++;
2627 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002628 return;
2629 }
2630 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002631 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2632 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002633}
2634
Glenn Kastend848eb42016-03-08 13:42:11 -08002635void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002636{
2637 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002638 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002639 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2640 if (pid != -1 && (caller == getpid_cached)) {
2641 caller = pid;
2642 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002643 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002644 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002645 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002646 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2647 ref->mCnt--;
2648 ALOGV(" decremented refcount to %d", ref->mCnt);
2649 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002650 mAudioSessionRefs.removeAt(i);
2651 delete ref;
2652 purgeStaleEffects_l();
2653 }
2654 return;
2655 }
2656 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002657 // If the caller is mediaserver it is likely that the session being released was acquired
2658 // on behalf of a process not in notification clients and we ignore the warning.
2659 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002660}
2661
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002662bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2663{
2664 size_t num = mAudioSessionRefs.size();
2665 for (size_t i = 0; i < num; i++) {
2666 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2667 if (ref->mSessionid == audioSession) {
2668 return true;
2669 }
2670 }
2671 return false;
2672}
2673
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002674void AudioFlinger::purgeStaleEffects_l() {
2675
Steve Block3856b092011-10-20 11:56:00 +01002676 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002677
2678 Vector< sp<EffectChain> > chains;
2679
2680 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2681 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002682 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002683 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2684 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002685 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2686 chains.push(ec);
2687 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002688 }
2689 }
2690 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2691 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002692 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002693 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2694 sp<EffectChain> ec = t->mEffectChains[j];
2695 chains.push(ec);
2696 }
2697 }
2698
2699 for (size_t i = 0; i < chains.size(); i++) {
2700 sp<EffectChain> ec = chains[i];
2701 int sessionid = ec->sessionId();
2702 sp<ThreadBase> t = ec->mThread.promote();
2703 if (t == 0) {
2704 continue;
2705 }
2706 size_t numsessionrefs = mAudioSessionRefs.size();
2707 bool found = false;
2708 for (size_t k = 0; k < numsessionrefs; k++) {
2709 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002710 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002711 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002712 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002713 found = true;
2714 break;
2715 }
2716 }
2717 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002718 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002719 // remove all effects from the chain
2720 while (ec->mEffects.size()) {
2721 sp<EffectModule> effect = ec->mEffects[0];
2722 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002723 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002724 if (effect->purgeHandles()) {
2725 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002726 }
2727 AudioSystem::unregisterEffect(effect->id());
2728 }
2729 }
2730 }
2731 return;
2732}
2733
Glenn Kasteneeecb982016-02-26 10:44:04 -08002734// checkThread_l() must be called with AudioFlinger::mLock held
2735AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2736{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002737 ThreadBase *thread = checkMmapThread_l(ioHandle);
2738 if (thread == 0) {
2739 switch (audio_unique_id_get_use(ioHandle)) {
2740 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2741 thread = checkPlaybackThread_l(ioHandle);
2742 break;
2743 case AUDIO_UNIQUE_ID_USE_INPUT:
2744 thread = checkRecordThread_l(ioHandle);
2745 break;
2746 default:
2747 break;
2748 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002749 }
2750 return thread;
2751}
2752
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002754AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755{
Glenn Kastena1117922012-01-26 10:53:32 -08002756 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757}
2758
2759// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002760AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761{
2762 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002763 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764}
2765
2766// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002767AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768{
Glenn Kastena1117922012-01-26 10:53:32 -08002769 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770}
2771
Eric Laurent6acd1d42017-01-04 14:23:29 -08002772// checkMmapThread_l() must be called with AudioFlinger::mLock held
2773AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2774{
2775 return mMmapThreads.valueFor(io).get();
2776}
2777
2778
2779// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2780AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2781{
Eric Laurent7459b902017-04-19 18:10:41 -07002782 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002783 if (volumeInterface == nullptr) {
2784 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2785 if (mmapThread != nullptr) {
2786 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002787 MmapPlaybackThread *mmapPlaybackThread =
2788 static_cast<MmapPlaybackThread *>(mmapThread);
2789 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002790 }
2791 }
2792 }
2793 return volumeInterface;
2794}
2795
2796Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2797{
2798 Vector <VolumeInterface *> volumeInterfaces;
2799 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002800 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002801 }
2802 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2803 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002804 MmapPlaybackThread *mmapPlaybackThread =
2805 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2806 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002807 }
2808 }
2809 return volumeInterfaces;
2810}
2811
Glenn Kasteneeecb982016-02-26 10:44:04 -08002812audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813{
Glenn Kasten9d003132016-04-06 14:38:09 -07002814 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002815 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002816 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2817 for (int retry = 0; retry < maxRetries; retry++) {
2818 // The cast allows wraparound from max positive to min negative instead of abort
2819 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2820 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2821 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2822 // allow wrap by skipping 0 and -1 for session ids
2823 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2824 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2825 return (audio_unique_id_t) (base | use);
2826 }
2827 }
2828 // We have no way of recovering from wraparound
2829 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2830 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831}
2832
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002833AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002834{
2835 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2836 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002837 if(thread->isDuplicating()) {
2838 continue;
2839 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002840 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002841 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002842 return thread;
2843 }
2844 }
2845 return NULL;
2846}
2847
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002848audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002849{
2850 PlaybackThread *thread = primaryPlaybackThread_l();
2851
2852 if (thread == NULL) {
2853 return 0;
2854 }
2855
Eric Laurentf1c04f92012-08-28 14:26:53 -07002856 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002857}
2858
Glenn Kastena7335632016-06-09 17:09:53 -07002859AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2860{
2861 size_t minFrameCount = 0;
2862 PlaybackThread *minThread = NULL;
2863 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2864 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2865 if (!thread->isDuplicating()) {
2866 size_t frameCount = thread->frameCountHAL();
2867 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2868 (frameCount == minFrameCount && thread->hasFastMixer() &&
2869 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2870 minFrameCount = frameCount;
2871 minThread = thread;
2872 }
2873 }
2874 }
2875 return minThread;
2876}
2877
Eric Laurenta011e352012-03-29 15:51:43 -07002878sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002879 audio_session_t triggerSession,
2880 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002881 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002882 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002883{
2884 Mutex::Autolock _l(mLock);
2885
2886 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2887 status_t playStatus = NAME_NOT_FOUND;
2888 status_t recStatus = NAME_NOT_FOUND;
2889 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2890 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2891 if (playStatus == NO_ERROR) {
2892 return event;
2893 }
2894 }
2895 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2896 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2897 if (recStatus == NO_ERROR) {
2898 return event;
2899 }
2900 }
2901 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2902 mPendingSyncEvents.add(event);
2903 } else {
2904 ALOGV("createSyncEvent() invalid event %d", event->type());
2905 event.clear();
2906 }
2907 return event;
2908}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002909
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910// ----------------------------------------------------------------------------
2911// Effect management
2912// ----------------------------------------------------------------------------
2913
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002914sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2915 return mEffectsFactoryHal;
2916}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917
Glenn Kastenf587ba52012-01-26 16:25:10 -08002918status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919{
2920 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002921 if (mEffectsFactoryHal.get()) {
2922 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2923 } else {
2924 return -ENODEV;
2925 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926}
2927
Glenn Kastenf587ba52012-01-26 16:25:10 -08002928status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929{
2930 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002931 if (mEffectsFactoryHal.get()) {
2932 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2933 } else {
2934 return -ENODEV;
2935 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936}
2937
Glenn Kasten5e92a782012-01-30 07:40:52 -08002938status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002939 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940{
2941 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002942 if (mEffectsFactoryHal.get()) {
2943 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2944 } else {
2945 return -ENODEV;
2946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947}
2948
2949
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002950sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 effect_descriptor_t *pDesc,
2952 const sp<IEffectClient>& effectClient,
2953 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002954 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002955 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002956 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002957 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 status_t *status,
2959 int *id,
2960 int *enabled)
2961{
2962 status_t lStatus = NO_ERROR;
2963 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965
Eric Laurentb6436272016-12-07 19:24:50 -08002966 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2967 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2968 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2969 ALOGW_IF(pid != -1 && pid != callingPid,
2970 "%s uid %d pid %d tried to pass itself off as pid %d",
2971 __func__, callingUid, callingPid, pid);
2972 pid = callingPid;
2973 }
2974
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002975 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2976 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977
2978 if (pDesc == NULL) {
2979 lStatus = BAD_VALUE;
2980 goto Exit;
2981 }
2982
Eric Laurent84e9a102010-09-23 16:10:16 -07002983 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002984 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002985 lStatus = PERMISSION_DENIED;
2986 goto Exit;
2987 }
2988
Dima Zavinfce7a472011-04-19 22:30:36 -07002989 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002990 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002991 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002992 lStatus = PERMISSION_DENIED;
2993 goto Exit;
2994 }
2995
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002996 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002997 lStatus = NO_INIT;
2998 goto Exit;
2999 }
3000
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003002 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003004 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003006 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 goto Exit;
3008 }
3009 } else {
3010 // if uuid is not specified, look for an available implementation
3011 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003012 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003013 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014 lStatus = BAD_VALUE;
3015 goto Exit;
3016 }
3017 uint32_t numEffects = 0;
3018 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003019 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020 bool found = false;
3021
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003022 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003024 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025 goto Exit;
3026 }
3027 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003028 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003029 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003030 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003031 continue;
3032 }
3033 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3034 // If matching type found save effect descriptor. If the session is
3035 // 0 and the effect is not auxiliary, continue enumeration in case
3036 // an auxiliary version of this effect type is available
3037 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003038 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003039 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3041 break;
3042 }
3043 }
3044 }
3045 if (!found) {
3046 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003047 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 goto Exit;
3049 }
3050 // For same effect type, chose auxiliary version over insert version if
3051 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003052 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003054 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 }
3056 }
3057
3058 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003059 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3061 lStatus = INVALID_OPERATION;
3062 goto Exit;
3063 }
3064
Eric Laurent59255e42011-07-27 19:49:51 -07003065 // check recording permission for visualizer
3066 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003067 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003068 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003069 lStatus = PERMISSION_DENIED;
3070 goto Exit;
3071 }
3072
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003074 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003075 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003076 // if the output returned by getOutputForEffect() is removed before we lock the
3077 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3078 // and we will exit safely
3079 io = AudioSystem::getOutputForEffect(&desc);
3080 ALOGV("createEffect got output %d", io);
3081 }
3082
3083 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084
3085 // If output is not specified try to find a matching audio session ID in one of the
3086 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003087 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3088 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003089 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003090 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003091 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3092 // output must be specified by AudioPolicyManager when using session
3093 // AUDIO_SESSION_OUTPUT_STAGE
3094 lStatus = BAD_VALUE;
3095 goto Exit;
3096 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003097 // look for the thread where the specified audio session is present
3098 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3099 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3100 io = mPlaybackThreads.keyAt(i);
3101 break;
3102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003104 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003105 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3106 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3107 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003108 break;
3109 }
3110 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003111 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003112 if (io == AUDIO_IO_HANDLE_NONE) {
3113 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3114 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3115 io = mMmapThreads.keyAt(i);
3116 break;
3117 }
3118 }
3119 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003120 // If no output thread contains the requested session ID, default to
3121 // first output. The effect chain will be moved to the correct output
3122 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003123 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003124 io = mPlaybackThreads.keyAt(0);
3125 }
Steve Block3856b092011-10-20 11:56:00 +01003126 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003127 }
3128 ThreadBase *thread = checkRecordThread_l(io);
3129 if (thread == NULL) {
3130 thread = checkPlaybackThread_l(io);
3131 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003132 thread = checkMmapThread_l(io);
3133 if (thread == NULL) {
3134 ALOGE("createEffect() unknown output thread");
3135 lStatus = BAD_VALUE;
3136 goto Exit;
3137 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003138 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003139 } else {
3140 // Check if one effect chain was awaiting for an effect to be created on this
3141 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003142 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003143 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003144 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003145 thread->addEffectChain_l(chain);
3146 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003148
Eric Laurent021cf962014-05-13 10:18:14 -07003149 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003151 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003152 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003153 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003154 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003155 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003156 // remove local strong reference to Client with mClientLock held
3157 Mutex::Autolock _cl(mClientLock);
3158 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003159 } else {
3160 // handle must be valid here, but check again to be safe.
3161 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163 }
3164
haobo101735295ff7b0d2017-03-17 17:44:03 +08003165 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3166 // handle must be cleared outside lock.
3167 handle.clear();
3168 }
3169
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003171 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 return handle;
3173}
3174
Glenn Kastend848eb42016-03-08 13:42:11 -08003175status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003176 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003177{
Steve Block3856b092011-10-20 11:56:00 +01003178 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003179 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003180 Mutex::Autolock _l(mLock);
3181 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003182 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003183 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 }
Eric Laurentde070132010-07-13 04:45:46 -07003185 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3186 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003187 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003188 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 }
Eric Laurentde070132010-07-13 04:45:46 -07003190 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3191 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003192 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003193 return BAD_VALUE;
3194 }
3195
3196 Mutex::Autolock _dl(dstThread->mLock);
3197 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003198 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199}
3200
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003201// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003202status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003203 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003204 AudioFlinger::PlaybackThread *dstThread,
3205 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003206{
Steve Block3856b092011-10-20 11:56:00 +01003207 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003208 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003209
Eric Laurent59255e42011-07-27 19:49:51 -07003210 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003211 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003212 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003213 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003214 return INVALID_OPERATION;
3215 }
3216
Eric Laurent4c415062016-06-17 16:14:16 -07003217 // Check whether the destination thread and all effects in the chain are compatible
3218 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003219 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003220 " destination thread %p is not compatible with effects in the chain",
3221 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003222 return INVALID_OPERATION;
3223 }
3224
Eric Laurent39e94f82010-07-28 01:32:47 -07003225 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003226 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003227 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003228 // removed.
3229 srcThread->removeEffectChain_l(chain);
3230
3231 // transfer all effects one by one so that new effect chain is created on new thread with
3232 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003233 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003234 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003235 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003236 Vector< sp<EffectModule> > removed;
3237 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003238 while (effect != 0) {
3239 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003240 removed.add(effect);
3241 status = dstThread->addEffect_l(effect);
3242 if (status != NO_ERROR) {
3243 break;
3244 }
Eric Laurentec35a142011-10-05 17:42:25 -07003245 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3246 if (effect->state() == EffectModule::ACTIVE ||
3247 effect->state() == EffectModule::STOPPING) {
3248 effect->start();
3249 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003250 // if the move request is not received from audio policy manager, the effect must be
3251 // re-registered with the new strategy and output
3252 if (dstChain == 0) {
3253 dstChain = effect->chain().promote();
3254 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003255 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003256 status = NO_INIT;
3257 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003258 }
3259 strategy = dstChain->strategy();
3260 }
3261 if (reRegister) {
3262 AudioSystem::unregisterEffect(effect->id());
3263 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003264 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003265 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003266 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003267 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003268 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003269 }
Eric Laurentde070132010-07-13 04:45:46 -07003270 effect = chain->getEffectFromId_l(0);
3271 }
3272
Eric Laurent5baf2af2013-09-12 17:37:00 -07003273 if (status != NO_ERROR) {
3274 for (size_t i = 0; i < removed.size(); i++) {
3275 srcThread->addEffect_l(removed[i]);
3276 if (dstChain != 0 && reRegister) {
3277 AudioSystem::unregisterEffect(removed[i]->id());
3278 AudioSystem::registerEffect(&removed[i]->desc(),
3279 srcThread->id(),
3280 strategy,
3281 sessionId,
3282 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003283 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003284 }
3285 }
3286 }
3287
3288 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289}
3290
Eric Laurent5baf2af2013-09-12 17:37:00 -07003291bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003292{
3293 if (mGlobalEffectEnableTime != 0 &&
3294 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3295 return true;
3296 }
3297
3298 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3299 sp<EffectChain> ec =
3300 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003301 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003302 return true;
3303 }
3304 }
3305 return false;
3306}
3307
Eric Laurent5baf2af2013-09-12 17:37:00 -07003308void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003309{
3310 Mutex::Autolock _l(mLock);
3311
3312 mGlobalEffectEnableTime = systemTime();
3313
3314 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3315 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3316 if (t->mType == ThreadBase::OFFLOAD) {
3317 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3318 }
3319 }
3320
3321}
3322
Eric Laurentaaa44472014-09-12 17:41:50 -07003323status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3324{
Eric Laurentd8365c52017-07-16 15:27:05 -07003325 // clear possible suspended state before parking the chain so that it starts in default state
3326 // when attached to a new record thread
3327 chain->setEffectSuspended_l(FX_IID_AEC, false);
3328 chain->setEffectSuspended_l(FX_IID_NS, false);
3329
Glenn Kastend848eb42016-03-08 13:42:11 -08003330 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003331 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003332 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003333 if (index >= 0) {
3334 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3335 return ALREADY_EXISTS;
3336 }
3337 mOrphanEffectChains.add(session, chain);
3338 return NO_ERROR;
3339}
3340
3341sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3342{
3343 sp<EffectChain> chain;
3344 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003345 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003346 if (index >= 0) {
3347 chain = mOrphanEffectChains.valueAt(index);
3348 mOrphanEffectChains.removeItemsAt(index);
3349 }
3350 return chain;
3351}
3352
3353bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3354{
3355 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003356 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003357 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003358 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003359 if (index >= 0) {
3360 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003361 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003362 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003363 mOrphanEffectChains.removeItemsAt(index);
3364 }
3365 return true;
3366 }
3367 return false;
3368}
3369
3370
Glenn Kastenda6ef132013-01-10 12:31:01 -08003371struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003372#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3373 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003374};
3375
3376int comparEntry(const void *p1, const void *p2)
3377{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003378 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003379}
3380
Glenn Kasten46909e72013-02-26 09:20:22 -08003381#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003382void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383{
Eric Laurent81784c32012-11-19 14:55:58 -08003384 NBAIO_Source *teeSource = source.get();
3385 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003386 // .wav rotation
3387 // There is a benign race condition if 2 threads call this simultaneously.
3388 // They would both traverse the directory, but the result would simply be
3389 // failures at unlink() which are ignored. It's also unlikely since
3390 // normally dumpsys is only done by bugreport or from the command line.
Andy Hungb1fe6e12018-04-19 19:20:00 -07003391 char teePath[PATH_MAX] = "/data/misc/audioserver";
Glenn Kastenda6ef132013-01-10 12:31:01 -08003392 size_t teePathLen = strlen(teePath);
3393 DIR *dir = opendir(teePath);
3394 teePath[teePathLen++] = '/';
3395 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003396#define TEE_MAX_SORT 20 // number of entries to sort
3397#define TEE_MAX_KEEP 10 // number of entries to keep
3398 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003399 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003400 while (entryCount < TEE_MAX_SORT) {
Andy Hungb1fe6e12018-04-19 19:20:00 -07003401 errno = 0; // clear errno before readdir() to track potential errors.
3402 const struct dirent *result = readdir(dir);
3403 if (result == nullptr) {
3404 ALOGW_IF(errno != 0, "tee readdir() failure %s", strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003405 break;
3406 }
3407 // ignore non .wav file entries
Andy Hungb1fe6e12018-04-19 19:20:00 -07003408 const size_t nameLen = strlen(result->d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003409 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Andy Hungb1fe6e12018-04-19 19:20:00 -07003410 strcmp(&result->d_name[nameLen - 4], ".wav")) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003411 continue;
3412 }
Andy Hungb1fe6e12018-04-19 19:20:00 -07003413 (void)audio_utils_strlcpy(entries[entryCount++].mFileName, result->d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003414 }
3415 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003416 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003417 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003418 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3419 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003420 (void) unlink(teePath);
3421 }
3422 }
3423 } else {
3424 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003425 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003426 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003427 }
3428 }
Eric Laurent81784c32012-11-19 14:55:58 -08003429 char teeTime[16];
3430 struct timeval tv;
3431 gettimeofday(&tv, NULL);
3432 struct tm tm;
3433 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003434 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003435 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3436 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003437 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3438 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003439 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003440 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003441 char wavHeader[44];
3442 memcpy(wavHeader,
3443 "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",
3444 sizeof(wavHeader));
3445 NBAIO_Format format = teeSource->format();
3446 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003447 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003448 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003449 wavHeader[22] = channelCount; // number of channels
3450 wavHeader[24] = sampleRate; // sample rate
3451 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003452 wavHeader[32] = frameSize; // block alignment
3453 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003454 write(teeFd, wavHeader, sizeof(wavHeader));
3455 size_t total = 0;
3456 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003457#define TEE_SINK_READ 1024 // frames per I/O operation
3458 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003459 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003460 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003461 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003462 bool wasFirstRead = firstRead;
3463 firstRead = false;
3464 if (actual <= 0) {
3465 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3466 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003467 }
Eric Laurent81784c32012-11-19 14:55:58 -08003468 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003469 }
Eric Laurent81784c32012-11-19 14:55:58 -08003470 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003471 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003472 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003473 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003474 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003475 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003476 uint32_t temp = 44 + total * frameSize - 8;
3477 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003478 write(teeFd, &temp, sizeof(temp));
3479 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003480 temp = total * frameSize;
3481 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003482 write(teeFd, &temp, sizeof(temp));
3483 close(teeFd);
Glenn Kasten9e756632017-10-03 13:01:09 -07003484 // TODO Should create file with temporary name and then rename to final if non-empty.
3485 if (total > 0) {
3486 if (fd >= 0) {
3487 dprintf(fd, "tee copied to %s\n", teePath);
3488 }
3489 } else {
3490 unlink(teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003491 }
Eric Laurent59255e42011-07-27 19:49:51 -07003492 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003493 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003494 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003495 }
Eric Laurent59255e42011-07-27 19:49:51 -07003496 }
3497 }
3498}
Glenn Kasten46909e72013-02-26 09:20:22 -08003499#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003500
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501// ----------------------------------------------------------------------------
3502
3503status_t AudioFlinger::onTransact(
3504 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3505{
3506 return BnAudioFlinger::onTransact(code, data, reply, flags);
3507}
3508
Glenn Kasten63238ef2015-03-02 15:50:29 -08003509} // namespace android