blob: 76b29c9e8fdcdf88908c8c17e5de4f339898361d [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>
Andy Hung7ad78182018-05-10 20:54:29 -070059#include <audio_utils/string.h>
Glenn Kasten3b21c502011-12-15 09:52:39 -080060
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070067#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080074#include "TypedLogger.h"
75
Mathias Agopian65ab4712010-07-14 17:59:35 -070076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
John Grossman1c345192012-03-27 14:00:17 -070078// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
Eric Laurentde070132010-07-13 04:45:46 -070090
Mathias Agopian65ab4712010-07-14 17:59:35 -070091namespace android {
92
Glenn Kastenec1d6b52011-12-12 09:04:45 -080093static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
94static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070095static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070096static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten58912562012-04-03 10:45:00 -070098
John Grossman4ff14ba2012-02-08 16:37:41 -080099nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700102
Eric Laurentfc235202016-12-20 18:48:17 -0800103
Glenn Kasten46909e72013-02-26 09:20:22 -0800104#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800105bool AudioFlinger::mTeeSinkInputEnabled = false;
106bool AudioFlinger::mTeeSinkOutputEnabled = false;
107bool AudioFlinger::mTeeSinkTrackEnabled = false;
108
109size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
110size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
111size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800112#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800113
Eric Laurent813e2a72013-08-31 12:59:48 -0700114// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
115// we define a minimum time during which a global effect is considered enabled.
116static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
117
Eric Laurentfc235202016-12-20 18:48:17 -0800118Mutex gLock;
119wp<AudioFlinger> gAudioFlinger;
120
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700121// Keep a strong reference to media.log service around forever.
122// The service is within our parent process so it can never die in a way that we could observe.
123// These two variables are const after initialization.
124static sp<IBinder> sMediaLogServiceAsBinder;
125static sp<IMediaLogService> sMediaLogService;
126
127static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
128
129static void sMediaLogInit()
130{
131 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
132 if (sMediaLogServiceAsBinder != 0) {
133 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
134 }
135}
136
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137// ----------------------------------------------------------------------------
138
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700139std::string formatToString(audio_format_t format) {
140 std::string result;
141 FormatConverter::toString(format, result);
142 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
147AudioFlinger::AudioFlinger()
148 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800149 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800150 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800151 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700152 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700155 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800156 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700157 mBtNrecIsOff(false),
158 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700159 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800160 mTotalMemory(0),
161 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700162 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700163 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700164{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700165 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
166 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
167 // zero ID has a special meaning, so unavailable
168 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
169 }
170
Glenn Kasten949a9262013-04-16 12:35:20 -0700171 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800172 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800173 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800174 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
175 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700176 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800177 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700178
Wei Jia3f273d12015-11-24 09:06:49 -0800179 // reset battery stats.
180 // if the audio service has crashed, battery stats could be left
181 // in bad state, reset the state upon service start.
182 BatteryNotifier::getInstance().noteResetAudio();
183
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700184 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700185 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
186
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800187 mMediaLogNotifier->run("MediaLogNotifier");
188
Glenn Kasten46909e72013-02-26 09:20:22 -0800189#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800190 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800191 (void) property_get("ro.debuggable", value, "0");
192 int debuggable = atoi(value);
193 int teeEnabled = 0;
194 if (debuggable) {
195 (void) property_get("af.tee", value, "0");
196 teeEnabled = atoi(value);
197 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800198 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700199 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700201 }
202 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800203 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700204 }
205 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800206 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700207 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800208#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700209}
210
211void AudioFlinger::onFirstRef()
212{
Eric Laurent93575202011-01-18 18:39:02 -0800213 Mutex::Autolock _l(mLock);
214
Dima Zavin799a70e2011-04-18 16:57:27 -0700215 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 char val_str[PROPERTY_VALUE_MAX] = { 0 };
217 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
218 uint32_t int_val;
219 if (1 == sscanf(val_str, "%u", &int_val)) {
220 mStandbyTimeInNsecs = milliseconds(int_val);
221 ALOGI("Using %u mSec as standby time.", int_val);
222 } else {
223 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
224 ALOGI("Using default %u mSec as standby time.",
225 (uint32_t)(mStandbyTimeInNsecs / 1000000));
226 }
227 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228
Eric Laurent1c333e22014-05-20 10:48:17 -0700229 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700230
Eric Laurenta4c5a552012-03-29 10:12:40 -0700231 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800232
233 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700234}
235
236AudioFlinger::~AudioFlinger()
237{
238 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700239 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700240 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241 }
242 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700243 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700244 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700246
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800247 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
248 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700249 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700251
252 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700253 if (sMediaLogService != 0) {
254 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
255 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
256 mUnregisteredWriters.pop();
257 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700258 }
259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260}
261
Eric Laurentfc235202016-12-20 18:48:17 -0800262//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800263__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800264status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
265 const audio_attributes_t *attr,
266 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700267 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800268 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800269 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800270 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700271 sp<MmapStreamInterface>& interface,
272 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800273{
274 sp<AudioFlinger> af;
275 {
276 Mutex::Autolock _l(gLock);
277 af = gAudioFlinger.promote();
278 }
279 status_t ret = NO_INIT;
280 if (af != 0) {
281 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800282 direction, attr, config, client, deviceId,
283 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800284 }
285 return ret;
286}
287
Eric Laurent6acd1d42017-01-04 14:23:29 -0800288status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
289 const audio_attributes_t *attr,
290 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700291 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800292 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800293 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800294 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700295 sp<MmapStreamInterface>& interface,
296 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800297{
298 status_t ret = initCheck();
299 if (ret != NO_ERROR) {
300 return ret;
301 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800302 audio_session_t actualSessionId = *sessionId;
303 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
304 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
305 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800306 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700307 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800308 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
309 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
310 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
311 fullConfig.sample_rate = config->sample_rate;
312 fullConfig.channel_mask = config->channel_mask;
313 fullConfig.format = config->format;
314 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800315 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200316 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800317 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800318 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
319 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700320 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800321 } else {
322 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800323 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800324 client.clientPid,
325 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800326 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800327 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700328 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800329 }
330 if (ret != NO_ERROR) {
331 return ret;
332 }
333
334 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
335 // audio policy manager and we can retrieve it
336 sp<MmapThread> thread = mMmapThreads.valueFor(io);
337 if (thread != 0) {
338 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800339 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700340 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800341 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800342 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700343 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800344 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700345 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800346 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700347 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800348 ret = NO_INIT;
349 }
350
351 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
352
Eric Laurentfc235202016-12-20 18:48:17 -0800353 return ret;
354}
355
Eric Laurenta4c5a552012-03-29 10:12:40 -0700356static const char * const audio_interfaces[] = {
357 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
358 AUDIO_HARDWARE_MODULE_ID_A2DP,
359 AUDIO_HARDWARE_MODULE_ID_USB,
360};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700361
Phil Burk062e67a2015-02-11 13:40:50 -0800362AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700363 audio_module_handle_t module,
364 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700365{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700366 // if module is 0, the request comes from an old policy manager and we should load
367 // well known modules
368 if (module == 0) {
369 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700370 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700371 loadHwModule_l(audio_interfaces[i]);
372 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700373 // then try to find a module supporting the requested device.
374 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
375 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700376 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
377 uint32_t supportedDevices;
378 if (dev->getSupportedDevices(&supportedDevices) == OK &&
379 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700380 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700381 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700382 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700383 } else {
384 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700385 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
386 if (audioHwDevice != NULL) {
387 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700388 }
389 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700390
Dima Zavin799a70e2011-04-18 16:57:27 -0700391 return NULL;
392}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393
Glenn Kasten0f11b512014-01-31 16:18:54 -0800394void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395{
396 const size_t SIZE = 256;
397 char buffer[SIZE];
398 String8 result;
399
400 result.append("Clients:\n");
401 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800402 sp<Client> client = mClients.valueAt(i).promote();
403 if (client != 0) {
404 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
405 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406 }
407 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700408
Eric Laurentd1b28d42013-09-18 18:47:13 -0700409 result.append("Notification Clients:\n");
410 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
411 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
412 result.append(buffer);
413 }
414
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700415 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800416 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700417 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
418 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800419 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700420 result.append(buffer);
421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700423}
424
425
Glenn Kasten0f11b512014-01-31 16:18:54 -0800426void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427{
428 const size_t SIZE = 256;
429 char buffer[SIZE];
430 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800431 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432
John Grossman4ff14ba2012-02-08 16:37:41 -0800433 snprintf(buffer, SIZE, "Hardware status: %d\n"
434 "Standby Time mSec: %u\n",
435 hardwareStatus,
436 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 result.append(buffer);
438 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439}
440
Glenn Kasten0f11b512014-01-31 16:18:54 -0800441void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442{
443 const size_t SIZE = 256;
444 char buffer[SIZE];
445 String8 result;
446 snprintf(buffer, SIZE, "Permission Denial: "
447 "can't dump AudioFlinger from pid=%d, uid=%d\n",
448 IPCThreadState::self()->getCallingPid(),
449 IPCThreadState::self()->getCallingUid());
450 result.append(buffer);
451 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452}
453
Eric Laurent81784c32012-11-19 14:55:58 -0800454bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455{
456 bool locked = false;
457 for (int i = 0; i < kDumpLockRetries; ++i) {
458 if (mutex.tryLock() == NO_ERROR) {
459 locked = true;
460 break;
461 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800462 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 }
464 return locked;
465}
466
467status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
468{
Glenn Kasten44deb052012-02-05 18:09:08 -0800469 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470 dumpPermissionDenial(fd, args);
471 } else {
472 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800473 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 if (!hardwareLocked) {
475 String8 result(kHardwareLockedString);
476 write(fd, result.string(), result.size());
477 } else {
478 mHardwareLock.unlock();
479 }
480
Eric Laurent81784c32012-11-19 14:55:58 -0800481 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482
483 // failed to lock - AudioFlinger is probably deadlocked
484 if (!locked) {
485 String8 result(kDeadlockedString);
486 write(fd, result.string(), result.size());
487 }
488
Eric Laurent021cf962014-05-13 10:18:14 -0700489 bool clientLocked = dumpTryLock(mClientLock);
490 if (!clientLocked) {
491 String8 result(kClientLockedString);
492 write(fd, result.string(), result.size());
493 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700494
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700495 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700496 mEffectsFactoryHal->dumpEffects(fd);
497 } else {
498 String8 result(kNoEffectsFactory);
499 write(fd, result.string(), result.size());
500 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700501
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700503 if (clientLocked) {
504 mClientLock.unlock();
505 }
506
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507 dumpInternals(fd, args);
508
509 // dump playback threads
510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
511 mPlaybackThreads.valueAt(i)->dump(fd, args);
512 }
513
514 // dump record threads
515 for (size_t i = 0; i < mRecordThreads.size(); i++) {
516 mRecordThreads.valueAt(i)->dump(fd, args);
517 }
518
Eric Laurent6acd1d42017-01-04 14:23:29 -0800519 // dump mmap threads
520 for (size_t i = 0; i < mMmapThreads.size(); i++) {
521 mMmapThreads.valueAt(i)->dump(fd, args);
522 }
523
Eric Laurentaaa44472014-09-12 17:41:50 -0700524 // dump orphan effect chains
525 if (mOrphanEffectChains.size() != 0) {
526 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
527 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
528 mOrphanEffectChains.valueAt(i)->dump(fd, args);
529 }
530 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700531 // dump all hardware devs
532 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700533 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
534 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700535 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700536
Glenn Kasten46909e72013-02-26 09:20:22 -0800537#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700538 // dump the serially shared record tee sink
539 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700540 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700541 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800542#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700543
rago3bd1c872016-09-26 12:58:14 -0700544 BUFLOG_RESET;
545
Glenn Kastend65d73c2012-06-22 17:21:07 -0700546 if (locked) {
547 mLock.unlock();
548 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800549
550 // append a copy of media.log here by forwarding fd to it, but don't attempt
551 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700552 if (sMediaLogServiceAsBinder != 0) {
553 dprintf(fd, "\nmedia.log:\n");
554 Vector<String16> args;
555 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800556 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700557
558 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700559 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700560 bool unreachableMemory = false;
561 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700562 if (arg == String16("-m")) {
563 dumpMem = true;
564 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700565 unreachableMemory = true;
566 }
567 }
568
Andy Hung07b745e2016-05-23 16:21:07 -0700569 if (dumpMem) {
570 dprintf(fd, "\nDumping memory:\n");
571 std::string s = dumpMemoryAddresses(100 /* limit */);
572 write(fd, s.c_str(), s.size());
573 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700574 if (unreachableMemory) {
575 dprintf(fd, "\nDumping unreachable memory:\n");
576 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700577 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700578 write(fd, s.c_str(), s.size());
579 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 }
581 return NO_ERROR;
582}
583
Eric Laurent021cf962014-05-13 10:18:14 -0700584sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800585{
Eric Laurent021cf962014-05-13 10:18:14 -0700586 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800587 // If pid is already in the mClients wp<> map, then use that entry
588 // (for which promote() is always != 0), otherwise create a new entry and Client.
589 sp<Client> client = mClients.valueFor(pid).promote();
590 if (client == 0) {
591 client = new Client(this, pid);
592 mClients.add(pid, client);
593 }
594
595 return client;
596}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597
Glenn Kasten9e58b552013-01-18 15:09:48 -0800598sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
599{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700600 // If there is no memory allocated for logs, return a dummy writer that does nothing.
601 // Similarly if we can't contact the media.log service, also return a dummy writer.
602 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800603 return new NBLog::Writer();
604 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700605 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
606 // If allocation fails, consult the vector of previously unregistered writers
607 // and garbage-collect one or more them until an allocation succeeds
608 if (shared == 0) {
609 Mutex::Autolock _l(mUnregisteredWritersLock);
610 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
611 {
612 // Pick the oldest stale writer to garbage-collect
613 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
614 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700615 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700616 // Now the media.log remote reference to IMemory is gone. When our last local
617 // reference to IMemory also drops to zero at end of this block,
618 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
619 }
620 // Re-attempt the allocation
621 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
622 if (shared != 0) {
623 goto success;
624 }
625 }
626 // Even after garbage-collecting all old writers, there is still not enough memory,
627 // so return a dummy writer
628 return new NBLog::Writer();
629 }
630success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800631 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
632 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
633 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700634 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800635 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800636}
637
638void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
639{
Glenn Kasten685ef092013-02-04 08:15:34 -0800640 if (writer == 0) {
641 return;
642 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800643 sp<IMemory> iMemory(writer->getIMemory());
644 if (iMemory == 0) {
645 return;
646 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700647 // Rather than removing the writer immediately, append it to a queue of old writers to
648 // be garbage-collected later. This allows us to continue to view old logs for a while.
649 Mutex::Autolock _l(mUnregisteredWritersLock);
650 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800651}
652
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653// IAudioFlinger interface
654
Eric Laurent21da6472017-11-09 16:29:26 -0800655sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
656 CreateTrackOutput& output,
657 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658{
659 sp<PlaybackThread::Track> track;
660 sp<TrackHandle> trackHandle;
661 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800663 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800664 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700665
Eric Laurent21da6472017-11-09 16:29:26 -0800666 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700667 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800668 uid_t clientUid = input.clientInfo.clientUid;
669 if (!isTrustedCallingUid(callingUid)) {
670 ALOGW_IF(clientUid != callingUid,
671 "%s uid %d tried to pass itself off as %d",
672 __FUNCTION__, callingUid, clientUid);
673 clientUid = callingUid;
674 updatePid = true;
675 }
676 pid_t clientPid = input.clientInfo.clientPid;
677 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700678 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800679 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700680 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800681 __func__, callingUid, callingPid, clientPid);
682 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700683 }
684
Eric Laurent21da6472017-11-09 16:29:26 -0800685 audio_session_t sessionId = input.sessionId;
686 if (sessionId == AUDIO_SESSION_ALLOCATE) {
687 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800688 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
689 lStatus = BAD_VALUE;
690 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800691 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800692
Eric Laurent21da6472017-11-09 16:29:26 -0800693 output.sessionId = sessionId;
694 output.outputId = AUDIO_IO_HANDLE_NONE;
695 output.selectedDeviceId = input.selectedDeviceId;
696
697 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200698 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800699 &output.selectedDeviceId, &portId);
700
701 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
702 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
703 goto Exit;
704 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800705 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
706 // but if someone uses binder directly they could bypass that and cause us to crash
707 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000708 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 lStatus = BAD_VALUE;
710 goto Exit;
711 }
712
Glenn Kasten53b5d092014-02-05 10:00:23 -0800713 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800714 if (!audio_is_output_channel(input.config.channel_mask)) {
715 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800716 lStatus = BAD_VALUE;
717 goto Exit;
718 }
719
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700720 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800721 if (!audio_is_valid_format(input.config.format)) {
722 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700723 lStatus = BAD_VALUE;
724 goto Exit;
725 }
726
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 {
728 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800729 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800731 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 lStatus = BAD_VALUE;
733 goto Exit;
734 }
735
Eric Laurent21da6472017-11-09 16:29:26 -0800736 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737
Glenn Kastene848bd92014-03-13 15:00:32 -0700738 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800739 // check if an effect chain with the same session ID is present on another
740 // output thread and move it here.
741 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
742 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
743 if (mPlaybackThreads.keyAt(i) != output.outputId) {
744 uint32_t sessions = t->hasAudioSession(sessionId);
745 if (sessions & ThreadBase::EFFECT_SESSION) {
746 effectThread = t.get();
747 break;
Eric Laurentde070132010-07-13 04:45:46 -0700748 }
749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 }
Eric Laurent21da6472017-11-09 16:29:26 -0800751 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752
Eric Laurent21da6472017-11-09 16:29:26 -0800753 output.sampleRate = input.config.sample_rate;
754 output.frameCount = input.frameCount;
755 output.notificationFrameCount = input.notificationFrameCount;
756 output.flags = input.flags;
757
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700758 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
759 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800760 &output.frameCount, &output.notificationFrameCount,
761 input.notificationsPerBuffer, input.speed,
762 input.sharedBuffer, sessionId, &output.flags,
763 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800764 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700765 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700766
Eric Laurent21da6472017-11-09 16:29:26 -0800767 output.afFrameCount = thread->frameCount();
768 output.afSampleRate = thread->sampleRate();
769 output.afLatencyMs = thread->latency();
770
Eric Laurent39e94f82010-07-28 01:32:47 -0700771 // move effect chain to this output thread if an effect on same session was waiting
772 // for a track to be created
773 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700774 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700775 Mutex::Autolock _dl(thread->mLock);
776 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800777 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700778 }
Eric Laurenta011e352012-03-29 15:51:43 -0700779
780 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700781 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800782 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700783 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700784 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700785 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700786 } else {
787 mPendingSyncEvents[i]->cancel();
788 }
Eric Laurenta011e352012-03-29 15:51:43 -0700789 mPendingSyncEvents.removeAt(i);
790 i--;
791 }
792 }
793 }
Glenn Kastene198c362013-08-13 09:13:36 -0700794
Eric Laurent21da6472017-11-09 16:29:26 -0800795 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 }
Glenn Kastene198c362013-08-13 09:13:36 -0700797
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700798 if (lStatus != NO_ERROR) {
799 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700800 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700801 // Don't hold mClientLock when releasing the reference on the track as the
802 // destructor will acquire it.
803 {
804 Mutex::Autolock _cl(mClientLock);
805 client.clear();
806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700808 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700811 // return handle to client
812 trackHandle = new TrackHandle(track);
813
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800815 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
816 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
817 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700818 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 return trackHandle;
820}
821
Glenn Kasten2c073da2016-02-26 09:14:08 -0800822uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823{
824 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800825 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800827 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 return 0;
829 }
830 return thread->sampleRate();
831}
832
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800833audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834{
835 Mutex::Autolock _l(mLock);
836 PlaybackThread *thread = checkPlaybackThread_l(output);
837 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000838 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800839 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 }
841 return thread->format();
842}
843
Glenn Kasten2c073da2016-02-26 09:14:08 -0800844size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845{
846 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800847 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800849 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 return 0;
851 }
Glenn Kasten58912562012-04-03 10:45:00 -0700852 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
853 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 return thread->frameCount();
855}
856
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700857size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
858{
859 Mutex::Autolock _l(mLock);
860 ThreadBase *thread = checkThread_l(ioHandle);
861 if (thread == NULL) {
862 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
863 return 0;
864 }
865 return thread->frameCountHAL();
866}
867
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800868uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869{
870 Mutex::Autolock _l(mLock);
871 PlaybackThread *thread = checkPlaybackThread_l(output);
872 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800873 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700874 return 0;
875 }
876 return thread->latency();
877}
878
879status_t AudioFlinger::setMasterVolume(float value)
880{
Eric Laurenta1884f92011-08-23 08:25:03 -0700881 status_t ret = initCheck();
882 if (ret != NO_ERROR) {
883 return ret;
884 }
885
Mathias Agopian65ab4712010-07-14 17:59:35 -0700886 // check calling permissions
887 if (!settingsAllowed()) {
888 return PERMISSION_DENIED;
889 }
890
Eric Laurenta4c5a552012-03-29 10:12:40 -0700891 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700892 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700893
John Grossmanee578c02012-07-23 17:05:46 -0700894 // Set master volume in the HALs which support it.
895 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
896 AutoMutex lock(mHardwareLock);
897 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800898
John Grossmanee578c02012-07-23 17:05:46 -0700899 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
900 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700901 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800902 }
John Grossmanee578c02012-07-23 17:05:46 -0700903 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905
John Grossmanee578c02012-07-23 17:05:46 -0700906 // Now set the master volume in each playback thread. Playback threads
907 // assigned to HALs which do not have master volume support will apply
908 // master volume during the mix operation. Threads with HALs which do
909 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700910 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
911 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
912 continue;
913 }
John Grossmanee578c02012-07-23 17:05:46 -0700914 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700915 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916
917 return NO_ERROR;
918}
919
Glenn Kastenf78aee72012-01-04 11:00:47 -0800920status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921{
Eric Laurenta1884f92011-08-23 08:25:03 -0700922 status_t ret = initCheck();
923 if (ret != NO_ERROR) {
924 return ret;
925 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926
927 // check calling permissions
928 if (!settingsAllowed()) {
929 return PERMISSION_DENIED;
930 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800931 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000932 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933 return BAD_VALUE;
934 }
935
936 { // scope for the lock
937 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700938 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700940 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941 mHardwareStatus = AUDIO_HW_IDLE;
942 }
943
944 if (NO_ERROR == ret) {
945 Mutex::Autolock _l(mLock);
946 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800947 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700948 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949 }
950
951 return ret;
952}
953
954status_t AudioFlinger::setMicMute(bool state)
955{
Eric Laurenta1884f92011-08-23 08:25:03 -0700956 status_t ret = initCheck();
957 if (ret != NO_ERROR) {
958 return ret;
959 }
960
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961 // check calling permissions
962 if (!settingsAllowed()) {
963 return PERMISSION_DENIED;
964 }
965
966 AutoMutex lock(mHardwareLock);
967 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700968 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700969 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
970 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700971 if (result != NO_ERROR) {
972 ret = result;
973 }
974 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 mHardwareStatus = AUDIO_HW_IDLE;
976 return ret;
977}
978
979bool AudioFlinger::getMicMute() const
980{
Eric Laurenta1884f92011-08-23 08:25:03 -0700981 status_t ret = initCheck();
982 if (ret != NO_ERROR) {
983 return false;
984 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800985 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700986 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800987 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800989 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700990 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
991 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800992 if (result == NO_ERROR) {
993 mute = mute && state;
994 }
995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800997
998 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999}
1000
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001001void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1002{
1003 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1004
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001005 AutoMutex lock(mLock);
1006 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001007 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1008 }
1009 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1010 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001011 }
1012}
1013
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014status_t AudioFlinger::setMasterMute(bool muted)
1015{
John Grossmand8f178d2012-07-20 14:51:35 -07001016 status_t ret = initCheck();
1017 if (ret != NO_ERROR) {
1018 return ret;
1019 }
1020
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 // check calling permissions
1022 if (!settingsAllowed()) {
1023 return PERMISSION_DENIED;
1024 }
1025
John Grossmanee578c02012-07-23 17:05:46 -07001026 Mutex::Autolock _l(mLock);
1027 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001028
John Grossmanee578c02012-07-23 17:05:46 -07001029 // Set master mute in the HALs which support it.
1030 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1031 AutoMutex lock(mHardwareLock);
1032 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001033
John Grossmanee578c02012-07-23 17:05:46 -07001034 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1035 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001036 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001037 }
John Grossmanee578c02012-07-23 17:05:46 -07001038 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001039 }
1040
John Grossmanee578c02012-07-23 17:05:46 -07001041 // Now set the master mute in each playback thread. Playback threads
1042 // assigned to HALs which do not have master mute support will apply master
1043 // mute during the mix operation. Threads with HALs which do support master
1044 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001045 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1046 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1047 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001048 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049
1050 return NO_ERROR;
1051}
1052
1053float AudioFlinger::masterVolume() const
1054{
Glenn Kasten98067102011-12-13 11:47:54 -08001055 Mutex::Autolock _l(mLock);
1056 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057}
1058
1059bool AudioFlinger::masterMute() const
1060{
Glenn Kasten98067102011-12-13 11:47:54 -08001061 Mutex::Autolock _l(mLock);
1062 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063}
1064
John Grossman4ff14ba2012-02-08 16:37:41 -08001065float AudioFlinger::masterVolume_l() const
1066{
John Grossman4ff14ba2012-02-08 16:37:41 -08001067 return mMasterVolume;
1068}
1069
John Grossmand8f178d2012-07-20 14:51:35 -07001070bool AudioFlinger::masterMute_l() const
1071{
John Grossmanee578c02012-07-23 17:05:46 -07001072 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001073}
1074
Eric Laurent223fd5c2014-11-11 13:43:36 -08001075status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1076{
1077 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001078 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001079 return BAD_VALUE;
1080 }
1081 pid_t caller = IPCThreadState::self()->getCallingPid();
1082 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001083 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001084 return PERMISSION_DENIED;
1085 }
1086
1087 return NO_ERROR;
1088}
1089
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001090status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1091 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092{
1093 // check calling permissions
1094 if (!settingsAllowed()) {
1095 return PERMISSION_DENIED;
1096 }
1097
Eric Laurent223fd5c2014-11-11 13:43:36 -08001098 status_t status = checkStreamType(stream);
1099 if (status != NO_ERROR) {
1100 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001101 }
Eric Laurent98e38192018-02-15 18:31:53 -08001102 if (output == AUDIO_IO_HANDLE_NONE) {
1103 return BAD_VALUE;
1104 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001105 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106
1107 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001108 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1109 if (volumeInterface == NULL) {
1110 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111 }
Eric Laurent98e38192018-02-15 18:31:53 -08001112 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113
1114 return NO_ERROR;
1115}
1116
Glenn Kastenfff6d712012-01-12 16:38:12 -08001117status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118{
1119 // check calling permissions
1120 if (!settingsAllowed()) {
1121 return PERMISSION_DENIED;
1122 }
1123
Eric Laurent223fd5c2014-11-11 13:43:36 -08001124 status_t status = checkStreamType(stream);
1125 if (status != NO_ERROR) {
1126 return status;
1127 }
1128 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1129
1130 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001131 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 return BAD_VALUE;
1133 }
1134
Eric Laurent93575202011-01-18 18:39:02 -08001135 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001137 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1138 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1139 volumeInterfaces[i]->setStreamMute(stream, muted);
1140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141
1142 return NO_ERROR;
1143}
1144
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001145float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001147 status_t status = checkStreamType(stream);
1148 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149 return 0.0f;
1150 }
Eric Laurent98e38192018-02-15 18:31:53 -08001151 if (output == AUDIO_IO_HANDLE_NONE) {
1152 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 }
1154
Eric Laurent98e38192018-02-15 18:31:53 -08001155 AutoMutex lock(mLock);
1156 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1157 if (volumeInterface == NULL) {
1158 return 0.0f;
1159 }
1160
1161 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162}
1163
Glenn Kastenfff6d712012-01-12 16:38:12 -08001164bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001166 status_t status = checkStreamType(stream);
1167 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168 return true;
1169 }
1170
Glenn Kasten6637baa2012-01-09 09:40:36 -08001171 AutoMutex lock(mLock);
1172 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173}
1174
Eric Laurent054d9d32015-04-24 08:48:48 -07001175
1176void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1177{
1178 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1179 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1180 }
1181}
1182
Eric Laurentf1047e82018-04-16 19:18:20 -07001183// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1184// Some keys are used for audio routing and audio path configuration and should be reserved for use
1185// by audio policy and audio flinger for functional, privacy and security reasons.
1186void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1187{
1188 static const String8 kReservedParameters[] = {
1189 String8(AudioParameter::keyRouting),
1190 String8(AudioParameter::keySamplingRate),
1191 String8(AudioParameter::keyFormat),
1192 String8(AudioParameter::keyChannels),
1193 String8(AudioParameter::keyFrameCount),
1194 String8(AudioParameter::keyInputSource),
1195 String8(AudioParameter::keyMonoOutput),
1196 String8(AudioParameter::keyStreamConnect),
1197 String8(AudioParameter::keyStreamDisconnect),
1198 String8(AudioParameter::keyStreamSupportedFormats),
1199 String8(AudioParameter::keyStreamSupportedChannels),
1200 String8(AudioParameter::keyStreamSupportedSamplingRates),
1201 };
1202
1203 // multiuser friendly app ID check for requests coming from audioserver
1204 if (multiuser_get_app_id(callingUid) == AID_AUDIOSERVER) {
1205 return;
1206 }
1207
1208 AudioParameter param = AudioParameter(keyValuePairs);
1209 String8 value;
1210 for (auto& key : kReservedParameters) {
1211 if (param.get(key, value) == NO_ERROR) {
1212 ALOGW("%s: filtering key %s value %s from uid %d",
1213 __func__, key.string(), value.string(), callingUid);
1214 param.remove(key);
1215 }
1216 }
1217 keyValuePairs = param.toString();
1218}
1219
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001220status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221{
Eric Laurentf1047e82018-04-16 19:18:20 -07001222 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1223 ioHandle, keyValuePairs.string(),
1224 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001225
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 // check calling permissions
1227 if (!settingsAllowed()) {
1228 return PERMISSION_DENIED;
1229 }
1230
Eric Laurentf1047e82018-04-16 19:18:20 -07001231 String8 filteredKeyValuePairs = keyValuePairs;
1232 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1233
1234 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1235
Glenn Kasten142f5192014-03-25 17:44:59 -07001236 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1237 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001238 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001239 // result will remain NO_INIT if no audio device is present
1240 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001241 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001242 AutoMutex lock(mHardwareLock);
1243 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001245 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001246 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001247 // return success if at least one audio device accepts the parameters as not all
1248 // HALs are requested to support all parameters. If no audio device supports the
1249 // requested parameters, the last error is reported.
1250 if (final_result != NO_ERROR) {
1251 final_result = result;
1252 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001253 }
1254 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001255 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001256 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001257 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001258 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001259 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1260 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001261 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001262 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001263 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001264 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001265 }
1266 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001267 String8 screenState;
1268 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001269 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001270 if (isOff != (AudioFlinger::mScreenState & 1)) {
1271 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001272 }
1273 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001274 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275 }
1276
1277 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1278 // and the thread is exited once the lock is released
1279 sp<ThreadBase> thread;
1280 {
1281 Mutex::Autolock _l(mLock);
1282 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001283 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001284 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001285 if (thread == 0) {
1286 thread = checkMmapThread_l(ioHandle);
1287 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001288 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001289 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001290 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001291 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001292 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1293 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001294 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001295 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 }
1297 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001298 if (thread != 0) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001299 return thread->setParameters(filteredKeyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300 }
1301 return BAD_VALUE;
1302}
1303
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001304String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001306 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1307 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001308
Eric Laurenta4c5a552012-03-29 10:12:40 -07001309 Mutex::Autolock _l(mLock);
1310
Glenn Kasten142f5192014-03-25 17:44:59 -07001311 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001312 String8 out_s8;
1313
Dima Zavin799a70e2011-04-18 16:57:27 -07001314 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001315 String8 s;
1316 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001317 {
1318 AutoMutex lock(mHardwareLock);
1319 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001320 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1321 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001322 mHardwareStatus = AUDIO_HW_IDLE;
1323 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001324 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001325 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001326 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001327 }
1328
Eric Laurent6acd1d42017-01-04 14:23:29 -08001329 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1330 if (thread == NULL) {
1331 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1332 if (thread == NULL) {
1333 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1334 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001335 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001336 }
1337 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001339 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001340}
1341
Glenn Kastendd8104c2012-07-02 12:42:44 -07001342size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1343 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001344{
Eric Laurenta1884f92011-08-23 08:25:03 -07001345 status_t ret = initCheck();
1346 if (ret != NO_ERROR) {
1347 return 0;
1348 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001349 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001350 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001351 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001352 return 0;
1353 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001354
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001355 AutoMutex lock(mHardwareLock);
1356 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001357 audio_config_t config, proposed;
1358 memset(&proposed, 0, sizeof(proposed));
1359 proposed.sample_rate = sampleRate;
1360 proposed.channel_mask = channelMask;
1361 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001362
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001363 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001364 size_t frames;
1365 for (;;) {
1366 // Note: config is currently a const parameter for get_input_buffer_size()
1367 // but we use a copy from proposed in case config changes from the call.
1368 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001369 status_t result = dev->getInputBufferSize(&config, &frames);
1370 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001371 break; // hal success, config is the result
1372 }
1373 // change one parameter of the configuration each iteration to a more "common" value
1374 // to see if the device will support it.
1375 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1376 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1377 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1378 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1379 } else {
1380 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1381 "format %#x, channelMask 0x%X",
1382 sampleRate, format, channelMask);
1383 break; // retries failed, break out of loop with frames == 0.
1384 }
1385 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001386 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001387 if (frames > 0 && config.sample_rate != sampleRate) {
1388 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1389 }
1390 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391}
1392
Glenn Kasten5f972c02014-01-13 09:59:31 -08001393uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 Mutex::Autolock _l(mLock);
1396
1397 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1398 if (recordThread != NULL) {
1399 return recordThread->getInputFramesLost();
1400 }
1401 return 0;
1402}
1403
1404status_t AudioFlinger::setVoiceVolume(float value)
1405{
Eric Laurenta1884f92011-08-23 08:25:03 -07001406 status_t ret = initCheck();
1407 if (ret != NO_ERROR) {
1408 return ret;
1409 }
1410
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411 // check calling permissions
1412 if (!settingsAllowed()) {
1413 return PERMISSION_DENIED;
1414 }
1415
1416 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001417 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001418 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001419 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420 mHardwareStatus = AUDIO_HW_IDLE;
1421
1422 return ret;
1423}
1424
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001425status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001426 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428 Mutex::Autolock _l(mLock);
1429
1430 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1431 if (playbackThread != NULL) {
1432 return playbackThread->getRenderPosition(halFrames, dspFrames);
1433 }
1434
1435 return BAD_VALUE;
1436}
1437
1438void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1439{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001441 if (client == 0) {
1442 return;
1443 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001444 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001445 {
1446 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001447 if (mNotificationClients.indexOfKey(pid) < 0) {
1448 sp<NotificationClient> notificationClient = new NotificationClient(this,
1449 client,
1450 pid);
1451 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452
Eric Laurent021cf962014-05-13 10:18:14 -07001453 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454
Marco Nelissen06b46062014-11-14 07:58:25 -08001455 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001456 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001457 }
1458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459
Eric Laurent021cf962014-05-13 10:18:14 -07001460 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001461 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001462 // the config change is always sent from playback or record threads to avoid deadlock
1463 // with AudioSystem::gLock
1464 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001465 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001466 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001468 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001469 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470 }
1471}
1472
1473void AudioFlinger::removeNotificationClient(pid_t pid)
1474{
1475 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001476 {
1477 Mutex::Autolock _cl(mClientLock);
1478 mNotificationClients.removeItem(pid);
1479 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001480
Steve Block3856b092011-10-20 11:56:00 +01001481 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001482 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001483 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001484 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001485 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001486 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001487 if (ref->mPid == pid) {
1488 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001489 mAudioSessionRefs.removeAt(i);
1490 delete ref;
1491 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001492 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001493 } else {
1494 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001495 }
1496 }
1497 if (removed) {
1498 purgeStaleEffects_l();
1499 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500}
1501
Eric Laurent73e26b62015-04-27 16:55:58 -07001502void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001503 const sp<AudioIoDescriptor>& ioDesc,
1504 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505{
Eric Laurent021cf962014-05-13 10:18:14 -07001506 Mutex::Autolock _l(mClientLock);
1507 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001509 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1510 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1511 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 }
1513}
1514
Eric Laurent021cf962014-05-13 10:18:14 -07001515// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516void AudioFlinger::removeClient_l(pid_t pid)
1517{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001518 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001519 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 mClients.removeItem(pid);
1521}
1522
Eric Laurent717e1282012-06-29 16:36:52 -07001523// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001524sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1525 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001526{
1527 sp<PlaybackThread> thread;
1528
1529 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1530 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1531 ALOG_ASSERT(thread == 0);
1532 thread = mPlaybackThreads.valueAt(i);
1533 }
1534 }
1535
1536 return thread;
1537}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540
1541// ----------------------------------------------------------------------------
1542
1543AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1544 : RefBase(),
1545 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001546 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547{
Andy Hung6f248bb2018-01-23 14:04:37 -08001548 mMemoryDealer = new MemoryDealer(
1549 audioFlinger->getClientSharedHeapSize(),
1550 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551}
1552
Eric Laurent021cf962014-05-13 10:18:14 -07001553// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554AudioFlinger::Client::~Client()
1555{
1556 mAudioFlinger->removeClient_l(mPid);
1557}
1558
Glenn Kasten435dbe62012-01-30 10:15:48 -08001559sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560{
1561 return mMemoryDealer;
1562}
1563
1564// ----------------------------------------------------------------------------
1565
1566AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1567 const sp<IAudioFlingerClient>& client,
1568 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001569 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570{
1571}
1572
1573AudioFlinger::NotificationClient::~NotificationClient()
1574{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575}
1576
Glenn Kasten0f11b512014-01-31 16:18:54 -08001577void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578{
1579 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001580 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581}
1582
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001583// ----------------------------------------------------------------------------
1584AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1585 : mPendingRequests(false) {}
1586
1587
1588void AudioFlinger::MediaLogNotifier::requestMerge() {
1589 AutoMutex _l(mMutex);
1590 mPendingRequests = true;
1591 mCond.signal();
1592}
1593
1594bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001595 // Should already have been checked, but just in case
1596 if (sMediaLogService == 0) {
1597 return false;
1598 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001599 // Wait until there are pending requests
1600 {
1601 AutoMutex _l(mMutex);
1602 mPendingRequests = false; // to ignore past requests
1603 while (!mPendingRequests) {
1604 mCond.wait(mMutex);
1605 // TODO may also need an exitPending check
1606 }
1607 mPendingRequests = false;
1608 }
1609 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001610 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001611 usleep(kPostTriggerSleepPeriod);
1612 return true;
1613}
1614
1615void AudioFlinger::requestLogMerge() {
1616 mMediaLogNotifier->requestMerge();
1617}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618
1619// ----------------------------------------------------------------------------
1620
Eric Laurentf14db3c2017-12-08 14:20:36 -08001621sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1622 CreateRecordOutput& output,
1623 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624{
1625 sp<RecordThread::RecordTrack> recordTrack;
1626 sp<RecordHandle> recordHandle;
1627 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001629 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001630 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631
Eric Laurentf14db3c2017-12-08 14:20:36 -08001632 output.cblk.clear();
1633 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001634 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001635
Eric Laurentf14db3c2017-12-08 14:20:36 -08001636 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001637 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001638 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001639 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001640 ALOGW_IF(clientUid != callingUid,
1641 "%s uid %d tried to pass itself off as %d",
1642 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001643 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001644 updatePid = true;
1645 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001646 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001647 if (updatePid) {
1648 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001649 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001650 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001651 __func__, callingUid, callingPid, clientPid);
1652 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001653 }
1654
Andy Hung6770c6f2015-04-07 13:43:36 -07001655 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001656 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1657 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001658 lStatus = BAD_VALUE;
1659 goto Exit;
1660 }
1661
Glenn Kasten53b5d092014-02-05 10:00:23 -08001662 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001663 if (!audio_is_input_channel(input.config.channel_mask)) {
1664 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001665 lStatus = BAD_VALUE;
1666 goto Exit;
1667 }
1668
Eric Laurentf14db3c2017-12-08 14:20:36 -08001669 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1670 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1671 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1672 lStatus = BAD_VALUE;
1673 goto Exit;
1674 }
1675
1676 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001677 output.selectedDeviceId = input.selectedDeviceId;
1678 output.flags = input.flags;
1679
1680 client = registerPid(clientPid);
1681
1682 // Not a conventional loop, but a retry loop for at most two iterations total.
1683 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1684 // Exits loop via break on no error of got exit on error
1685 // The sp<> references will be dropped when re-entering scope.
1686 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1687 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001688 // release previously opened input if retrying.
1689 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1690 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001691 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001692 output.inputId = AUDIO_IO_HANDLE_NONE;
Eric Laurent77881cd2018-02-09 16:01:31 -08001693 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001694 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001695 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1696 sessionId,
1697 // FIXME compare to AudioTrack
1698 clientPid,
1699 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001700 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001701 &input.config,
1702 output.flags, &output.selectedDeviceId, &portId);
1703
Glenn Kasten05997e22014-03-13 15:08:33 -07001704 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001706 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001708 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709 lStatus = BAD_VALUE;
1710 goto Exit;
1711 }
1712
Eric Laurentf14db3c2017-12-08 14:20:36 -08001713 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714
Eric Laurentf14db3c2017-12-08 14:20:36 -08001715 output.sampleRate = input.config.sample_rate;
1716 output.frameCount = input.frameCount;
1717 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001718
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001719 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001720 input.config.format, input.config.channel_mask,
1721 &output.frameCount, sessionId,
1722 &output.notificationFrameCount,
1723 clientUid, &output.flags,
1724 input.clientInfo.clientTid,
1725 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001726 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001727
Eric Laurentf14db3c2017-12-08 14:20:36 -08001728 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1729 // audio policy manager without FAST constraint
1730 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001731 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001732 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001733
1734 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001735 goto Exit;
1736 }
1737
1738 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1739 // session and move it to this thread.
1740 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1741 if (chain != 0) {
1742 Mutex::Autolock _l(thread->mLock);
1743 thread->addEffectChain_l(chain);
1744 }
1745 break;
1746 }
1747 // End of retry loop.
1748 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 }
Glenn Kastene198c362013-08-13 09:13:36 -07001750
Eric Laurentf14db3c2017-12-08 14:20:36 -08001751 output.cblk = recordTrack->getCblk();
1752 output.buffers = recordTrack->getBuffers();
1753
1754 // return handle to client
1755 recordHandle = new RecordHandle(recordTrack);
1756
1757Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001758 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001759 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001760 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001761 // Don't hold mClientLock when releasing the reference on the track as the
1762 // destructor will acquire it.
1763 {
1764 Mutex::Autolock _cl(mClientLock);
1765 client.clear();
1766 }
Eric Laurent896c9672017-12-08 14:08:45 -08001767 recordTrack.clear();
1768 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001769 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001770 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 }
1772
Glenn Kasten9156ef32013-08-06 15:39:08 -07001773 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774 return recordHandle;
1775}
1776
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001777
1778
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779// ----------------------------------------------------------------------------
1780
Eric Laurenta4c5a552012-03-29 10:12:40 -07001781audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1782{
Eric Laurent44622db2014-08-01 19:00:33 -07001783 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001784 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001785 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001786 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001787 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001788 }
1789 Mutex::Autolock _l(mLock);
1790 return loadHwModule_l(name);
1791}
1792
1793// loadHwModule_l() must be called with AudioFlinger::mLock held
1794audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1795{
1796 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1797 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1798 ALOGW("loadHwModule() module %s already loaded", name);
1799 return mAudioHwDevs.keyAt(i);
1800 }
1801 }
1802
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001803 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001804
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001805 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001806 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001807 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001808 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001809 }
1810
1811 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001812 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001813 mHardwareStatus = AUDIO_HW_IDLE;
1814 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001815 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001816 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001817 }
1818
John Grossmanee578c02012-07-23 17:05:46 -07001819 // Check and cache this HAL's level of support for master mute and master
1820 // volume. If this is the first HAL opened, and it supports the get
1821 // methods, use the initial values provided by the HAL as the current
1822 // master mute and volume settings.
1823
1824 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1825 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001826 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001827
1828 if (0 == mAudioHwDevs.size()) {
1829 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001830 float mv;
1831 if (OK == dev->getMasterVolume(&mv)) {
1832 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001833 }
1834
1835 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001836 bool mm;
1837 if (OK == dev->getMasterMute(&mm)) {
1838 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001839 }
1840 }
1841
Eric Laurenta4c5a552012-03-29 10:12:40 -07001842 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001843 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001844 flags = static_cast<AudioHwDevice::Flags>(flags |
1845 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1846 }
1847
1848 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001849 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001850 flags = static_cast<AudioHwDevice::Flags>(flags |
1851 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1852 }
1853
Eric Laurenta4c5a552012-03-29 10:12:40 -07001854 mHardwareStatus = AUDIO_HW_IDLE;
1855 }
1856
Glenn Kastena13cde92016-03-28 15:26:02 -07001857 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001858 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001859
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001860 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001861
1862 return handle;
1863
1864}
1865
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001866// ----------------------------------------------------------------------------
1867
Glenn Kasten3b16c762012-11-14 08:44:39 -08001868uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001869{
1870 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001871 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001872 return thread != NULL ? thread->sampleRate() : 0;
1873}
1874
Glenn Kastene33054e2012-11-14 12:54:39 -08001875size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001876{
1877 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001878 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001879 return thread != NULL ? thread->frameCountHAL() : 0;
1880}
1881
1882// ----------------------------------------------------------------------------
1883
Andy Hung6f248bb2018-01-23 14:04:37 -08001884status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001885{
1886 uid_t uid = IPCThreadState::self()->getCallingUid();
1887 if (uid != AID_SYSTEM) {
1888 return PERMISSION_DENIED;
1889 }
1890 Mutex::Autolock _l(mLock);
1891 if (mIsDeviceTypeKnown) {
1892 return INVALID_OPERATION;
1893 }
1894 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001895 mTotalMemory = totalMemory;
1896 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1897 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1898 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1899 // though actual setting is determined through device configuration.
1900 constexpr int64_t GB = 1024 * 1024 * 1024;
1901 mClientSharedHeapSize =
1902 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1903 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1904 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1905 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1906 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001907 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001908
1909 // TODO: Cache the client shared heap size in a persistent property.
1910 // It's possible that a native process or Java service or app accesses audioserver
1911 // after it is registered by system server, but before AudioService updates
1912 // the memory info. This would occur immediately after boot or an audioserver
1913 // crash and restore. Before update from AudioService, the client would get the
1914 // minimum heap size.
1915
1916 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1917 (isLowRamDevice ? "true" : "false"),
1918 (long long)mTotalMemory,
1919 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001920 return NO_ERROR;
1921}
1922
Andy Hung6f248bb2018-01-23 14:04:37 -08001923size_t AudioFlinger::getClientSharedHeapSize() const
1924{
1925 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1926 if (heapSizeInBytes != 0) { // read-only property overrides all.
1927 return heapSizeInBytes;
1928 }
1929 return mClientSharedHeapSize;
1930}
1931
Eric Laurent93c3d412014-08-01 14:48:35 -07001932audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1933{
1934 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001935
1936 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1937 if (index >= 0) {
1938 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1939 mHwAvSyncIds.valueAt(index), sessionId);
1940 return mHwAvSyncIds.valueAt(index);
1941 }
1942
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001943 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001944 if (dev == NULL) {
1945 return AUDIO_HW_SYNC_INVALID;
1946 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001947 String8 reply;
1948 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001949 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001950 param = AudioParameter(reply);
1951 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001952
1953 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001954 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001955 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1956 return AUDIO_HW_SYNC_INVALID;
1957 }
1958
1959 // allow only one session for a given HW A/V sync ID.
1960 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1961 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1962 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1963 value, mHwAvSyncIds.keyAt(i));
1964 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001965 break;
1966 }
1967 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001968
1969 mHwAvSyncIds.add(sessionId, value);
1970
1971 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1972 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1973 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001974 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001975 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001976 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001977 thread->setParameters(param.toString());
1978 break;
1979 }
1980 }
1981
1982 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1983 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001984}
1985
Eric Laurent72e3f392015-05-20 14:43:50 -07001986status_t AudioFlinger::systemReady()
1987{
1988 Mutex::Autolock _l(mLock);
1989 ALOGI("%s", __FUNCTION__);
1990 if (mSystemReady) {
1991 ALOGW("%s called twice", __FUNCTION__);
1992 return NO_ERROR;
1993 }
1994 mSystemReady = true;
1995 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1996 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1997 thread->systemReady();
1998 }
1999 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2000 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2001 thread->systemReady();
2002 }
2003 return NO_ERROR;
2004}
2005
jiabin46a76fa2018-01-05 10:18:21 -08002006status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2007{
jiabin9ff780e2018-03-19 18:19:52 -07002008 AutoMutex lock(mHardwareLock);
2009 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2010 status_t status = dev->getMicrophones(microphones);
2011 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002012}
2013
Eric Laurentfa90e842014-10-17 18:12:31 -07002014// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2015void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2016{
2017 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2018 if (index >= 0) {
2019 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2020 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2021 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002022 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002023 thread->setParameters(param.toString());
2024 }
2025}
2026
2027
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002028// ----------------------------------------------------------------------------
2029
Eric Laurent83b88082014-06-20 18:31:16 -07002030
Eric Laurent6acd1d42017-01-04 14:23:29 -08002031sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002032 audio_io_handle_t *output,
2033 audio_config_t *config,
2034 audio_devices_t devices,
2035 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002036 audio_output_flags_t flags)
2037{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002038 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002039 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002040 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002041 }
2042
Eric Laurentcf2c0212014-07-25 16:20:43 -07002043 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002044 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2045 } else {
2046 // Audio Policy does not currently request a specific output handle.
2047 // If this is ever needed, see openInput_l() for example code.
2048 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2049 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002050 }
Eric Laurent83b88082014-06-20 18:31:16 -07002051
2052 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2053
Eric Laurent83b88082014-06-20 18:31:16 -07002054 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002055 // This if statement allows overriding the audio policy settings
2056 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2057 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2058 // Check only for Normal Mixing mode
2059 if (kEnableExtendedPrecision) {
2060 // Specify format (uncomment one below to choose)
2061 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2062 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2063 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2064 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002065 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002066 }
2067 if (kEnableExtendedChannels) {
2068 // Specify channel mask (uncomment one below to choose)
2069 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2070 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2071 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2072 }
Eric Laurent83b88082014-06-20 18:31:16 -07002073 }
2074
Phil Burk062e67a2015-02-11 13:40:50 -08002075 AudioStreamOut *outputStream = NULL;
2076 status_t status = outHwDev->openOutputStream(
2077 &outputStream,
2078 *output,
2079 devices,
2080 flags,
2081 config,
2082 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002083
2084 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002085
Phil Burk062e67a2015-02-11 13:40:50 -08002086 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002087 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2088 sp<MmapPlaybackThread> thread =
2089 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2090 devices, AUDIO_DEVICE_NONE, mSystemReady);
2091 mMmapThreads.add(*output, thread);
2092 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2093 *output, thread.get());
2094 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002095 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002096 sp<PlaybackThread> thread;
2097 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2098 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2099 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2100 *output, thread.get());
2101 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2102 || !isValidPcmSinkFormat(config->format)
2103 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2104 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2105 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2106 *output, thread.get());
2107 } else {
2108 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2109 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2110 *output, thread.get());
2111 }
2112 mPlaybackThreads.add(*output, thread);
2113 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002114 }
Eric Laurent83b88082014-06-20 18:31:16 -07002115 }
2116
2117 return 0;
2118}
2119
Eric Laurentcf2c0212014-07-25 16:20:43 -07002120status_t AudioFlinger::openOutput(audio_module_handle_t module,
2121 audio_io_handle_t *output,
2122 audio_config_t *config,
2123 audio_devices_t *devices,
2124 const String8& address,
2125 uint32_t *latencyMs,
2126 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002128 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2129 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002130 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002131 (devices != NULL) ? *devices : 0,
2132 config->sample_rate,
2133 config->format,
2134 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002135 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002137 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002138 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002140
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141 Mutex::Autolock _l(mLock);
2142
Eric Laurent6acd1d42017-01-04 14:23:29 -08002143 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002144 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002145 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2146 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2147 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148
Eric Laurent6acd1d42017-01-04 14:23:29 -08002149 // notify client processes of the new output creation
2150 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002151
Eric Laurent6acd1d42017-01-04 14:23:29 -08002152 // the first primary output opened designates the primary hw device
2153 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002154 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002155 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002156
Eric Laurent6acd1d42017-01-04 14:23:29 -08002157 AutoMutex lock(mHardwareLock);
2158 mHardwareStatus = AUDIO_HW_SET_MODE;
2159 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2160 mHardwareStatus = AUDIO_HW_IDLE;
2161 }
2162 } else {
2163 MmapThread *mmapThread = (MmapThread *)thread.get();
2164 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002165 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002166 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 }
2168
Eric Laurentcf2c0212014-07-25 16:20:43 -07002169 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170}
2171
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002172audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2173 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174{
2175 Mutex::Autolock _l(mLock);
2176 MixerThread *thread1 = checkMixerThread_l(output1);
2177 MixerThread *thread2 = checkMixerThread_l(output2);
2178
2179 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002180 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2181 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002182 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 }
2184
Glenn Kasteneeecb982016-02-26 10:44:04 -08002185 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002186 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 thread->addOutputTrack(thread2);
2188 mPlaybackThreads.add(id, thread);
2189 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002190 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 return id;
2192}
2193
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002194status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002195{
Glenn Kastend96c5722012-04-25 13:44:49 -07002196 return closeOutput_nonvirtual(output);
2197}
2198
2199status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2200{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 // keep strong reference on the playback thread so that
2202 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002203 sp<PlaybackThread> playbackThread;
2204 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 {
2206 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002207 playbackThread = checkPlaybackThread_l(output);
2208 if (playbackThread != NULL) {
2209 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210
Eric Laurent6acd1d42017-01-04 14:23:29 -08002211 if (playbackThread->type() == ThreadBase::MIXER) {
2212 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2213 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2214 DuplicatingThread *dupThread =
2215 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2216 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2217 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002218 }
2219 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002220
2221
Eric Laurent6acd1d42017-01-04 14:23:29 -08002222 mPlaybackThreads.removeItem(output);
2223 // save all effects to the default thread
2224 if (mPlaybackThreads.size()) {
2225 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2226 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002227 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002228 Mutex::Autolock _dl(dstThread->mLock);
2229 Mutex::Autolock _sl(playbackThread->mLock);
2230 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2231 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002232 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2233 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 }
2236 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002237 } else {
2238 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2239 if (mmapThread == 0) {
2240 return BAD_VALUE;
2241 }
2242 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002243 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002245 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2246 ioDesc->mIoHandle = output;
2247 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002249 // The thread entity (active unit of execution) is no longer running here,
2250 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251
Eric Laurent6acd1d42017-01-04 14:23:29 -08002252 if (playbackThread != 0) {
2253 playbackThread->exit();
2254 if (!playbackThread->isDuplicating()) {
2255 closeOutputFinish(playbackThread);
2256 }
2257 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002258 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002259 mmapThread->exit();
2260 AudioStreamOut *out = mmapThread->clearOutput();
2261 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2262 // from now on thread->mOutput is NULL
2263 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 }
2265 return NO_ERROR;
2266}
2267
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002268void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002269{
2270 AudioStreamOut *out = thread->clearOutput();
2271 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2272 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002273 delete out;
2274}
2275
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002276void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002277{
2278 mPlaybackThreads.removeItem(thread->mId);
2279 thread->exit();
2280 closeOutputFinish(thread);
2281}
2282
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002283status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284{
2285 Mutex::Autolock _l(mLock);
2286 PlaybackThread *thread = checkPlaybackThread_l(output);
2287
2288 if (thread == NULL) {
2289 return BAD_VALUE;
2290 }
2291
Steve Block3856b092011-10-20 11:56:00 +01002292 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 thread->suspend();
2294
2295 return NO_ERROR;
2296}
2297
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002298status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299{
2300 Mutex::Autolock _l(mLock);
2301 PlaybackThread *thread = checkPlaybackThread_l(output);
2302
2303 if (thread == NULL) {
2304 return BAD_VALUE;
2305 }
2306
Steve Block3856b092011-10-20 11:56:00 +01002307 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308
2309 thread->restore();
2310
2311 return NO_ERROR;
2312}
2313
Eric Laurentcf2c0212014-07-25 16:20:43 -07002314status_t AudioFlinger::openInput(audio_module_handle_t module,
2315 audio_io_handle_t *input,
2316 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002317 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002318 const String8& address,
2319 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002320 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321{
Eric Laurent83b88082014-06-20 18:31:16 -07002322 Mutex::Autolock _l(mLock);
2323
Glenn Kastene7d66712015-03-05 13:46:52 -08002324 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002325 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002326 }
2327
Eric Laurent6acd1d42017-01-04 14:23:29 -08002328 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002329
2330 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002331 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002332 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002333 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002335 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002336}
Dima Zavin799a70e2011-04-18 16:57:27 -07002337
Eric Laurent6acd1d42017-01-04 14:23:29 -08002338sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002339 audio_io_handle_t *input,
2340 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002341 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002342 const String8& address,
2343 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002344 audio_input_flags_t flags)
2345{
Glenn Kastene7d66712015-03-05 13:46:52 -08002346 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002347 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002348 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002349 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002350 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002351
Glenn Kasteneeecb982016-02-26 10:44:04 -08002352 // Audio Policy can request a specific handle for hardware hotword.
2353 // The goal here is not to re-open an already opened input.
2354 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002355 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002356 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2357 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2358 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2359 return 0;
2360 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2361 // This should not happen in a transient state with current design.
2362 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2363 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002364 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002365
Eric Laurentcf2c0212014-07-25 16:20:43 -07002366 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002367 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002368 sp<StreamInHalInterface> inStream;
2369 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002370 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002371 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2372 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002373 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002374 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002375 halconfig.sample_rate,
2376 halconfig.format,
2377 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002378 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002379 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002381 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002382 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002383 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002384 audio_is_linear_pcm(config->format) &&
2385 audio_is_linear_pcm(halconfig.format) &&
2386 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002387 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2388 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002389 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002390 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002391 inStream.clear();
2392 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002393 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002394 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 }
2396
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002397 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002398 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002399 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2400 sp<MmapCaptureThread> thread =
2401 new MmapCaptureThread(this, *input,
2402 inHwDev, inputStream,
2403 primaryOutputDevice_l(), devices, mSystemReady);
2404 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002405 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2406 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002407 return thread;
2408 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002409#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002410 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2411 // or (re-)create if current Pipe is idle and does not match the new format
2412 sp<NBAIO_Sink> teeSink;
2413 enum {
2414 TEE_SINK_NO, // don't copy input
2415 TEE_SINK_NEW, // copy input using a new pipe
2416 TEE_SINK_OLD, // copy input using an existing pipe
2417 } kind;
2418 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2419 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2420 if (!mTeeSinkInputEnabled) {
2421 kind = TEE_SINK_NO;
2422 } else if (!Format_isValid(format)) {
2423 kind = TEE_SINK_NO;
2424 } else if (mRecordTeeSink == 0) {
2425 kind = TEE_SINK_NEW;
2426 } else if (mRecordTeeSink->getStrongCount() != 1) {
2427 kind = TEE_SINK_NO;
2428 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2429 kind = TEE_SINK_OLD;
2430 } else {
2431 kind = TEE_SINK_NEW;
2432 }
2433 switch (kind) {
2434 case TEE_SINK_NEW: {
2435 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2436 size_t numCounterOffers = 0;
2437 const NBAIO_Format offers[1] = {format};
2438 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2439 ALOG_ASSERT(index == 0);
2440 PipeReader *pipeReader = new PipeReader(*pipe);
2441 numCounterOffers = 0;
2442 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2443 ALOG_ASSERT(index == 0);
2444 mRecordTeeSink = pipe;
2445 mRecordTeeSource = pipeReader;
2446 teeSink = pipe;
2447 }
2448 break;
2449 case TEE_SINK_OLD:
2450 teeSink = mRecordTeeSink;
2451 break;
2452 case TEE_SINK_NO:
2453 default:
2454 break;
2455 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002456#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002457
2458 // Start record thread
2459 // RecordThread requires both input and output device indication to forward to audio
2460 // pre processing modules
2461 sp<RecordThread> thread = new RecordThread(this,
2462 inputStream,
2463 *input,
2464 primaryOutputDevice_l(),
2465 devices,
2466 mSystemReady
2467#ifdef TEE_SINK
2468 , teeSink
2469#endif
2470 );
2471 mRecordThreads.add(*input, thread);
2472 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2473 return thread;
2474 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475 }
2476
Eric Laurentcf2c0212014-07-25 16:20:43 -07002477 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 return 0;
2479}
2480
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002481status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482{
Glenn Kastend96c5722012-04-25 13:44:49 -07002483 return closeInput_nonvirtual(input);
2484}
2485
2486status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2487{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488 // keep strong reference on the record thread so that
2489 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002490 sp<RecordThread> recordThread;
2491 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 {
2493 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002494 recordThread = checkRecordThread_l(input);
2495 if (recordThread != 0) {
2496 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497
Eric Laurent6acd1d42017-01-04 14:23:29 -08002498 // If we still have effect chains, it means that a client still holds a handle
2499 // on at least one effect. We must either move the chain to an existing thread with the
2500 // same session ID or put it aside in case a new record thread is opened for a
2501 // new capture on the same session
2502 sp<EffectChain> chain;
2503 {
2504 Mutex::Autolock _sl(recordThread->mLock);
2505 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2506 // Note: maximum one chain per record thread
2507 if (effectChains.size() != 0) {
2508 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002509 }
2510 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002511 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002512 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002513 // This should only happen in case of overlap between one thread tear down and the
2514 // creation of its replacement
2515 size_t i;
2516 for (i = 0; i < mRecordThreads.size(); i++) {
2517 sp<RecordThread> t = mRecordThreads.valueAt(i);
2518 if (t == recordThread) {
2519 continue;
2520 }
2521 if (t->hasAudioSession(chain->sessionId()) != 0) {
2522 Mutex::Autolock _l(t->mLock);
2523 ALOGV("closeInput() found thread %d for effect session %d",
2524 t->id(), chain->sessionId());
2525 t->addEffectChain_l(chain);
2526 break;
2527 }
2528 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002529 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002530 if (i == mRecordThreads.size()) {
2531 putOrphanEffectChain_l(chain);
2532 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002533 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002534 mRecordThreads.removeItem(input);
2535 } else {
2536 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2537 if (mmapThread == 0) {
2538 return BAD_VALUE;
2539 }
2540 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002541 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002542 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2543 ioDesc->mIoHandle = input;
2544 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 }
Eric Laurent83b88082014-06-20 18:31:16 -07002546 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2547 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002548 if (recordThread != 0) {
2549 closeInputFinish(recordThread);
2550 } else if (mmapThread != 0) {
2551 mmapThread->exit();
2552 AudioStreamIn *in = mmapThread->clearInput();
2553 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2554 // from now on thread->mInput is NULL
2555 delete in;
2556 }
Eric Laurent83b88082014-06-20 18:31:16 -07002557 return NO_ERROR;
2558}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002560void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002561{
2562 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002563 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002564 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002565 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002566 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002567}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002569void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002570{
2571 mRecordThreads.removeItem(thread->mId);
2572 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573}
2574
Glenn Kastend2304db2014-02-03 07:40:31 -08002575status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576{
2577 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002578 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579
2580 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2581 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002582 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002583 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002584 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2585 mMmapThreads[i]->invalidateTracks(stream);
2586 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 return NO_ERROR;
2588}
2589
2590
Glenn Kasteneeecb982016-02-26 10:44:04 -08002591audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592{
Glenn Kasten9d003132016-04-06 14:38:09 -07002593 // This is a binder API, so a malicious client could pass in a bad parameter.
2594 // Check for that before calling the internal API nextUniqueId().
2595 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2596 ALOGE("newAudioUniqueId invalid use %d", use);
2597 return AUDIO_UNIQUE_ID_ALLOCATE;
2598 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002599 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600}
2601
Glenn Kastend848eb42016-03-08 13:42:11 -08002602void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002603{
2604 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002605 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002606 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2607 if (pid != -1 && (caller == getpid_cached)) {
2608 caller = pid;
2609 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002610
Eric Laurent021cf962014-05-13 10:18:14 -07002611 {
2612 Mutex::Autolock _cl(mClientLock);
2613 // Ignore requests received from processes not known as notification client. The request
2614 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2615 // called from a different pid leaving a stale session reference. Also we don't know how
2616 // to clear this reference if the client process dies.
2617 if (mNotificationClients.indexOfKey(caller) < 0) {
2618 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2619 return;
2620 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002621 }
2622
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002623 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002624 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002625 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002626 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2627 ref->mCnt++;
2628 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002629 return;
2630 }
2631 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002632 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2633 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002634}
2635
Glenn Kastend848eb42016-03-08 13:42:11 -08002636void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002637{
2638 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002639 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002640 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2641 if (pid != -1 && (caller == getpid_cached)) {
2642 caller = pid;
2643 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002644 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002645 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002646 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002647 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2648 ref->mCnt--;
2649 ALOGV(" decremented refcount to %d", ref->mCnt);
2650 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002651 mAudioSessionRefs.removeAt(i);
2652 delete ref;
2653 purgeStaleEffects_l();
2654 }
2655 return;
2656 }
2657 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002658 // If the caller is mediaserver it is likely that the session being released was acquired
2659 // on behalf of a process not in notification clients and we ignore the warning.
2660 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002661}
2662
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002663bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2664{
2665 size_t num = mAudioSessionRefs.size();
2666 for (size_t i = 0; i < num; i++) {
2667 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2668 if (ref->mSessionid == audioSession) {
2669 return true;
2670 }
2671 }
2672 return false;
2673}
2674
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002675void AudioFlinger::purgeStaleEffects_l() {
2676
Steve Block3856b092011-10-20 11:56:00 +01002677 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002678
2679 Vector< sp<EffectChain> > chains;
2680
2681 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2682 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002683 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002684 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2685 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002686 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2687 chains.push(ec);
2688 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002689 }
2690 }
2691 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2692 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002693 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002694 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2695 sp<EffectChain> ec = t->mEffectChains[j];
2696 chains.push(ec);
2697 }
2698 }
2699
2700 for (size_t i = 0; i < chains.size(); i++) {
2701 sp<EffectChain> ec = chains[i];
2702 int sessionid = ec->sessionId();
2703 sp<ThreadBase> t = ec->mThread.promote();
2704 if (t == 0) {
2705 continue;
2706 }
2707 size_t numsessionrefs = mAudioSessionRefs.size();
2708 bool found = false;
2709 for (size_t k = 0; k < numsessionrefs; k++) {
2710 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002711 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002712 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002713 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002714 found = true;
2715 break;
2716 }
2717 }
2718 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002719 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002720 // remove all effects from the chain
2721 while (ec->mEffects.size()) {
2722 sp<EffectModule> effect = ec->mEffects[0];
2723 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002724 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002725 if (effect->purgeHandles()) {
2726 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002727 }
2728 AudioSystem::unregisterEffect(effect->id());
2729 }
2730 }
2731 }
2732 return;
2733}
2734
Glenn Kasteneeecb982016-02-26 10:44:04 -08002735// checkThread_l() must be called with AudioFlinger::mLock held
2736AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2737{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002738 ThreadBase *thread = checkMmapThread_l(ioHandle);
2739 if (thread == 0) {
2740 switch (audio_unique_id_get_use(ioHandle)) {
2741 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2742 thread = checkPlaybackThread_l(ioHandle);
2743 break;
2744 case AUDIO_UNIQUE_ID_USE_INPUT:
2745 thread = checkRecordThread_l(ioHandle);
2746 break;
2747 default:
2748 break;
2749 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002750 }
2751 return thread;
2752}
2753
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002755AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756{
Glenn Kastena1117922012-01-26 10:53:32 -08002757 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758}
2759
2760// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002761AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762{
2763 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002764 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765}
2766
2767// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002768AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769{
Glenn Kastena1117922012-01-26 10:53:32 -08002770 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771}
2772
Eric Laurent6acd1d42017-01-04 14:23:29 -08002773// checkMmapThread_l() must be called with AudioFlinger::mLock held
2774AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2775{
2776 return mMmapThreads.valueFor(io).get();
2777}
2778
2779
2780// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2781AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2782{
Eric Laurent7459b902017-04-19 18:10:41 -07002783 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002784 if (volumeInterface == nullptr) {
2785 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2786 if (mmapThread != nullptr) {
2787 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002788 MmapPlaybackThread *mmapPlaybackThread =
2789 static_cast<MmapPlaybackThread *>(mmapThread);
2790 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002791 }
2792 }
2793 }
2794 return volumeInterface;
2795}
2796
2797Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2798{
2799 Vector <VolumeInterface *> volumeInterfaces;
2800 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002801 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002802 }
2803 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2804 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002805 MmapPlaybackThread *mmapPlaybackThread =
2806 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2807 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002808 }
2809 }
2810 return volumeInterfaces;
2811}
2812
Glenn Kasteneeecb982016-02-26 10:44:04 -08002813audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814{
Glenn Kasten9d003132016-04-06 14:38:09 -07002815 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002816 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002817 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2818 for (int retry = 0; retry < maxRetries; retry++) {
2819 // The cast allows wraparound from max positive to min negative instead of abort
2820 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2821 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2822 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2823 // allow wrap by skipping 0 and -1 for session ids
2824 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2825 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2826 return (audio_unique_id_t) (base | use);
2827 }
2828 }
2829 // We have no way of recovering from wraparound
2830 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2831 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832}
2833
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002834AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002835{
2836 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2837 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002838 if(thread->isDuplicating()) {
2839 continue;
2840 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002841 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002842 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002843 return thread;
2844 }
2845 }
2846 return NULL;
2847}
2848
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002849audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002850{
2851 PlaybackThread *thread = primaryPlaybackThread_l();
2852
2853 if (thread == NULL) {
2854 return 0;
2855 }
2856
Eric Laurentf1c04f92012-08-28 14:26:53 -07002857 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002858}
2859
Glenn Kastena7335632016-06-09 17:09:53 -07002860AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2861{
2862 size_t minFrameCount = 0;
2863 PlaybackThread *minThread = NULL;
2864 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2865 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2866 if (!thread->isDuplicating()) {
2867 size_t frameCount = thread->frameCountHAL();
2868 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2869 (frameCount == minFrameCount && thread->hasFastMixer() &&
2870 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2871 minFrameCount = frameCount;
2872 minThread = thread;
2873 }
2874 }
2875 }
2876 return minThread;
2877}
2878
Eric Laurenta011e352012-03-29 15:51:43 -07002879sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002880 audio_session_t triggerSession,
2881 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002882 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002883 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002884{
2885 Mutex::Autolock _l(mLock);
2886
2887 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2888 status_t playStatus = NAME_NOT_FOUND;
2889 status_t recStatus = NAME_NOT_FOUND;
2890 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2891 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2892 if (playStatus == NO_ERROR) {
2893 return event;
2894 }
2895 }
2896 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2897 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2898 if (recStatus == NO_ERROR) {
2899 return event;
2900 }
2901 }
2902 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2903 mPendingSyncEvents.add(event);
2904 } else {
2905 ALOGV("createSyncEvent() invalid event %d", event->type());
2906 event.clear();
2907 }
2908 return event;
2909}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002910
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911// ----------------------------------------------------------------------------
2912// Effect management
2913// ----------------------------------------------------------------------------
2914
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002915sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2916 return mEffectsFactoryHal;
2917}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918
Glenn Kastenf587ba52012-01-26 16:25:10 -08002919status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920{
2921 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002922 if (mEffectsFactoryHal.get()) {
2923 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2924 } else {
2925 return -ENODEV;
2926 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927}
2928
Glenn Kastenf587ba52012-01-26 16:25:10 -08002929status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930{
2931 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002932 if (mEffectsFactoryHal.get()) {
2933 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2934 } else {
2935 return -ENODEV;
2936 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937}
2938
Glenn Kasten5e92a782012-01-30 07:40:52 -08002939status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002940 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941{
2942 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002943 if (mEffectsFactoryHal.get()) {
2944 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2945 } else {
2946 return -ENODEV;
2947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948}
2949
2950
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002951sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 effect_descriptor_t *pDesc,
2953 const sp<IEffectClient>& effectClient,
2954 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002955 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002956 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002957 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002958 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959 status_t *status,
2960 int *id,
2961 int *enabled)
2962{
2963 status_t lStatus = NO_ERROR;
2964 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966
Eric Laurentb6436272016-12-07 19:24:50 -08002967 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2968 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2969 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2970 ALOGW_IF(pid != -1 && pid != callingPid,
2971 "%s uid %d pid %d tried to pass itself off as pid %d",
2972 __func__, callingUid, callingPid, pid);
2973 pid = callingPid;
2974 }
2975
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002976 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2977 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978
2979 if (pDesc == NULL) {
2980 lStatus = BAD_VALUE;
2981 goto Exit;
2982 }
2983
Eric Laurent84e9a102010-09-23 16:10:16 -07002984 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002985 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002986 lStatus = PERMISSION_DENIED;
2987 goto Exit;
2988 }
2989
Dima Zavinfce7a472011-04-19 22:30:36 -07002990 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002991 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002992 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002993 lStatus = PERMISSION_DENIED;
2994 goto Exit;
2995 }
2996
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002997 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002998 lStatus = NO_INIT;
2999 goto Exit;
3000 }
3001
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003003 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003005 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003007 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 goto Exit;
3009 }
3010 } else {
3011 // if uuid is not specified, look for an available implementation
3012 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003013 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003014 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 lStatus = BAD_VALUE;
3016 goto Exit;
3017 }
3018 uint32_t numEffects = 0;
3019 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003020 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 bool found = false;
3022
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003023 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003025 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 goto Exit;
3027 }
3028 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003029 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003031 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 continue;
3033 }
3034 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3035 // If matching type found save effect descriptor. If the session is
3036 // 0 and the effect is not auxiliary, continue enumeration in case
3037 // an auxiliary version of this effect type is available
3038 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003039 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003040 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3042 break;
3043 }
3044 }
3045 }
3046 if (!found) {
3047 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003048 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 goto Exit;
3050 }
3051 // For same effect type, chose auxiliary version over insert version if
3052 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003053 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003054 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003055 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 }
3057 }
3058
3059 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003060 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3062 lStatus = INVALID_OPERATION;
3063 goto Exit;
3064 }
3065
Eric Laurent59255e42011-07-27 19:49:51 -07003066 // check recording permission for visualizer
3067 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003068 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003069 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003070 lStatus = PERMISSION_DENIED;
3071 goto Exit;
3072 }
3073
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003075 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003076 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003077 // if the output returned by getOutputForEffect() is removed before we lock the
3078 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3079 // and we will exit safely
3080 io = AudioSystem::getOutputForEffect(&desc);
3081 ALOGV("createEffect got output %d", io);
3082 }
3083
3084 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085
3086 // If output is not specified try to find a matching audio session ID in one of the
3087 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003088 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3089 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003090 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003091 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003092 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3093 // output must be specified by AudioPolicyManager when using session
3094 // AUDIO_SESSION_OUTPUT_STAGE
3095 lStatus = BAD_VALUE;
3096 goto Exit;
3097 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003098 // look for the thread where the specified audio session is present
3099 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3100 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3101 io = mPlaybackThreads.keyAt(i);
3102 break;
3103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003105 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003106 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3107 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3108 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003109 break;
3110 }
3111 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003112 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003113 if (io == AUDIO_IO_HANDLE_NONE) {
3114 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3115 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3116 io = mMmapThreads.keyAt(i);
3117 break;
3118 }
3119 }
3120 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003121 // If no output thread contains the requested session ID, default to
3122 // first output. The effect chain will be moved to the correct output
3123 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003124 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003125 io = mPlaybackThreads.keyAt(0);
3126 }
Steve Block3856b092011-10-20 11:56:00 +01003127 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003128 }
3129 ThreadBase *thread = checkRecordThread_l(io);
3130 if (thread == NULL) {
3131 thread = checkPlaybackThread_l(io);
3132 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003133 thread = checkMmapThread_l(io);
3134 if (thread == NULL) {
3135 ALOGE("createEffect() unknown output thread");
3136 lStatus = BAD_VALUE;
3137 goto Exit;
3138 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003139 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003140 } else {
3141 // Check if one effect chain was awaiting for an effect to be created on this
3142 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003143 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003144 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003145 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003146 thread->addEffectChain_l(chain);
3147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003149
Eric Laurent021cf962014-05-13 10:18:14 -07003150 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003152 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003153 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003154 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003155 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003156 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003157 // remove local strong reference to Client with mClientLock held
3158 Mutex::Autolock _cl(mClientLock);
3159 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003160 } else {
3161 // handle must be valid here, but check again to be safe.
3162 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 }
3165
haobo101735295ff7b0d2017-03-17 17:44:03 +08003166 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3167 // handle must be cleared outside lock.
3168 handle.clear();
3169 }
3170
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003172 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 return handle;
3174}
3175
Glenn Kastend848eb42016-03-08 13:42:11 -08003176status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003177 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003178{
Steve Block3856b092011-10-20 11:56:00 +01003179 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003180 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003181 Mutex::Autolock _l(mLock);
3182 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003183 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003184 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 }
Eric Laurentde070132010-07-13 04:45:46 -07003186 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3187 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003188 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003189 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 }
Eric Laurentde070132010-07-13 04:45:46 -07003191 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3192 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003193 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003194 return BAD_VALUE;
3195 }
3196
3197 Mutex::Autolock _dl(dstThread->mLock);
3198 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003199 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200}
3201
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003202// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003203status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003204 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003205 AudioFlinger::PlaybackThread *dstThread,
3206 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003207{
Steve Block3856b092011-10-20 11:56:00 +01003208 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003209 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003210
Eric Laurent59255e42011-07-27 19:49:51 -07003211 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003212 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003213 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003214 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003215 return INVALID_OPERATION;
3216 }
3217
Eric Laurent4c415062016-06-17 16:14:16 -07003218 // Check whether the destination thread and all effects in the chain are compatible
3219 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003220 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003221 " destination thread %p is not compatible with effects in the chain",
3222 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003223 return INVALID_OPERATION;
3224 }
3225
Eric Laurent39e94f82010-07-28 01:32:47 -07003226 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003227 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003228 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003229 // removed.
3230 srcThread->removeEffectChain_l(chain);
3231
3232 // transfer all effects one by one so that new effect chain is created on new thread with
3233 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003234 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003235 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003236 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003237 Vector< sp<EffectModule> > removed;
3238 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003239 while (effect != 0) {
3240 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003241 removed.add(effect);
3242 status = dstThread->addEffect_l(effect);
3243 if (status != NO_ERROR) {
3244 break;
3245 }
Eric Laurentec35a142011-10-05 17:42:25 -07003246 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3247 if (effect->state() == EffectModule::ACTIVE ||
3248 effect->state() == EffectModule::STOPPING) {
3249 effect->start();
3250 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003251 // if the move request is not received from audio policy manager, the effect must be
3252 // re-registered with the new strategy and output
3253 if (dstChain == 0) {
3254 dstChain = effect->chain().promote();
3255 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003256 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003257 status = NO_INIT;
3258 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003259 }
3260 strategy = dstChain->strategy();
3261 }
3262 if (reRegister) {
3263 AudioSystem::unregisterEffect(effect->id());
3264 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003265 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003266 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003267 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003268 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003269 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003270 }
Eric Laurentde070132010-07-13 04:45:46 -07003271 effect = chain->getEffectFromId_l(0);
3272 }
3273
Eric Laurent5baf2af2013-09-12 17:37:00 -07003274 if (status != NO_ERROR) {
3275 for (size_t i = 0; i < removed.size(); i++) {
3276 srcThread->addEffect_l(removed[i]);
3277 if (dstChain != 0 && reRegister) {
3278 AudioSystem::unregisterEffect(removed[i]->id());
3279 AudioSystem::registerEffect(&removed[i]->desc(),
3280 srcThread->id(),
3281 strategy,
3282 sessionId,
3283 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003284 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003285 }
3286 }
3287 }
3288
3289 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290}
3291
Eric Laurent5baf2af2013-09-12 17:37:00 -07003292bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003293{
3294 if (mGlobalEffectEnableTime != 0 &&
3295 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3296 return true;
3297 }
3298
3299 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3300 sp<EffectChain> ec =
3301 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003302 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003303 return true;
3304 }
3305 }
3306 return false;
3307}
3308
Eric Laurent5baf2af2013-09-12 17:37:00 -07003309void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003310{
3311 Mutex::Autolock _l(mLock);
3312
3313 mGlobalEffectEnableTime = systemTime();
3314
3315 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3316 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3317 if (t->mType == ThreadBase::OFFLOAD) {
3318 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3319 }
3320 }
3321
3322}
3323
Eric Laurentaaa44472014-09-12 17:41:50 -07003324status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3325{
Eric Laurentd8365c52017-07-16 15:27:05 -07003326 // clear possible suspended state before parking the chain so that it starts in default state
3327 // when attached to a new record thread
3328 chain->setEffectSuspended_l(FX_IID_AEC, false);
3329 chain->setEffectSuspended_l(FX_IID_NS, false);
3330
Glenn Kastend848eb42016-03-08 13:42:11 -08003331 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003332 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003333 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003334 if (index >= 0) {
3335 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3336 return ALREADY_EXISTS;
3337 }
3338 mOrphanEffectChains.add(session, chain);
3339 return NO_ERROR;
3340}
3341
3342sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3343{
3344 sp<EffectChain> chain;
3345 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003346 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003347 if (index >= 0) {
3348 chain = mOrphanEffectChains.valueAt(index);
3349 mOrphanEffectChains.removeItemsAt(index);
3350 }
3351 return chain;
3352}
3353
3354bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3355{
3356 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003357 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003358 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003359 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003360 if (index >= 0) {
3361 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003362 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003363 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003364 mOrphanEffectChains.removeItemsAt(index);
3365 }
3366 return true;
3367 }
3368 return false;
3369}
3370
3371
Glenn Kastenda6ef132013-01-10 12:31:01 -08003372struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003373#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3374 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003375};
3376
3377int comparEntry(const void *p1, const void *p2)
3378{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003379 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003380}
3381
Glenn Kasten46909e72013-02-26 09:20:22 -08003382#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003383void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384{
Eric Laurent81784c32012-11-19 14:55:58 -08003385 NBAIO_Source *teeSource = source.get();
3386 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003387 // .wav rotation
3388 // There is a benign race condition if 2 threads call this simultaneously.
3389 // They would both traverse the directory, but the result would simply be
3390 // failures at unlink() which are ignored. It's also unlikely since
3391 // normally dumpsys is only done by bugreport or from the command line.
Andy Hungb1fe6e12018-04-19 19:20:00 -07003392 char teePath[PATH_MAX] = "/data/misc/audioserver";
Glenn Kastenda6ef132013-01-10 12:31:01 -08003393 size_t teePathLen = strlen(teePath);
3394 DIR *dir = opendir(teePath);
3395 teePath[teePathLen++] = '/';
3396 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003397#define TEE_MAX_SORT 20 // number of entries to sort
3398#define TEE_MAX_KEEP 10 // number of entries to keep
3399 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003400 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003401 while (entryCount < TEE_MAX_SORT) {
Andy Hungb1fe6e12018-04-19 19:20:00 -07003402 errno = 0; // clear errno before readdir() to track potential errors.
3403 const struct dirent *result = readdir(dir);
3404 if (result == nullptr) {
3405 ALOGW_IF(errno != 0, "tee readdir() failure %s", strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003406 break;
3407 }
3408 // ignore non .wav file entries
Andy Hungb1fe6e12018-04-19 19:20:00 -07003409 const size_t nameLen = strlen(result->d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003410 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Andy Hungb1fe6e12018-04-19 19:20:00 -07003411 strcmp(&result->d_name[nameLen - 4], ".wav")) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003412 continue;
3413 }
Andy Hungb1fe6e12018-04-19 19:20:00 -07003414 (void)audio_utils_strlcpy(entries[entryCount++].mFileName, result->d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003415 }
3416 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003417 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003418 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003419 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3420 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003421 (void) unlink(teePath);
3422 }
3423 }
3424 } else {
3425 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003426 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003427 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003428 }
3429 }
Eric Laurent81784c32012-11-19 14:55:58 -08003430 char teeTime[16];
3431 struct timeval tv;
3432 gettimeofday(&tv, NULL);
3433 struct tm tm;
3434 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003435 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003436 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3437 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003438 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3439 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003440 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003441 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003442 char wavHeader[44];
3443 memcpy(wavHeader,
3444 "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",
3445 sizeof(wavHeader));
3446 NBAIO_Format format = teeSource->format();
3447 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003448 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003449 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003450 wavHeader[22] = channelCount; // number of channels
3451 wavHeader[24] = sampleRate; // sample rate
3452 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003453 wavHeader[32] = frameSize; // block alignment
3454 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003455 write(teeFd, wavHeader, sizeof(wavHeader));
3456 size_t total = 0;
3457 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003458#define TEE_SINK_READ 1024 // frames per I/O operation
3459 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003460 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003461 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003462 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003463 bool wasFirstRead = firstRead;
3464 firstRead = false;
3465 if (actual <= 0) {
3466 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3467 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003468 }
Eric Laurent81784c32012-11-19 14:55:58 -08003469 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003470 }
Eric Laurent81784c32012-11-19 14:55:58 -08003471 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003472 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003473 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003474 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003475 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003476 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003477 uint32_t temp = 44 + total * frameSize - 8;
3478 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003479 write(teeFd, &temp, sizeof(temp));
3480 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003481 temp = total * frameSize;
3482 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003483 write(teeFd, &temp, sizeof(temp));
3484 close(teeFd);
Glenn Kasten9e756632017-10-03 13:01:09 -07003485 // TODO Should create file with temporary name and then rename to final if non-empty.
3486 if (total > 0) {
3487 if (fd >= 0) {
3488 dprintf(fd, "tee copied to %s\n", teePath);
3489 }
3490 } else {
3491 unlink(teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003492 }
Eric Laurent59255e42011-07-27 19:49:51 -07003493 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003494 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003495 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003496 }
Eric Laurent59255e42011-07-27 19:49:51 -07003497 }
3498 }
3499}
Glenn Kasten46909e72013-02-26 09:20:22 -08003500#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003501
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502// ----------------------------------------------------------------------------
3503
3504status_t AudioFlinger::onTransact(
3505 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3506{
3507 return BnAudioFlinger::onTransact(code, data, reply, flags);
3508}
3509
Glenn Kasten63238ef2015-03-02 15:50:29 -08003510} // namespace android