blob: 803338213e29dc9cd3a4c6d02e0bb5b84f30775b [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
42
Steven Morelandf0c02ce2018-02-23 14:53:55 -080043#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <cutils/properties.h>
45
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Mathias Agopian65ab4712010-07-14 17:59:35 -070048#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080049#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Andy Hung6770c6f2015-04-07 13:43:36 -070051#include <media/AudioResamplerPublic.h>
52
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_visualizer.h>
54#include <system/audio_effects/effect_ns.h>
55#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Eric Laurentfeb0db62011-07-22 09:04:31 -070059#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080060
Glenn Kasten9e58b552013-01-18 15:09:48 -080061#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070062#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080063#include <media/nbaio/Pipe.h>
64#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070065#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080066#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070067#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080068
rago3bd1c872016-09-26 12:58:14 -070069//#define BUFLOG_NDEBUG 0
70#include <BufLog.h>
71
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080072#include "TypedLogger.h"
73
Mathias Agopian65ab4712010-07-14 17:59:35 -070074// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070075
John Grossman1c345192012-03-27 14:00:17 -070076// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
Eric Laurentde070132010-07-13 04:45:46 -070088
Mathias Agopian65ab4712010-07-14 17:59:35 -070089namespace android {
90
Glenn Kastenec1d6b52011-12-12 09:04:45 -080091static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
92static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070093static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070094static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten58912562012-04-03 10:45:00 -070096
John Grossman4ff14ba2012-02-08 16:37:41 -080097nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080098
Eric Laurent81784c32012-11-19 14:55:58 -080099uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700100
Eric Laurentfc235202016-12-20 18:48:17 -0800101
Glenn Kasten46909e72013-02-26 09:20:22 -0800102#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800103bool AudioFlinger::mTeeSinkInputEnabled = false;
104bool AudioFlinger::mTeeSinkOutputEnabled = false;
105bool AudioFlinger::mTeeSinkTrackEnabled = false;
106
107size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
108size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
109size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800110#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800111
Eric Laurent813e2a72013-08-31 12:59:48 -0700112// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
113// we define a minimum time during which a global effect is considered enabled.
114static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
115
Eric Laurentfc235202016-12-20 18:48:17 -0800116Mutex gLock;
117wp<AudioFlinger> gAudioFlinger;
118
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700119// Keep a strong reference to media.log service around forever.
120// The service is within our parent process so it can never die in a way that we could observe.
121// These two variables are const after initialization.
122static sp<IBinder> sMediaLogServiceAsBinder;
123static sp<IMediaLogService> sMediaLogService;
124
125static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
126
127static void sMediaLogInit()
128{
129 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
130 if (sMediaLogServiceAsBinder != 0) {
131 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
132 }
133}
134
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135// ----------------------------------------------------------------------------
136
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700137std::string formatToString(audio_format_t format) {
138 std::string result;
139 FormatConverter::toString(format, result);
140 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800141}
142
Mathias Agopian65ab4712010-07-14 17:59:35 -0700143// ----------------------------------------------------------------------------
144
145AudioFlinger::AudioFlinger()
146 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800147 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800148 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800149 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700150 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800151 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800152 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700153 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700155 mBtNrecIsOff(false),
156 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700157 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800158 mTotalMemory(0),
159 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700160 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700161 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700162{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700163 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
164 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
165 // zero ID has a special meaning, so unavailable
166 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
167 }
168
Glenn Kasten949a9262013-04-16 12:35:20 -0700169 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800170 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800171 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800172 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
173 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700174 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800175 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700176
Wei Jia3f273d12015-11-24 09:06:49 -0800177 // reset battery stats.
178 // if the audio service has crashed, battery stats could be left
179 // in bad state, reset the state upon service start.
180 BatteryNotifier::getInstance().noteResetAudio();
181
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700182 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700183 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
184
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800185 mMediaLogNotifier->run("MediaLogNotifier");
186
Glenn Kasten46909e72013-02-26 09:20:22 -0800187#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800188 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800189 (void) property_get("ro.debuggable", value, "0");
190 int debuggable = atoi(value);
191 int teeEnabled = 0;
192 if (debuggable) {
193 (void) property_get("af.tee", value, "0");
194 teeEnabled = atoi(value);
195 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800196 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700197 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700199 }
200 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700202 }
203 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800204 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700205 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800206#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700207}
208
209void AudioFlinger::onFirstRef()
210{
Eric Laurent93575202011-01-18 18:39:02 -0800211 Mutex::Autolock _l(mLock);
212
Dima Zavin799a70e2011-04-18 16:57:27 -0700213 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 char val_str[PROPERTY_VALUE_MAX] = { 0 };
215 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
216 uint32_t int_val;
217 if (1 == sscanf(val_str, "%u", &int_val)) {
218 mStandbyTimeInNsecs = milliseconds(int_val);
219 ALOGI("Using %u mSec as standby time.", int_val);
220 } else {
221 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
222 ALOGI("Using default %u mSec as standby time.",
223 (uint32_t)(mStandbyTimeInNsecs / 1000000));
224 }
225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226
Eric Laurent1c333e22014-05-20 10:48:17 -0700227 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700228
Eric Laurenta4c5a552012-03-29 10:12:40 -0700229 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800230
231 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232}
233
234AudioFlinger::~AudioFlinger()
235{
236 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700237 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700238 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239 }
240 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700241 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700242 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700244
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800245 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
246 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700247 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700249
250 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700251 if (sMediaLogService != 0) {
252 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
253 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
254 mUnregisteredWriters.pop();
255 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700256 }
257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258}
259
Eric Laurentfc235202016-12-20 18:48:17 -0800260//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800261__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800262status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
263 const audio_attributes_t *attr,
264 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700265 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800266 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800267 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800268 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700269 sp<MmapStreamInterface>& interface,
270 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800271{
272 sp<AudioFlinger> af;
273 {
274 Mutex::Autolock _l(gLock);
275 af = gAudioFlinger.promote();
276 }
277 status_t ret = NO_INIT;
278 if (af != 0) {
279 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800280 direction, attr, config, client, deviceId,
281 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800282 }
283 return ret;
284}
285
Eric Laurent6acd1d42017-01-04 14:23:29 -0800286status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
287 const audio_attributes_t *attr,
288 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700289 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800290 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800291 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800292 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700293 sp<MmapStreamInterface>& interface,
294 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800295{
296 status_t ret = initCheck();
297 if (ret != NO_ERROR) {
298 return ret;
299 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800300 audio_session_t actualSessionId = *sessionId;
301 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
302 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
303 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800304 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700305 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800306 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
307 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
308 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
309 fullConfig.sample_rate = config->sample_rate;
310 fullConfig.channel_mask = config->channel_mask;
311 fullConfig.format = config->format;
312 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800313 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200314 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800315 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800316 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
317 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700318 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800319 } else {
320 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800321 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800322 client.clientPid,
323 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800324 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800325 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700326 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800327 }
328 if (ret != NO_ERROR) {
329 return ret;
330 }
331
332 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
333 // audio policy manager and we can retrieve it
334 sp<MmapThread> thread = mMmapThreads.valueFor(io);
335 if (thread != 0) {
336 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800337 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700338 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800339 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800340 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700341 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800342 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700343 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800344 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700345 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800346 ret = NO_INIT;
347 }
348
349 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
350
Eric Laurentfc235202016-12-20 18:48:17 -0800351 return ret;
352}
353
Eric Laurenta4c5a552012-03-29 10:12:40 -0700354static const char * const audio_interfaces[] = {
355 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
356 AUDIO_HARDWARE_MODULE_ID_A2DP,
357 AUDIO_HARDWARE_MODULE_ID_USB,
358};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700359
Phil Burk062e67a2015-02-11 13:40:50 -0800360AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700361 audio_module_handle_t module,
362 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700363{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700364 // if module is 0, the request comes from an old policy manager and we should load
365 // well known modules
366 if (module == 0) {
367 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700368 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700369 loadHwModule_l(audio_interfaces[i]);
370 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700371 // then try to find a module supporting the requested device.
372 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
373 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700374 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
375 uint32_t supportedDevices;
376 if (dev->getSupportedDevices(&supportedDevices) == OK &&
377 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700378 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700379 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700380 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700381 } else {
382 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700383 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
384 if (audioHwDevice != NULL) {
385 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700386 }
387 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700388
Dima Zavin799a70e2011-04-18 16:57:27 -0700389 return NULL;
390}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700391
Glenn Kasten0f11b512014-01-31 16:18:54 -0800392void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393{
394 const size_t SIZE = 256;
395 char buffer[SIZE];
396 String8 result;
397
398 result.append("Clients:\n");
399 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800400 sp<Client> client = mClients.valueAt(i).promote();
401 if (client != 0) {
402 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
403 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 }
405 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700406
Eric Laurentd1b28d42013-09-18 18:47:13 -0700407 result.append("Notification Clients:\n");
408 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
409 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
410 result.append(buffer);
411 }
412
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700413 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800414 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700415 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
416 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800417 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700418 result.append(buffer);
419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421}
422
423
Glenn Kasten0f11b512014-01-31 16:18:54 -0800424void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425{
426 const size_t SIZE = 256;
427 char buffer[SIZE];
428 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800429 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700430
John Grossman4ff14ba2012-02-08 16:37:41 -0800431 snprintf(buffer, SIZE, "Hardware status: %d\n"
432 "Standby Time mSec: %u\n",
433 hardwareStatus,
434 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 result.append(buffer);
436 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437}
438
Glenn Kasten0f11b512014-01-31 16:18:54 -0800439void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440{
441 const size_t SIZE = 256;
442 char buffer[SIZE];
443 String8 result;
444 snprintf(buffer, SIZE, "Permission Denial: "
445 "can't dump AudioFlinger from pid=%d, uid=%d\n",
446 IPCThreadState::self()->getCallingPid(),
447 IPCThreadState::self()->getCallingUid());
448 result.append(buffer);
449 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450}
451
Eric Laurent81784c32012-11-19 14:55:58 -0800452bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453{
454 bool locked = false;
455 for (int i = 0; i < kDumpLockRetries; ++i) {
456 if (mutex.tryLock() == NO_ERROR) {
457 locked = true;
458 break;
459 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800460 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 }
462 return locked;
463}
464
465status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
466{
Glenn Kasten44deb052012-02-05 18:09:08 -0800467 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468 dumpPermissionDenial(fd, args);
469 } else {
470 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800471 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 if (!hardwareLocked) {
473 String8 result(kHardwareLockedString);
474 write(fd, result.string(), result.size());
475 } else {
476 mHardwareLock.unlock();
477 }
478
Eric Laurent81784c32012-11-19 14:55:58 -0800479 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480
481 // failed to lock - AudioFlinger is probably deadlocked
482 if (!locked) {
483 String8 result(kDeadlockedString);
484 write(fd, result.string(), result.size());
485 }
486
Eric Laurent021cf962014-05-13 10:18:14 -0700487 bool clientLocked = dumpTryLock(mClientLock);
488 if (!clientLocked) {
489 String8 result(kClientLockedString);
490 write(fd, result.string(), result.size());
491 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700492
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700493 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700494 mEffectsFactoryHal->dumpEffects(fd);
495 } else {
496 String8 result(kNoEffectsFactory);
497 write(fd, result.string(), result.size());
498 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700499
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700501 if (clientLocked) {
502 mClientLock.unlock();
503 }
504
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505 dumpInternals(fd, args);
506
507 // dump playback threads
508 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
509 mPlaybackThreads.valueAt(i)->dump(fd, args);
510 }
511
512 // dump record threads
513 for (size_t i = 0; i < mRecordThreads.size(); i++) {
514 mRecordThreads.valueAt(i)->dump(fd, args);
515 }
516
Eric Laurent6acd1d42017-01-04 14:23:29 -0800517 // dump mmap threads
518 for (size_t i = 0; i < mMmapThreads.size(); i++) {
519 mMmapThreads.valueAt(i)->dump(fd, args);
520 }
521
Eric Laurentaaa44472014-09-12 17:41:50 -0700522 // dump orphan effect chains
523 if (mOrphanEffectChains.size() != 0) {
524 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
525 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
526 mOrphanEffectChains.valueAt(i)->dump(fd, args);
527 }
528 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700529 // dump all hardware devs
530 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700531 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
532 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700534
Glenn Kasten46909e72013-02-26 09:20:22 -0800535#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700536 // dump the serially shared record tee sink
537 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700538 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700539 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800540#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700541
rago3bd1c872016-09-26 12:58:14 -0700542 BUFLOG_RESET;
543
Glenn Kastend65d73c2012-06-22 17:21:07 -0700544 if (locked) {
545 mLock.unlock();
546 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800547
548 // append a copy of media.log here by forwarding fd to it, but don't attempt
549 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700550 if (sMediaLogServiceAsBinder != 0) {
551 dprintf(fd, "\nmedia.log:\n");
552 Vector<String16> args;
553 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800554 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700555
556 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700557 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700558 bool unreachableMemory = false;
559 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700560 if (arg == String16("-m")) {
561 dumpMem = true;
562 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700563 unreachableMemory = true;
564 }
565 }
566
Andy Hung07b745e2016-05-23 16:21:07 -0700567 if (dumpMem) {
568 dprintf(fd, "\nDumping memory:\n");
569 std::string s = dumpMemoryAddresses(100 /* limit */);
570 write(fd, s.c_str(), s.size());
571 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700572 if (unreachableMemory) {
573 dprintf(fd, "\nDumping unreachable memory:\n");
574 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700575 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700576 write(fd, s.c_str(), s.size());
577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 }
579 return NO_ERROR;
580}
581
Eric Laurent021cf962014-05-13 10:18:14 -0700582sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800583{
Eric Laurent021cf962014-05-13 10:18:14 -0700584 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800585 // If pid is already in the mClients wp<> map, then use that entry
586 // (for which promote() is always != 0), otherwise create a new entry and Client.
587 sp<Client> client = mClients.valueFor(pid).promote();
588 if (client == 0) {
589 client = new Client(this, pid);
590 mClients.add(pid, client);
591 }
592
593 return client;
594}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595
Glenn Kasten9e58b552013-01-18 15:09:48 -0800596sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
597{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700598 // If there is no memory allocated for logs, return a dummy writer that does nothing.
599 // Similarly if we can't contact the media.log service, also return a dummy writer.
600 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800601 return new NBLog::Writer();
602 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700603 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
604 // If allocation fails, consult the vector of previously unregistered writers
605 // and garbage-collect one or more them until an allocation succeeds
606 if (shared == 0) {
607 Mutex::Autolock _l(mUnregisteredWritersLock);
608 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
609 {
610 // Pick the oldest stale writer to garbage-collect
611 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
612 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700613 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700614 // Now the media.log remote reference to IMemory is gone. When our last local
615 // reference to IMemory also drops to zero at end of this block,
616 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
617 }
618 // Re-attempt the allocation
619 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
620 if (shared != 0) {
621 goto success;
622 }
623 }
624 // Even after garbage-collecting all old writers, there is still not enough memory,
625 // so return a dummy writer
626 return new NBLog::Writer();
627 }
628success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800629 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
630 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
631 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700632 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800633 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800634}
635
636void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
637{
Glenn Kasten685ef092013-02-04 08:15:34 -0800638 if (writer == 0) {
639 return;
640 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800641 sp<IMemory> iMemory(writer->getIMemory());
642 if (iMemory == 0) {
643 return;
644 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700645 // Rather than removing the writer immediately, append it to a queue of old writers to
646 // be garbage-collected later. This allows us to continue to view old logs for a while.
647 Mutex::Autolock _l(mUnregisteredWritersLock);
648 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800649}
650
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651// IAudioFlinger interface
652
Eric Laurent21da6472017-11-09 16:29:26 -0800653sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
654 CreateTrackOutput& output,
655 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656{
657 sp<PlaybackThread::Track> track;
658 sp<TrackHandle> trackHandle;
659 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800661 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800662 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663
Eric Laurent21da6472017-11-09 16:29:26 -0800664 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700665 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800666 uid_t clientUid = input.clientInfo.clientUid;
667 if (!isTrustedCallingUid(callingUid)) {
668 ALOGW_IF(clientUid != callingUid,
669 "%s uid %d tried to pass itself off as %d",
670 __FUNCTION__, callingUid, clientUid);
671 clientUid = callingUid;
672 updatePid = true;
673 }
674 pid_t clientPid = input.clientInfo.clientPid;
675 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700676 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800677 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700678 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800679 __func__, callingUid, callingPid, clientPid);
680 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700681 }
682
Eric Laurent21da6472017-11-09 16:29:26 -0800683 audio_session_t sessionId = input.sessionId;
684 if (sessionId == AUDIO_SESSION_ALLOCATE) {
685 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800686 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
687 lStatus = BAD_VALUE;
688 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800689 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800690
Eric Laurent21da6472017-11-09 16:29:26 -0800691 output.sessionId = sessionId;
692 output.outputId = AUDIO_IO_HANDLE_NONE;
693 output.selectedDeviceId = input.selectedDeviceId;
694
695 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200696 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800697 &output.selectedDeviceId, &portId);
698
699 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
700 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
701 goto Exit;
702 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800703 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
704 // but if someone uses binder directly they could bypass that and cause us to crash
705 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000706 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 lStatus = BAD_VALUE;
708 goto Exit;
709 }
710
Glenn Kasten53b5d092014-02-05 10:00:23 -0800711 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800712 if (!audio_is_output_channel(input.config.channel_mask)) {
713 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800714 lStatus = BAD_VALUE;
715 goto Exit;
716 }
717
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700718 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800719 if (!audio_is_valid_format(input.config.format)) {
720 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700721 lStatus = BAD_VALUE;
722 goto Exit;
723 }
724
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 {
726 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800727 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800729 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 lStatus = BAD_VALUE;
731 goto Exit;
732 }
733
Eric Laurent21da6472017-11-09 16:29:26 -0800734 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735
Glenn Kastene848bd92014-03-13 15:00:32 -0700736 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800737 // check if an effect chain with the same session ID is present on another
738 // output thread and move it here.
739 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
740 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
741 if (mPlaybackThreads.keyAt(i) != output.outputId) {
742 uint32_t sessions = t->hasAudioSession(sessionId);
743 if (sessions & ThreadBase::EFFECT_SESSION) {
744 effectThread = t.get();
745 break;
Eric Laurentde070132010-07-13 04:45:46 -0700746 }
747 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 }
Eric Laurent21da6472017-11-09 16:29:26 -0800749 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750
Eric Laurent21da6472017-11-09 16:29:26 -0800751 output.sampleRate = input.config.sample_rate;
752 output.frameCount = input.frameCount;
753 output.notificationFrameCount = input.notificationFrameCount;
754 output.flags = input.flags;
755
756 track = thread->createTrack_l(client, streamType, &output.sampleRate, input.config.format,
757 input.config.channel_mask,
758 &output.frameCount, &output.notificationFrameCount,
759 input.notificationsPerBuffer, input.speed,
760 input.sharedBuffer, sessionId, &output.flags,
761 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800762 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700763 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700764
Eric Laurent21da6472017-11-09 16:29:26 -0800765 output.afFrameCount = thread->frameCount();
766 output.afSampleRate = thread->sampleRate();
767 output.afLatencyMs = thread->latency();
768
Eric Laurent39e94f82010-07-28 01:32:47 -0700769 // move effect chain to this output thread if an effect on same session was waiting
770 // for a track to be created
771 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700772 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700773 Mutex::Autolock _dl(thread->mLock);
774 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800775 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700776 }
Eric Laurenta011e352012-03-29 15:51:43 -0700777
778 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700779 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800780 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700781 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700782 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700783 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700784 } else {
785 mPendingSyncEvents[i]->cancel();
786 }
Eric Laurenta011e352012-03-29 15:51:43 -0700787 mPendingSyncEvents.removeAt(i);
788 i--;
789 }
790 }
791 }
Glenn Kastene198c362013-08-13 09:13:36 -0700792
Eric Laurent21da6472017-11-09 16:29:26 -0800793 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 }
Glenn Kastene198c362013-08-13 09:13:36 -0700795
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700796 if (lStatus != NO_ERROR) {
797 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700798 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700799 // Don't hold mClientLock when releasing the reference on the track as the
800 // destructor will acquire it.
801 {
802 Mutex::Autolock _cl(mClientLock);
803 client.clear();
804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700806 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 }
808
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700809 // return handle to client
810 trackHandle = new TrackHandle(track);
811
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800813 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
814 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
815 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700816 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return trackHandle;
818}
819
Glenn Kasten2c073da2016-02-26 09:14:08 -0800820uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821{
822 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800823 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800825 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 return 0;
827 }
828 return thread->sampleRate();
829}
830
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800831audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832{
833 Mutex::Autolock _l(mLock);
834 PlaybackThread *thread = checkPlaybackThread_l(output);
835 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000836 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800837 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 }
839 return thread->format();
840}
841
Glenn Kasten2c073da2016-02-26 09:14:08 -0800842size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843{
844 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800845 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800847 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 return 0;
849 }
Glenn Kasten58912562012-04-03 10:45:00 -0700850 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
851 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 return thread->frameCount();
853}
854
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700855size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
856{
857 Mutex::Autolock _l(mLock);
858 ThreadBase *thread = checkThread_l(ioHandle);
859 if (thread == NULL) {
860 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
861 return 0;
862 }
863 return thread->frameCountHAL();
864}
865
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800866uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867{
868 Mutex::Autolock _l(mLock);
869 PlaybackThread *thread = checkPlaybackThread_l(output);
870 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800871 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 return 0;
873 }
874 return thread->latency();
875}
876
877status_t AudioFlinger::setMasterVolume(float value)
878{
Eric Laurenta1884f92011-08-23 08:25:03 -0700879 status_t ret = initCheck();
880 if (ret != NO_ERROR) {
881 return ret;
882 }
883
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 // check calling permissions
885 if (!settingsAllowed()) {
886 return PERMISSION_DENIED;
887 }
888
Eric Laurenta4c5a552012-03-29 10:12:40 -0700889 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700890 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700891
John Grossmanee578c02012-07-23 17:05:46 -0700892 // Set master volume in the HALs which support it.
893 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
894 AutoMutex lock(mHardwareLock);
895 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800896
John Grossmanee578c02012-07-23 17:05:46 -0700897 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
898 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700899 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800900 }
John Grossmanee578c02012-07-23 17:05:46 -0700901 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903
John Grossmanee578c02012-07-23 17:05:46 -0700904 // Now set the master volume in each playback thread. Playback threads
905 // assigned to HALs which do not have master volume support will apply
906 // master volume during the mix operation. Threads with HALs which do
907 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700908 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
909 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
910 continue;
911 }
John Grossmanee578c02012-07-23 17:05:46 -0700912 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914
915 return NO_ERROR;
916}
917
Glenn Kastenf78aee72012-01-04 11:00:47 -0800918status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919{
Eric Laurenta1884f92011-08-23 08:25:03 -0700920 status_t ret = initCheck();
921 if (ret != NO_ERROR) {
922 return ret;
923 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924
925 // check calling permissions
926 if (!settingsAllowed()) {
927 return PERMISSION_DENIED;
928 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800929 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000930 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 return BAD_VALUE;
932 }
933
934 { // scope for the lock
935 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700936 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700938 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 mHardwareStatus = AUDIO_HW_IDLE;
940 }
941
942 if (NO_ERROR == ret) {
943 Mutex::Autolock _l(mLock);
944 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800945 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700946 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 }
948
949 return ret;
950}
951
952status_t AudioFlinger::setMicMute(bool state)
953{
Eric Laurenta1884f92011-08-23 08:25:03 -0700954 status_t ret = initCheck();
955 if (ret != NO_ERROR) {
956 return ret;
957 }
958
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959 // check calling permissions
960 if (!settingsAllowed()) {
961 return PERMISSION_DENIED;
962 }
963
964 AutoMutex lock(mHardwareLock);
965 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700966 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700967 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
968 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700969 if (result != NO_ERROR) {
970 ret = result;
971 }
972 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973 mHardwareStatus = AUDIO_HW_IDLE;
974 return ret;
975}
976
977bool AudioFlinger::getMicMute() const
978{
Eric Laurenta1884f92011-08-23 08:25:03 -0700979 status_t ret = initCheck();
980 if (ret != NO_ERROR) {
981 return false;
982 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800983 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700984 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800985 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800987 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700988 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
989 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800990 if (result == NO_ERROR) {
991 mute = mute && state;
992 }
993 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800995
996 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997}
998
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800999void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1000{
1001 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1002
1003 // TODO: Notify MmapThreads
1004
1005 AutoMutex lock(mLock);
1006 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1007 sp<RecordThread> thread = mRecordThreads.valueAt(i);
1008 if (thread != 0) {
1009 thread->setRecordSilenced(uid, silenced);
1010 }
1011 }
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
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001183status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001185 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1186 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001187
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 // check calling permissions
1189 if (!settingsAllowed()) {
1190 return PERMISSION_DENIED;
1191 }
1192
Glenn Kasten142f5192014-03-25 17:44:59 -07001193 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1194 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001195 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001196 // result will remain NO_INIT if no audio device is present
1197 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001198 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001199 AutoMutex lock(mHardwareLock);
1200 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1201 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001202 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1203 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001204 // return success if at least one audio device accepts the parameters as not all
1205 // HALs are requested to support all parameters. If no audio device supports the
1206 // requested parameters, the last error is reported.
1207 if (final_result != NO_ERROR) {
1208 final_result = result;
1209 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001210 }
1211 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001212 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001213 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1214 AudioParameter param = AudioParameter(keyValuePairs);
1215 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001216 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1217 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001218 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001219 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001220 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001221 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001222 }
1223 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001224 String8 screenState;
1225 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001226 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001227 if (isOff != (AudioFlinger::mScreenState & 1)) {
1228 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001229 }
1230 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001231 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 }
1233
1234 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1235 // and the thread is exited once the lock is released
1236 sp<ThreadBase> thread;
1237 {
1238 Mutex::Autolock _l(mLock);
1239 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001240 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001242 if (thread == 0) {
1243 thread = checkMmapThread_l(ioHandle);
1244 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001245 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001246 // indicate output device change to all input threads for pre processing
1247 AudioParameter param = AudioParameter(keyValuePairs);
1248 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001249 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1250 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001251 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001252 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 }
1254 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001255 if (thread != 0) {
1256 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257 }
1258 return BAD_VALUE;
1259}
1260
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001261String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001263 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1264 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265
Eric Laurenta4c5a552012-03-29 10:12:40 -07001266 Mutex::Autolock _l(mLock);
1267
Glenn Kasten142f5192014-03-25 17:44:59 -07001268 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001269 String8 out_s8;
1270
Dima Zavin799a70e2011-04-18 16:57:27 -07001271 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001272 String8 s;
1273 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001274 {
1275 AutoMutex lock(mHardwareLock);
1276 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001277 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1278 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001279 mHardwareStatus = AUDIO_HW_IDLE;
1280 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001281 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001282 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001283 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001284 }
1285
Eric Laurent6acd1d42017-01-04 14:23:29 -08001286 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1287 if (thread == NULL) {
1288 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1289 if (thread == NULL) {
1290 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1291 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001292 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001293 }
1294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001296 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297}
1298
Glenn Kastendd8104c2012-07-02 12:42:44 -07001299size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1300 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301{
Eric Laurenta1884f92011-08-23 08:25:03 -07001302 status_t ret = initCheck();
1303 if (ret != NO_ERROR) {
1304 return 0;
1305 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001306 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001307 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001308 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001309 return 0;
1310 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001311
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001312 AutoMutex lock(mHardwareLock);
1313 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001314 audio_config_t config, proposed;
1315 memset(&proposed, 0, sizeof(proposed));
1316 proposed.sample_rate = sampleRate;
1317 proposed.channel_mask = channelMask;
1318 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001319
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001320 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001321 size_t frames;
1322 for (;;) {
1323 // Note: config is currently a const parameter for get_input_buffer_size()
1324 // but we use a copy from proposed in case config changes from the call.
1325 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001326 status_t result = dev->getInputBufferSize(&config, &frames);
1327 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001328 break; // hal success, config is the result
1329 }
1330 // change one parameter of the configuration each iteration to a more "common" value
1331 // to see if the device will support it.
1332 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1333 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1334 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1335 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1336 } else {
1337 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1338 "format %#x, channelMask 0x%X",
1339 sampleRate, format, channelMask);
1340 break; // retries failed, break out of loop with frames == 0.
1341 }
1342 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001343 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001344 if (frames > 0 && config.sample_rate != sampleRate) {
1345 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1346 }
1347 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348}
1349
Glenn Kasten5f972c02014-01-13 09:59:31 -08001350uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001352 Mutex::Autolock _l(mLock);
1353
1354 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1355 if (recordThread != NULL) {
1356 return recordThread->getInputFramesLost();
1357 }
1358 return 0;
1359}
1360
1361status_t AudioFlinger::setVoiceVolume(float value)
1362{
Eric Laurenta1884f92011-08-23 08:25:03 -07001363 status_t ret = initCheck();
1364 if (ret != NO_ERROR) {
1365 return ret;
1366 }
1367
Mathias Agopian65ab4712010-07-14 17:59:35 -07001368 // check calling permissions
1369 if (!settingsAllowed()) {
1370 return PERMISSION_DENIED;
1371 }
1372
1373 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001374 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001375 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001376 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 mHardwareStatus = AUDIO_HW_IDLE;
1378
1379 return ret;
1380}
1381
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001382status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001383 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385 Mutex::Autolock _l(mLock);
1386
1387 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1388 if (playbackThread != NULL) {
1389 return playbackThread->getRenderPosition(halFrames, dspFrames);
1390 }
1391
1392 return BAD_VALUE;
1393}
1394
1395void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1396{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001398 if (client == 0) {
1399 return;
1400 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001401 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001402 {
1403 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001404 if (mNotificationClients.indexOfKey(pid) < 0) {
1405 sp<NotificationClient> notificationClient = new NotificationClient(this,
1406 client,
1407 pid);
1408 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409
Eric Laurent021cf962014-05-13 10:18:14 -07001410 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411
Marco Nelissen06b46062014-11-14 07:58:25 -08001412 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001413 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001414 }
1415 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416
Eric Laurent021cf962014-05-13 10:18:14 -07001417 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001418 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001419 // the config change is always sent from playback or record threads to avoid deadlock
1420 // with AudioSystem::gLock
1421 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001422 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001425 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001426 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 }
1428}
1429
1430void AudioFlinger::removeNotificationClient(pid_t pid)
1431{
1432 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001433 {
1434 Mutex::Autolock _cl(mClientLock);
1435 mNotificationClients.removeItem(pid);
1436 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001437
Steve Block3856b092011-10-20 11:56:00 +01001438 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001439 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001440 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001441 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001442 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001443 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001444 if (ref->mPid == pid) {
1445 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001446 mAudioSessionRefs.removeAt(i);
1447 delete ref;
1448 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001449 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001450 } else {
1451 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001452 }
1453 }
1454 if (removed) {
1455 purgeStaleEffects_l();
1456 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457}
1458
Eric Laurent73e26b62015-04-27 16:55:58 -07001459void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001460 const sp<AudioIoDescriptor>& ioDesc,
1461 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001462{
Eric Laurent021cf962014-05-13 10:18:14 -07001463 Mutex::Autolock _l(mClientLock);
1464 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001465 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001466 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1467 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1468 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 }
1470}
1471
Eric Laurent021cf962014-05-13 10:18:14 -07001472// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473void AudioFlinger::removeClient_l(pid_t pid)
1474{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001475 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001476 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 mClients.removeItem(pid);
1478}
1479
Eric Laurent717e1282012-06-29 16:36:52 -07001480// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001481sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1482 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001483{
1484 sp<PlaybackThread> thread;
1485
1486 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1487 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1488 ALOG_ASSERT(thread == 0);
1489 thread = mPlaybackThreads.valueAt(i);
1490 }
1491 }
1492
1493 return thread;
1494}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497
1498// ----------------------------------------------------------------------------
1499
1500AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1501 : RefBase(),
1502 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001503 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504{
Andy Hung6f248bb2018-01-23 14:04:37 -08001505 mMemoryDealer = new MemoryDealer(
1506 audioFlinger->getClientSharedHeapSize(),
1507 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508}
1509
Eric Laurent021cf962014-05-13 10:18:14 -07001510// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511AudioFlinger::Client::~Client()
1512{
1513 mAudioFlinger->removeClient_l(mPid);
1514}
1515
Glenn Kasten435dbe62012-01-30 10:15:48 -08001516sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517{
1518 return mMemoryDealer;
1519}
1520
1521// ----------------------------------------------------------------------------
1522
1523AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1524 const sp<IAudioFlingerClient>& client,
1525 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001526 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527{
1528}
1529
1530AudioFlinger::NotificationClient::~NotificationClient()
1531{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532}
1533
Glenn Kasten0f11b512014-01-31 16:18:54 -08001534void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535{
1536 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001537 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538}
1539
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001540// ----------------------------------------------------------------------------
1541AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1542 : mPendingRequests(false) {}
1543
1544
1545void AudioFlinger::MediaLogNotifier::requestMerge() {
1546 AutoMutex _l(mMutex);
1547 mPendingRequests = true;
1548 mCond.signal();
1549}
1550
1551bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001552 // Should already have been checked, but just in case
1553 if (sMediaLogService == 0) {
1554 return false;
1555 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001556 // Wait until there are pending requests
1557 {
1558 AutoMutex _l(mMutex);
1559 mPendingRequests = false; // to ignore past requests
1560 while (!mPendingRequests) {
1561 mCond.wait(mMutex);
1562 // TODO may also need an exitPending check
1563 }
1564 mPendingRequests = false;
1565 }
1566 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001567 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001568 usleep(kPostTriggerSleepPeriod);
1569 return true;
1570}
1571
1572void AudioFlinger::requestLogMerge() {
1573 mMediaLogNotifier->requestMerge();
1574}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575
1576// ----------------------------------------------------------------------------
1577
Eric Laurentf14db3c2017-12-08 14:20:36 -08001578sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1579 CreateRecordOutput& output,
1580 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581{
1582 sp<RecordThread::RecordTrack> recordTrack;
1583 sp<RecordHandle> recordHandle;
1584 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001586 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001587 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588
Eric Laurentf14db3c2017-12-08 14:20:36 -08001589 output.cblk.clear();
1590 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001591 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001592
Eric Laurentf14db3c2017-12-08 14:20:36 -08001593 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001594 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001595 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001596 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001597 ALOGW_IF(clientUid != callingUid,
1598 "%s uid %d tried to pass itself off as %d",
1599 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001600 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001601 updatePid = true;
1602 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001603 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001604 if (updatePid) {
1605 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001606 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001607 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001608 __func__, callingUid, callingPid, clientPid);
1609 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001610 }
1611
Andy Hung6770c6f2015-04-07 13:43:36 -07001612 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001613 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1614 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001615 lStatus = BAD_VALUE;
1616 goto Exit;
1617 }
1618
Glenn Kasten53b5d092014-02-05 10:00:23 -08001619 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001620 if (!audio_is_input_channel(input.config.channel_mask)) {
1621 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001622 lStatus = BAD_VALUE;
1623 goto Exit;
1624 }
1625
Eric Laurentf14db3c2017-12-08 14:20:36 -08001626 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1627 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1628 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1629 lStatus = BAD_VALUE;
1630 goto Exit;
1631 }
1632
1633 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001634 output.selectedDeviceId = input.selectedDeviceId;
1635 output.flags = input.flags;
1636
1637 client = registerPid(clientPid);
1638
1639 // Not a conventional loop, but a retry loop for at most two iterations total.
1640 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1641 // Exits loop via break on no error of got exit on error
1642 // The sp<> references will be dropped when re-entering scope.
1643 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1644 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001645 // release previously opened input if retrying.
1646 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1647 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001648 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001649 output.inputId = AUDIO_IO_HANDLE_NONE;
Eric Laurent77881cd2018-02-09 16:01:31 -08001650 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001651 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001652 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1653 sessionId,
1654 // FIXME compare to AudioTrack
1655 clientPid,
1656 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001657 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001658 &input.config,
1659 output.flags, &output.selectedDeviceId, &portId);
1660
Glenn Kasten05997e22014-03-13 15:08:33 -07001661 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001663 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001665 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 lStatus = BAD_VALUE;
1667 goto Exit;
1668 }
1669
Eric Laurentf14db3c2017-12-08 14:20:36 -08001670 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671
Eric Laurentf14db3c2017-12-08 14:20:36 -08001672 output.sampleRate = input.config.sample_rate;
1673 output.frameCount = input.frameCount;
1674 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001675
Eric Laurentf14db3c2017-12-08 14:20:36 -08001676 recordTrack = thread->createRecordTrack_l(client, &output.sampleRate,
1677 input.config.format, input.config.channel_mask,
1678 &output.frameCount, sessionId,
1679 &output.notificationFrameCount,
1680 clientUid, &output.flags,
1681 input.clientInfo.clientTid,
1682 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001683 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001684
Eric Laurentf14db3c2017-12-08 14:20:36 -08001685 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1686 // audio policy manager without FAST constraint
1687 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001688 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001689 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001690
1691 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001692 goto Exit;
1693 }
1694
1695 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1696 // session and move it to this thread.
1697 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1698 if (chain != 0) {
1699 Mutex::Autolock _l(thread->mLock);
1700 thread->addEffectChain_l(chain);
1701 }
1702 break;
1703 }
1704 // End of retry loop.
1705 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 }
Glenn Kastene198c362013-08-13 09:13:36 -07001707
Eric Laurentf14db3c2017-12-08 14:20:36 -08001708 output.cblk = recordTrack->getCblk();
1709 output.buffers = recordTrack->getBuffers();
1710
1711 // return handle to client
1712 recordHandle = new RecordHandle(recordTrack);
1713
1714Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001715 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001716 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001717 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001718 // Don't hold mClientLock when releasing the reference on the track as the
1719 // destructor will acquire it.
1720 {
1721 Mutex::Autolock _cl(mClientLock);
1722 client.clear();
1723 }
Eric Laurent896c9672017-12-08 14:08:45 -08001724 recordTrack.clear();
1725 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001726 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001727 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 }
1729
Glenn Kasten9156ef32013-08-06 15:39:08 -07001730 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731 return recordHandle;
1732}
1733
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001734
1735
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736// ----------------------------------------------------------------------------
1737
Eric Laurenta4c5a552012-03-29 10:12:40 -07001738audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1739{
Eric Laurent44622db2014-08-01 19:00:33 -07001740 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001741 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001742 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001743 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001744 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001745 }
1746 Mutex::Autolock _l(mLock);
1747 return loadHwModule_l(name);
1748}
1749
1750// loadHwModule_l() must be called with AudioFlinger::mLock held
1751audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1752{
1753 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1754 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1755 ALOGW("loadHwModule() module %s already loaded", name);
1756 return mAudioHwDevs.keyAt(i);
1757 }
1758 }
1759
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001760 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001761
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001762 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001763 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001764 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001765 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001766 }
1767
1768 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001769 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001770 mHardwareStatus = AUDIO_HW_IDLE;
1771 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001772 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001773 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001774 }
1775
John Grossmanee578c02012-07-23 17:05:46 -07001776 // Check and cache this HAL's level of support for master mute and master
1777 // volume. If this is the first HAL opened, and it supports the get
1778 // methods, use the initial values provided by the HAL as the current
1779 // master mute and volume settings.
1780
1781 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1782 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001783 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001784
1785 if (0 == mAudioHwDevs.size()) {
1786 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001787 float mv;
1788 if (OK == dev->getMasterVolume(&mv)) {
1789 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001790 }
1791
1792 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001793 bool mm;
1794 if (OK == dev->getMasterMute(&mm)) {
1795 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001796 }
1797 }
1798
Eric Laurenta4c5a552012-03-29 10:12:40 -07001799 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001800 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001801 flags = static_cast<AudioHwDevice::Flags>(flags |
1802 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1803 }
1804
1805 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001806 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001807 flags = static_cast<AudioHwDevice::Flags>(flags |
1808 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1809 }
1810
Eric Laurenta4c5a552012-03-29 10:12:40 -07001811 mHardwareStatus = AUDIO_HW_IDLE;
1812 }
1813
Glenn Kastena13cde92016-03-28 15:26:02 -07001814 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001815 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001816
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001817 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001818
1819 return handle;
1820
1821}
1822
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001823// ----------------------------------------------------------------------------
1824
Glenn Kasten3b16c762012-11-14 08:44:39 -08001825uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001826{
1827 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001828 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001829 return thread != NULL ? thread->sampleRate() : 0;
1830}
1831
Glenn Kastene33054e2012-11-14 12:54:39 -08001832size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001833{
1834 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001835 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001836 return thread != NULL ? thread->frameCountHAL() : 0;
1837}
1838
1839// ----------------------------------------------------------------------------
1840
Andy Hung6f248bb2018-01-23 14:04:37 -08001841status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001842{
1843 uid_t uid = IPCThreadState::self()->getCallingUid();
1844 if (uid != AID_SYSTEM) {
1845 return PERMISSION_DENIED;
1846 }
1847 Mutex::Autolock _l(mLock);
1848 if (mIsDeviceTypeKnown) {
1849 return INVALID_OPERATION;
1850 }
1851 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001852 mTotalMemory = totalMemory;
1853 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1854 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1855 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1856 // though actual setting is determined through device configuration.
1857 constexpr int64_t GB = 1024 * 1024 * 1024;
1858 mClientSharedHeapSize =
1859 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1860 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1861 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1862 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1863 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001864 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001865
1866 // TODO: Cache the client shared heap size in a persistent property.
1867 // It's possible that a native process or Java service or app accesses audioserver
1868 // after it is registered by system server, but before AudioService updates
1869 // the memory info. This would occur immediately after boot or an audioserver
1870 // crash and restore. Before update from AudioService, the client would get the
1871 // minimum heap size.
1872
1873 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1874 (isLowRamDevice ? "true" : "false"),
1875 (long long)mTotalMemory,
1876 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001877 return NO_ERROR;
1878}
1879
Andy Hung6f248bb2018-01-23 14:04:37 -08001880size_t AudioFlinger::getClientSharedHeapSize() const
1881{
1882 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1883 if (heapSizeInBytes != 0) { // read-only property overrides all.
1884 return heapSizeInBytes;
1885 }
1886 return mClientSharedHeapSize;
1887}
1888
Eric Laurent93c3d412014-08-01 14:48:35 -07001889audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1890{
1891 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001892
1893 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1894 if (index >= 0) {
1895 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1896 mHwAvSyncIds.valueAt(index), sessionId);
1897 return mHwAvSyncIds.valueAt(index);
1898 }
1899
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001900 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001901 if (dev == NULL) {
1902 return AUDIO_HW_SYNC_INVALID;
1903 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001904 String8 reply;
1905 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001906 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001907 param = AudioParameter(reply);
1908 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001909
1910 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001911 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001912 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1913 return AUDIO_HW_SYNC_INVALID;
1914 }
1915
1916 // allow only one session for a given HW A/V sync ID.
1917 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1918 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1919 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1920 value, mHwAvSyncIds.keyAt(i));
1921 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001922 break;
1923 }
1924 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001925
1926 mHwAvSyncIds.add(sessionId, value);
1927
1928 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1929 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1930 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001931 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001932 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001933 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001934 thread->setParameters(param.toString());
1935 break;
1936 }
1937 }
1938
1939 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1940 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001941}
1942
Eric Laurent72e3f392015-05-20 14:43:50 -07001943status_t AudioFlinger::systemReady()
1944{
1945 Mutex::Autolock _l(mLock);
1946 ALOGI("%s", __FUNCTION__);
1947 if (mSystemReady) {
1948 ALOGW("%s called twice", __FUNCTION__);
1949 return NO_ERROR;
1950 }
1951 mSystemReady = true;
1952 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1953 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1954 thread->systemReady();
1955 }
1956 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1957 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1958 thread->systemReady();
1959 }
1960 return NO_ERROR;
1961}
1962
jiabin46a76fa2018-01-05 10:18:21 -08001963status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
1964{
1965 // Fake data
1966 size_t fakeNum = 2;
1967 audio_devices_t fakeTypes[] = { AUDIO_DEVICE_IN_BUILTIN_MIC, AUDIO_DEVICE_IN_BACK_MIC };
1968 for (size_t i = 0; i < fakeNum; i++) {
1969 struct audio_microphone_characteristic_t characteristics;
1970 sprintf(characteristics.device_id, "microphone:%zu", i);
rago1de79cf2018-02-01 15:21:02 -08001971 characteristics.device = fakeTypes[i];
jiabin46a76fa2018-01-05 10:18:21 -08001972 sprintf(characteristics.address, "");
1973 characteristics.location = AUDIO_MICROPHONE_LOCATION_MAINBODY;
1974 characteristics.group = 0;
1975 characteristics.index_in_the_group = i;
1976 characteristics.sensitivity = 1.0f;
1977 characteristics.max_spl = 100.0f;
1978 characteristics.min_spl = 0.0f;
1979 characteristics.directionality = AUDIO_MICROPHONE_DIRECTIONALITY_OMNI;
1980 characteristics.num_frequency_responses = 5 - i;
1981 for (size_t j = 0; j < characteristics.num_frequency_responses; j++) {
1982 characteristics.frequency_responses[0][j] = 100.0f - j;
1983 characteristics.frequency_responses[1][j] = 100.0f + j;
1984 }
1985 for (size_t j = 0; j < AUDIO_CHANNEL_COUNT_MAX; j++) {
1986 characteristics.channel_mapping[j] = AUDIO_MICROPHONE_CHANNEL_MAPPING_UNUSED;
1987 }
1988 characteristics.geometric_location.x = 0.1f;
1989 characteristics.geometric_location.y = 0.2f;
1990 characteristics.geometric_location.z = 0.3f;
1991 characteristics.orientation.x = 0.0f;
1992 characteristics.orientation.y = 1.0f;
1993 characteristics.orientation.z = 0.0f;
1994 media::MicrophoneInfo microphoneInfo = media::MicrophoneInfo(characteristics);
1995 microphones->push_back(microphoneInfo);
1996 }
1997 return NO_ERROR;
1998}
1999
Eric Laurentfa90e842014-10-17 18:12:31 -07002000// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2001void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2002{
2003 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2004 if (index >= 0) {
2005 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2006 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2007 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002008 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002009 thread->setParameters(param.toString());
2010 }
2011}
2012
2013
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002014// ----------------------------------------------------------------------------
2015
Eric Laurent83b88082014-06-20 18:31:16 -07002016
Eric Laurent6acd1d42017-01-04 14:23:29 -08002017sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002018 audio_io_handle_t *output,
2019 audio_config_t *config,
2020 audio_devices_t devices,
2021 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002022 audio_output_flags_t flags)
2023{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002024 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002025 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002026 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002027 }
2028
Eric Laurentcf2c0212014-07-25 16:20:43 -07002029 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002030 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2031 } else {
2032 // Audio Policy does not currently request a specific output handle.
2033 // If this is ever needed, see openInput_l() for example code.
2034 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2035 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002036 }
Eric Laurent83b88082014-06-20 18:31:16 -07002037
2038 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2039
Eric Laurent83b88082014-06-20 18:31:16 -07002040 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002041 // This if statement allows overriding the audio policy settings
2042 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2043 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2044 // Check only for Normal Mixing mode
2045 if (kEnableExtendedPrecision) {
2046 // Specify format (uncomment one below to choose)
2047 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2048 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2049 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2050 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002051 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002052 }
2053 if (kEnableExtendedChannels) {
2054 // Specify channel mask (uncomment one below to choose)
2055 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2056 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2057 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2058 }
Eric Laurent83b88082014-06-20 18:31:16 -07002059 }
2060
Phil Burk062e67a2015-02-11 13:40:50 -08002061 AudioStreamOut *outputStream = NULL;
2062 status_t status = outHwDev->openOutputStream(
2063 &outputStream,
2064 *output,
2065 devices,
2066 flags,
2067 config,
2068 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002069
2070 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002071
Phil Burk062e67a2015-02-11 13:40:50 -08002072 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002073 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2074 sp<MmapPlaybackThread> thread =
2075 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2076 devices, AUDIO_DEVICE_NONE, mSystemReady);
2077 mMmapThreads.add(*output, thread);
2078 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2079 *output, thread.get());
2080 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002081 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002082 sp<PlaybackThread> thread;
2083 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2084 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2085 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2086 *output, thread.get());
2087 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2088 || !isValidPcmSinkFormat(config->format)
2089 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2090 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2091 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2092 *output, thread.get());
2093 } else {
2094 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2095 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2096 *output, thread.get());
2097 }
2098 mPlaybackThreads.add(*output, thread);
2099 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002100 }
Eric Laurent83b88082014-06-20 18:31:16 -07002101 }
2102
2103 return 0;
2104}
2105
Eric Laurentcf2c0212014-07-25 16:20:43 -07002106status_t AudioFlinger::openOutput(audio_module_handle_t module,
2107 audio_io_handle_t *output,
2108 audio_config_t *config,
2109 audio_devices_t *devices,
2110 const String8& address,
2111 uint32_t *latencyMs,
2112 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002114 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2115 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002116 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002117 (devices != NULL) ? *devices : 0,
2118 config->sample_rate,
2119 config->format,
2120 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002121 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002123 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002124 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002126
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 Mutex::Autolock _l(mLock);
2128
Eric Laurent6acd1d42017-01-04 14:23:29 -08002129 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002130 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002131 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2132 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2133 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134
Eric Laurent6acd1d42017-01-04 14:23:29 -08002135 // notify client processes of the new output creation
2136 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002137
Eric Laurent6acd1d42017-01-04 14:23:29 -08002138 // the first primary output opened designates the primary hw device
2139 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002140 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002141 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002142
Eric Laurent6acd1d42017-01-04 14:23:29 -08002143 AutoMutex lock(mHardwareLock);
2144 mHardwareStatus = AUDIO_HW_SET_MODE;
2145 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2146 mHardwareStatus = AUDIO_HW_IDLE;
2147 }
2148 } else {
2149 MmapThread *mmapThread = (MmapThread *)thread.get();
2150 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002151 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002152 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 }
2154
Eric Laurentcf2c0212014-07-25 16:20:43 -07002155 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156}
2157
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002158audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2159 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160{
2161 Mutex::Autolock _l(mLock);
2162 MixerThread *thread1 = checkMixerThread_l(output1);
2163 MixerThread *thread2 = checkMixerThread_l(output2);
2164
2165 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002166 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2167 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002168 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 }
2170
Glenn Kasteneeecb982016-02-26 10:44:04 -08002171 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002172 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 thread->addOutputTrack(thread2);
2174 mPlaybackThreads.add(id, thread);
2175 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002176 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177 return id;
2178}
2179
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002180status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181{
Glenn Kastend96c5722012-04-25 13:44:49 -07002182 return closeOutput_nonvirtual(output);
2183}
2184
2185status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2186{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 // keep strong reference on the playback thread so that
2188 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002189 sp<PlaybackThread> playbackThread;
2190 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 {
2192 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002193 playbackThread = checkPlaybackThread_l(output);
2194 if (playbackThread != NULL) {
2195 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196
Eric Laurent6acd1d42017-01-04 14:23:29 -08002197 if (playbackThread->type() == ThreadBase::MIXER) {
2198 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2199 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2200 DuplicatingThread *dupThread =
2201 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2202 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2203 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 }
2205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206
2207
Eric Laurent6acd1d42017-01-04 14:23:29 -08002208 mPlaybackThreads.removeItem(output);
2209 // save all effects to the default thread
2210 if (mPlaybackThreads.size()) {
2211 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2212 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002213 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002214 Mutex::Autolock _dl(dstThread->mLock);
2215 Mutex::Autolock _sl(playbackThread->mLock);
2216 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2217 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002218 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2219 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221 }
2222 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002223 } else {
2224 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2225 if (mmapThread == 0) {
2226 return BAD_VALUE;
2227 }
2228 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002229 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002231 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2232 ioDesc->mIoHandle = output;
2233 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002235 // The thread entity (active unit of execution) is no longer running here,
2236 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237
Eric Laurent6acd1d42017-01-04 14:23:29 -08002238 if (playbackThread != 0) {
2239 playbackThread->exit();
2240 if (!playbackThread->isDuplicating()) {
2241 closeOutputFinish(playbackThread);
2242 }
2243 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002244 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245 mmapThread->exit();
2246 AudioStreamOut *out = mmapThread->clearOutput();
2247 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2248 // from now on thread->mOutput is NULL
2249 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 }
2251 return NO_ERROR;
2252}
2253
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002254void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002255{
2256 AudioStreamOut *out = thread->clearOutput();
2257 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2258 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002259 delete out;
2260}
2261
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002262void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002263{
2264 mPlaybackThreads.removeItem(thread->mId);
2265 thread->exit();
2266 closeOutputFinish(thread);
2267}
2268
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002269status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270{
2271 Mutex::Autolock _l(mLock);
2272 PlaybackThread *thread = checkPlaybackThread_l(output);
2273
2274 if (thread == NULL) {
2275 return BAD_VALUE;
2276 }
2277
Steve Block3856b092011-10-20 11:56:00 +01002278 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 thread->suspend();
2280
2281 return NO_ERROR;
2282}
2283
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002284status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002285{
2286 Mutex::Autolock _l(mLock);
2287 PlaybackThread *thread = checkPlaybackThread_l(output);
2288
2289 if (thread == NULL) {
2290 return BAD_VALUE;
2291 }
2292
Steve Block3856b092011-10-20 11:56:00 +01002293 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294
2295 thread->restore();
2296
2297 return NO_ERROR;
2298}
2299
Eric Laurentcf2c0212014-07-25 16:20:43 -07002300status_t AudioFlinger::openInput(audio_module_handle_t module,
2301 audio_io_handle_t *input,
2302 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002303 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002304 const String8& address,
2305 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002306 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307{
Eric Laurent83b88082014-06-20 18:31:16 -07002308 Mutex::Autolock _l(mLock);
2309
Glenn Kastene7d66712015-03-05 13:46:52 -08002310 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002311 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002312 }
2313
Eric Laurent6acd1d42017-01-04 14:23:29 -08002314 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002315
2316 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002317 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002318 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002319 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002321 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002322}
Dima Zavin799a70e2011-04-18 16:57:27 -07002323
Eric Laurent6acd1d42017-01-04 14:23:29 -08002324sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002325 audio_io_handle_t *input,
2326 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002327 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002328 const String8& address,
2329 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002330 audio_input_flags_t flags)
2331{
Glenn Kastene7d66712015-03-05 13:46:52 -08002332 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002333 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002334 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002335 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002336 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002337
Glenn Kasteneeecb982016-02-26 10:44:04 -08002338 // Audio Policy can request a specific handle for hardware hotword.
2339 // The goal here is not to re-open an already opened input.
2340 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002341 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002342 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2343 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2344 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2345 return 0;
2346 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2347 // This should not happen in a transient state with current design.
2348 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2349 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002350 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002351
Eric Laurentcf2c0212014-07-25 16:20:43 -07002352 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002353 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002354 sp<StreamInHalInterface> inStream;
2355 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002356 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002357 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2358 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002359 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002360 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002361 halconfig.sample_rate,
2362 halconfig.format,
2363 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002364 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002365 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002366
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002367 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002368 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002369 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002370 audio_is_linear_pcm(config->format) &&
2371 audio_is_linear_pcm(halconfig.format) &&
2372 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002373 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2374 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002375 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002376 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002377 inStream.clear();
2378 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002379 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002380 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381 }
2382
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002383 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002384 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002385 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2386 sp<MmapCaptureThread> thread =
2387 new MmapCaptureThread(this, *input,
2388 inHwDev, inputStream,
2389 primaryOutputDevice_l(), devices, mSystemReady);
2390 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002391 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2392 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002393 return thread;
2394 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002395#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002396 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2397 // or (re-)create if current Pipe is idle and does not match the new format
2398 sp<NBAIO_Sink> teeSink;
2399 enum {
2400 TEE_SINK_NO, // don't copy input
2401 TEE_SINK_NEW, // copy input using a new pipe
2402 TEE_SINK_OLD, // copy input using an existing pipe
2403 } kind;
2404 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2405 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2406 if (!mTeeSinkInputEnabled) {
2407 kind = TEE_SINK_NO;
2408 } else if (!Format_isValid(format)) {
2409 kind = TEE_SINK_NO;
2410 } else if (mRecordTeeSink == 0) {
2411 kind = TEE_SINK_NEW;
2412 } else if (mRecordTeeSink->getStrongCount() != 1) {
2413 kind = TEE_SINK_NO;
2414 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2415 kind = TEE_SINK_OLD;
2416 } else {
2417 kind = TEE_SINK_NEW;
2418 }
2419 switch (kind) {
2420 case TEE_SINK_NEW: {
2421 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2422 size_t numCounterOffers = 0;
2423 const NBAIO_Format offers[1] = {format};
2424 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2425 ALOG_ASSERT(index == 0);
2426 PipeReader *pipeReader = new PipeReader(*pipe);
2427 numCounterOffers = 0;
2428 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2429 ALOG_ASSERT(index == 0);
2430 mRecordTeeSink = pipe;
2431 mRecordTeeSource = pipeReader;
2432 teeSink = pipe;
2433 }
2434 break;
2435 case TEE_SINK_OLD:
2436 teeSink = mRecordTeeSink;
2437 break;
2438 case TEE_SINK_NO:
2439 default:
2440 break;
2441 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002442#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002443
2444 // Start record thread
2445 // RecordThread requires both input and output device indication to forward to audio
2446 // pre processing modules
2447 sp<RecordThread> thread = new RecordThread(this,
2448 inputStream,
2449 *input,
2450 primaryOutputDevice_l(),
2451 devices,
2452 mSystemReady
2453#ifdef TEE_SINK
2454 , teeSink
2455#endif
2456 );
2457 mRecordThreads.add(*input, thread);
2458 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2459 return thread;
2460 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 }
2462
Eric Laurentcf2c0212014-07-25 16:20:43 -07002463 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464 return 0;
2465}
2466
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002467status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468{
Glenn Kastend96c5722012-04-25 13:44:49 -07002469 return closeInput_nonvirtual(input);
2470}
2471
2472status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2473{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474 // keep strong reference on the record thread so that
2475 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002476 sp<RecordThread> recordThread;
2477 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 {
2479 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002480 recordThread = checkRecordThread_l(input);
2481 if (recordThread != 0) {
2482 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483
Eric Laurent6acd1d42017-01-04 14:23:29 -08002484 // If we still have effect chains, it means that a client still holds a handle
2485 // on at least one effect. We must either move the chain to an existing thread with the
2486 // same session ID or put it aside in case a new record thread is opened for a
2487 // new capture on the same session
2488 sp<EffectChain> chain;
2489 {
2490 Mutex::Autolock _sl(recordThread->mLock);
2491 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2492 // Note: maximum one chain per record thread
2493 if (effectChains.size() != 0) {
2494 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002495 }
2496 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002497 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002498 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002499 // This should only happen in case of overlap between one thread tear down and the
2500 // creation of its replacement
2501 size_t i;
2502 for (i = 0; i < mRecordThreads.size(); i++) {
2503 sp<RecordThread> t = mRecordThreads.valueAt(i);
2504 if (t == recordThread) {
2505 continue;
2506 }
2507 if (t->hasAudioSession(chain->sessionId()) != 0) {
2508 Mutex::Autolock _l(t->mLock);
2509 ALOGV("closeInput() found thread %d for effect session %d",
2510 t->id(), chain->sessionId());
2511 t->addEffectChain_l(chain);
2512 break;
2513 }
2514 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002515 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002516 if (i == mRecordThreads.size()) {
2517 putOrphanEffectChain_l(chain);
2518 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002519 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002520 mRecordThreads.removeItem(input);
2521 } else {
2522 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2523 if (mmapThread == 0) {
2524 return BAD_VALUE;
2525 }
2526 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002527 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002528 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2529 ioDesc->mIoHandle = input;
2530 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 }
Eric Laurent83b88082014-06-20 18:31:16 -07002532 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2533 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002534 if (recordThread != 0) {
2535 closeInputFinish(recordThread);
2536 } else if (mmapThread != 0) {
2537 mmapThread->exit();
2538 AudioStreamIn *in = mmapThread->clearInput();
2539 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2540 // from now on thread->mInput is NULL
2541 delete in;
2542 }
Eric Laurent83b88082014-06-20 18:31:16 -07002543 return NO_ERROR;
2544}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002546void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002547{
2548 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002549 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002550 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002551 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002552 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002553}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002555void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002556{
2557 mRecordThreads.removeItem(thread->mId);
2558 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559}
2560
Glenn Kastend2304db2014-02-03 07:40:31 -08002561status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562{
2563 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002564 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565
2566 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2567 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002568 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002569 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002570 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2571 mMmapThreads[i]->invalidateTracks(stream);
2572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 return NO_ERROR;
2574}
2575
2576
Glenn Kasteneeecb982016-02-26 10:44:04 -08002577audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578{
Glenn Kasten9d003132016-04-06 14:38:09 -07002579 // This is a binder API, so a malicious client could pass in a bad parameter.
2580 // Check for that before calling the internal API nextUniqueId().
2581 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2582 ALOGE("newAudioUniqueId invalid use %d", use);
2583 return AUDIO_UNIQUE_ID_ALLOCATE;
2584 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002585 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586}
2587
Glenn Kastend848eb42016-03-08 13:42:11 -08002588void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002589{
2590 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002591 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002592 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2593 if (pid != -1 && (caller == getpid_cached)) {
2594 caller = pid;
2595 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002596
Eric Laurent021cf962014-05-13 10:18:14 -07002597 {
2598 Mutex::Autolock _cl(mClientLock);
2599 // Ignore requests received from processes not known as notification client. The request
2600 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2601 // called from a different pid leaving a stale session reference. Also we don't know how
2602 // to clear this reference if the client process dies.
2603 if (mNotificationClients.indexOfKey(caller) < 0) {
2604 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2605 return;
2606 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002607 }
2608
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002609 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002610 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002611 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002612 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2613 ref->mCnt++;
2614 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002615 return;
2616 }
2617 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002618 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2619 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002620}
2621
Glenn Kastend848eb42016-03-08 13:42:11 -08002622void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002623{
2624 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002625 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002626 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2627 if (pid != -1 && (caller == getpid_cached)) {
2628 caller = pid;
2629 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002630 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002631 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002632 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002633 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2634 ref->mCnt--;
2635 ALOGV(" decremented refcount to %d", ref->mCnt);
2636 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002637 mAudioSessionRefs.removeAt(i);
2638 delete ref;
2639 purgeStaleEffects_l();
2640 }
2641 return;
2642 }
2643 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002644 // If the caller is mediaserver it is likely that the session being released was acquired
2645 // on behalf of a process not in notification clients and we ignore the warning.
2646 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002647}
2648
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002649bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2650{
2651 size_t num = mAudioSessionRefs.size();
2652 for (size_t i = 0; i < num; i++) {
2653 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2654 if (ref->mSessionid == audioSession) {
2655 return true;
2656 }
2657 }
2658 return false;
2659}
2660
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002661void AudioFlinger::purgeStaleEffects_l() {
2662
Steve Block3856b092011-10-20 11:56:00 +01002663 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002664
2665 Vector< sp<EffectChain> > chains;
2666
2667 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2668 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002669 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002670 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2671 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002672 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2673 chains.push(ec);
2674 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002675 }
2676 }
2677 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2678 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002679 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002680 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2681 sp<EffectChain> ec = t->mEffectChains[j];
2682 chains.push(ec);
2683 }
2684 }
2685
2686 for (size_t i = 0; i < chains.size(); i++) {
2687 sp<EffectChain> ec = chains[i];
2688 int sessionid = ec->sessionId();
2689 sp<ThreadBase> t = ec->mThread.promote();
2690 if (t == 0) {
2691 continue;
2692 }
2693 size_t numsessionrefs = mAudioSessionRefs.size();
2694 bool found = false;
2695 for (size_t k = 0; k < numsessionrefs; k++) {
2696 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002697 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002698 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002699 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002700 found = true;
2701 break;
2702 }
2703 }
2704 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002705 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002706 // remove all effects from the chain
2707 while (ec->mEffects.size()) {
2708 sp<EffectModule> effect = ec->mEffects[0];
2709 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002710 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002711 if (effect->purgeHandles()) {
2712 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002713 }
2714 AudioSystem::unregisterEffect(effect->id());
2715 }
2716 }
2717 }
2718 return;
2719}
2720
Glenn Kasteneeecb982016-02-26 10:44:04 -08002721// checkThread_l() must be called with AudioFlinger::mLock held
2722AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2723{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002724 ThreadBase *thread = checkMmapThread_l(ioHandle);
2725 if (thread == 0) {
2726 switch (audio_unique_id_get_use(ioHandle)) {
2727 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2728 thread = checkPlaybackThread_l(ioHandle);
2729 break;
2730 case AUDIO_UNIQUE_ID_USE_INPUT:
2731 thread = checkRecordThread_l(ioHandle);
2732 break;
2733 default:
2734 break;
2735 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002736 }
2737 return thread;
2738}
2739
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002741AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742{
Glenn Kastena1117922012-01-26 10:53:32 -08002743 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744}
2745
2746// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002747AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748{
2749 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002750 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751}
2752
2753// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002754AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755{
Glenn Kastena1117922012-01-26 10:53:32 -08002756 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757}
2758
Eric Laurent6acd1d42017-01-04 14:23:29 -08002759// checkMmapThread_l() must be called with AudioFlinger::mLock held
2760AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2761{
2762 return mMmapThreads.valueFor(io).get();
2763}
2764
2765
2766// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2767AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2768{
Eric Laurent7459b902017-04-19 18:10:41 -07002769 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002770 if (volumeInterface == nullptr) {
2771 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2772 if (mmapThread != nullptr) {
2773 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002774 MmapPlaybackThread *mmapPlaybackThread =
2775 static_cast<MmapPlaybackThread *>(mmapThread);
2776 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002777 }
2778 }
2779 }
2780 return volumeInterface;
2781}
2782
2783Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2784{
2785 Vector <VolumeInterface *> volumeInterfaces;
2786 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002787 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002788 }
2789 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2790 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002791 MmapPlaybackThread *mmapPlaybackThread =
2792 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2793 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002794 }
2795 }
2796 return volumeInterfaces;
2797}
2798
Glenn Kasteneeecb982016-02-26 10:44:04 -08002799audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800{
Glenn Kasten9d003132016-04-06 14:38:09 -07002801 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002802 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002803 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2804 for (int retry = 0; retry < maxRetries; retry++) {
2805 // The cast allows wraparound from max positive to min negative instead of abort
2806 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2807 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2808 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2809 // allow wrap by skipping 0 and -1 for session ids
2810 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2811 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2812 return (audio_unique_id_t) (base | use);
2813 }
2814 }
2815 // We have no way of recovering from wraparound
2816 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2817 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818}
2819
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002820AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002821{
2822 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2823 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002824 if(thread->isDuplicating()) {
2825 continue;
2826 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002827 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002828 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002829 return thread;
2830 }
2831 }
2832 return NULL;
2833}
2834
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002835audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002836{
2837 PlaybackThread *thread = primaryPlaybackThread_l();
2838
2839 if (thread == NULL) {
2840 return 0;
2841 }
2842
Eric Laurentf1c04f92012-08-28 14:26:53 -07002843 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002844}
2845
Glenn Kastena7335632016-06-09 17:09:53 -07002846AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2847{
2848 size_t minFrameCount = 0;
2849 PlaybackThread *minThread = NULL;
2850 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2851 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2852 if (!thread->isDuplicating()) {
2853 size_t frameCount = thread->frameCountHAL();
2854 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2855 (frameCount == minFrameCount && thread->hasFastMixer() &&
2856 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2857 minFrameCount = frameCount;
2858 minThread = thread;
2859 }
2860 }
2861 }
2862 return minThread;
2863}
2864
Eric Laurenta011e352012-03-29 15:51:43 -07002865sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002866 audio_session_t triggerSession,
2867 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002868 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002869 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002870{
2871 Mutex::Autolock _l(mLock);
2872
2873 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2874 status_t playStatus = NAME_NOT_FOUND;
2875 status_t recStatus = NAME_NOT_FOUND;
2876 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2877 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2878 if (playStatus == NO_ERROR) {
2879 return event;
2880 }
2881 }
2882 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2883 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2884 if (recStatus == NO_ERROR) {
2885 return event;
2886 }
2887 }
2888 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2889 mPendingSyncEvents.add(event);
2890 } else {
2891 ALOGV("createSyncEvent() invalid event %d", event->type());
2892 event.clear();
2893 }
2894 return event;
2895}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002896
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897// ----------------------------------------------------------------------------
2898// Effect management
2899// ----------------------------------------------------------------------------
2900
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002901sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2902 return mEffectsFactoryHal;
2903}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002904
Glenn Kastenf587ba52012-01-26 16:25:10 -08002905status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906{
2907 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002908 if (mEffectsFactoryHal.get()) {
2909 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2910 } else {
2911 return -ENODEV;
2912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913}
2914
Glenn Kastenf587ba52012-01-26 16:25:10 -08002915status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916{
2917 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002918 if (mEffectsFactoryHal.get()) {
2919 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2920 } else {
2921 return -ENODEV;
2922 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923}
2924
Glenn Kasten5e92a782012-01-30 07:40:52 -08002925status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002926 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927{
2928 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002929 if (mEffectsFactoryHal.get()) {
2930 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2931 } else {
2932 return -ENODEV;
2933 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934}
2935
2936
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002937sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938 effect_descriptor_t *pDesc,
2939 const sp<IEffectClient>& effectClient,
2940 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002941 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002942 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002943 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002944 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 status_t *status,
2946 int *id,
2947 int *enabled)
2948{
2949 status_t lStatus = NO_ERROR;
2950 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952
Eric Laurentb6436272016-12-07 19:24:50 -08002953 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2954 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2955 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2956 ALOGW_IF(pid != -1 && pid != callingPid,
2957 "%s uid %d pid %d tried to pass itself off as pid %d",
2958 __func__, callingUid, callingPid, pid);
2959 pid = callingPid;
2960 }
2961
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002962 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2963 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964
2965 if (pDesc == NULL) {
2966 lStatus = BAD_VALUE;
2967 goto Exit;
2968 }
2969
Eric Laurent84e9a102010-09-23 16:10:16 -07002970 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002971 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002972 lStatus = PERMISSION_DENIED;
2973 goto Exit;
2974 }
2975
Dima Zavinfce7a472011-04-19 22:30:36 -07002976 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002977 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002978 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002979 lStatus = PERMISSION_DENIED;
2980 goto Exit;
2981 }
2982
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002983 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002984 lStatus = NO_INIT;
2985 goto Exit;
2986 }
2987
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002989 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002991 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002993 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 goto Exit;
2995 }
2996 } else {
2997 // if uuid is not specified, look for an available implementation
2998 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002999 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003000 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 lStatus = BAD_VALUE;
3002 goto Exit;
3003 }
3004 uint32_t numEffects = 0;
3005 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003006 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 bool found = false;
3008
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003009 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003011 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 goto Exit;
3013 }
3014 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003015 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003017 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018 continue;
3019 }
3020 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3021 // If matching type found save effect descriptor. If the session is
3022 // 0 and the effect is not auxiliary, continue enumeration in case
3023 // an auxiliary version of this effect type is available
3024 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003025 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003026 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3028 break;
3029 }
3030 }
3031 }
3032 if (!found) {
3033 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003034 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 goto Exit;
3036 }
3037 // For same effect type, chose auxiliary version over insert version if
3038 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003039 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003041 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 }
3043 }
3044
3045 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003046 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3048 lStatus = INVALID_OPERATION;
3049 goto Exit;
3050 }
3051
Eric Laurent59255e42011-07-27 19:49:51 -07003052 // check recording permission for visualizer
3053 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov5b81f552018-03-02 09:21:30 -08003054 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003055 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003056 lStatus = PERMISSION_DENIED;
3057 goto Exit;
3058 }
3059
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003061 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003062 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003063 // if the output returned by getOutputForEffect() is removed before we lock the
3064 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3065 // and we will exit safely
3066 io = AudioSystem::getOutputForEffect(&desc);
3067 ALOGV("createEffect got output %d", io);
3068 }
3069
3070 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003071
3072 // If output is not specified try to find a matching audio session ID in one of the
3073 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003074 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3075 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003076 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003077 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003078 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3079 // output must be specified by AudioPolicyManager when using session
3080 // AUDIO_SESSION_OUTPUT_STAGE
3081 lStatus = BAD_VALUE;
3082 goto Exit;
3083 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003084 // look for the thread where the specified audio session is present
3085 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3086 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3087 io = mPlaybackThreads.keyAt(i);
3088 break;
3089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003091 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003092 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3093 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3094 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003095 break;
3096 }
3097 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003098 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003099 if (io == AUDIO_IO_HANDLE_NONE) {
3100 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3101 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3102 io = mMmapThreads.keyAt(i);
3103 break;
3104 }
3105 }
3106 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003107 // If no output thread contains the requested session ID, default to
3108 // first output. The effect chain will be moved to the correct output
3109 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003110 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003111 io = mPlaybackThreads.keyAt(0);
3112 }
Steve Block3856b092011-10-20 11:56:00 +01003113 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003114 }
3115 ThreadBase *thread = checkRecordThread_l(io);
3116 if (thread == NULL) {
3117 thread = checkPlaybackThread_l(io);
3118 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003119 thread = checkMmapThread_l(io);
3120 if (thread == NULL) {
3121 ALOGE("createEffect() unknown output thread");
3122 lStatus = BAD_VALUE;
3123 goto Exit;
3124 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003125 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003126 } else {
3127 // Check if one effect chain was awaiting for an effect to be created on this
3128 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003129 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003130 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003131 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003132 thread->addEffectChain_l(chain);
3133 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003135
Eric Laurent021cf962014-05-13 10:18:14 -07003136 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003138 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003139 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003140 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003141 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 if (handle != 0 && id != NULL) {
3143 *id = handle->id();
3144 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003145 if (handle == 0) {
3146 // remove local strong reference to Client with mClientLock held
3147 Mutex::Autolock _cl(mClientLock);
3148 client.clear();
3149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 }
3151
3152Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003153 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 return handle;
3155}
3156
Glenn Kastend848eb42016-03-08 13:42:11 -08003157status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003158 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003159{
Steve Block3856b092011-10-20 11:56:00 +01003160 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003161 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003162 Mutex::Autolock _l(mLock);
3163 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003164 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003165 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 }
Eric Laurentde070132010-07-13 04:45:46 -07003167 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3168 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003169 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003170 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 }
Eric Laurentde070132010-07-13 04:45:46 -07003172 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3173 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003174 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003175 return BAD_VALUE;
3176 }
3177
3178 Mutex::Autolock _dl(dstThread->mLock);
3179 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003180 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181}
3182
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003183// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003184status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003185 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003186 AudioFlinger::PlaybackThread *dstThread,
3187 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003188{
Steve Block3856b092011-10-20 11:56:00 +01003189 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003190 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003191
Eric Laurent59255e42011-07-27 19:49:51 -07003192 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003193 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003194 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003195 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003196 return INVALID_OPERATION;
3197 }
3198
Eric Laurent4c415062016-06-17 16:14:16 -07003199 // Check whether the destination thread and all effects in the chain are compatible
3200 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003201 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003202 " destination thread %p is not compatible with effects in the chain",
3203 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003204 return INVALID_OPERATION;
3205 }
3206
Eric Laurent39e94f82010-07-28 01:32:47 -07003207 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003208 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003209 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003210 // removed.
3211 srcThread->removeEffectChain_l(chain);
3212
3213 // transfer all effects one by one so that new effect chain is created on new thread with
3214 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003215 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003216 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003217 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003218 Vector< sp<EffectModule> > removed;
3219 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003220 while (effect != 0) {
3221 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003222 removed.add(effect);
3223 status = dstThread->addEffect_l(effect);
3224 if (status != NO_ERROR) {
3225 break;
3226 }
Eric Laurentec35a142011-10-05 17:42:25 -07003227 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3228 if (effect->state() == EffectModule::ACTIVE ||
3229 effect->state() == EffectModule::STOPPING) {
3230 effect->start();
3231 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003232 // if the move request is not received from audio policy manager, the effect must be
3233 // re-registered with the new strategy and output
3234 if (dstChain == 0) {
3235 dstChain = effect->chain().promote();
3236 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003237 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003238 status = NO_INIT;
3239 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003240 }
3241 strategy = dstChain->strategy();
3242 }
3243 if (reRegister) {
3244 AudioSystem::unregisterEffect(effect->id());
3245 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003246 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003247 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003248 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003249 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003250 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003251 }
Eric Laurentde070132010-07-13 04:45:46 -07003252 effect = chain->getEffectFromId_l(0);
3253 }
3254
Eric Laurent5baf2af2013-09-12 17:37:00 -07003255 if (status != NO_ERROR) {
3256 for (size_t i = 0; i < removed.size(); i++) {
3257 srcThread->addEffect_l(removed[i]);
3258 if (dstChain != 0 && reRegister) {
3259 AudioSystem::unregisterEffect(removed[i]->id());
3260 AudioSystem::registerEffect(&removed[i]->desc(),
3261 srcThread->id(),
3262 strategy,
3263 sessionId,
3264 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003265 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003266 }
3267 }
3268 }
3269
3270 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271}
3272
Eric Laurent5baf2af2013-09-12 17:37:00 -07003273bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003274{
3275 if (mGlobalEffectEnableTime != 0 &&
3276 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3277 return true;
3278 }
3279
3280 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3281 sp<EffectChain> ec =
3282 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003283 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003284 return true;
3285 }
3286 }
3287 return false;
3288}
3289
Eric Laurent5baf2af2013-09-12 17:37:00 -07003290void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003291{
3292 Mutex::Autolock _l(mLock);
3293
3294 mGlobalEffectEnableTime = systemTime();
3295
3296 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3297 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3298 if (t->mType == ThreadBase::OFFLOAD) {
3299 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3300 }
3301 }
3302
3303}
3304
Eric Laurentaaa44472014-09-12 17:41:50 -07003305status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3306{
Eric Laurentd8365c52017-07-16 15:27:05 -07003307 // clear possible suspended state before parking the chain so that it starts in default state
3308 // when attached to a new record thread
3309 chain->setEffectSuspended_l(FX_IID_AEC, false);
3310 chain->setEffectSuspended_l(FX_IID_NS, false);
3311
Glenn Kastend848eb42016-03-08 13:42:11 -08003312 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003313 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003314 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003315 if (index >= 0) {
3316 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3317 return ALREADY_EXISTS;
3318 }
3319 mOrphanEffectChains.add(session, chain);
3320 return NO_ERROR;
3321}
3322
3323sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3324{
3325 sp<EffectChain> chain;
3326 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003327 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003328 if (index >= 0) {
3329 chain = mOrphanEffectChains.valueAt(index);
3330 mOrphanEffectChains.removeItemsAt(index);
3331 }
3332 return chain;
3333}
3334
3335bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3336{
3337 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003338 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003339 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003340 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003341 if (index >= 0) {
3342 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003343 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003344 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003345 mOrphanEffectChains.removeItemsAt(index);
3346 }
3347 return true;
3348 }
3349 return false;
3350}
3351
3352
Glenn Kastenda6ef132013-01-10 12:31:01 -08003353struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003354#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3355 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003356};
3357
3358int comparEntry(const void *p1, const void *p2)
3359{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003360 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003361}
3362
Glenn Kasten46909e72013-02-26 09:20:22 -08003363#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003364void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365{
Eric Laurent81784c32012-11-19 14:55:58 -08003366 NBAIO_Source *teeSource = source.get();
3367 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003368 // .wav rotation
3369 // There is a benign race condition if 2 threads call this simultaneously.
3370 // They would both traverse the directory, but the result would simply be
3371 // failures at unlink() which are ignored. It's also unlikely since
3372 // normally dumpsys is only done by bugreport or from the command line.
3373 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003374 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003375 size_t teePathLen = strlen(teePath);
3376 DIR *dir = opendir(teePath);
3377 teePath[teePathLen++] = '/';
3378 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003379#define TEE_MAX_SORT 20 // number of entries to sort
3380#define TEE_MAX_KEEP 10 // number of entries to keep
3381 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003382 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003383 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003384 struct dirent de;
3385 struct dirent *result = NULL;
3386 int rc = readdir_r(dir, &de, &result);
3387 if (rc != 0) {
3388 ALOGW("readdir_r failed %d", rc);
3389 break;
3390 }
3391 if (result == NULL) {
3392 break;
3393 }
3394 if (result != &de) {
3395 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3396 break;
3397 }
3398 // ignore non .wav file entries
3399 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003400 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003401 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3402 continue;
3403 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003404 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003405 }
3406 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003407 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003408 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003409 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3410 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003411 (void) unlink(teePath);
3412 }
3413 }
3414 } else {
3415 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003416 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003417 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003418 }
3419 }
Eric Laurent81784c32012-11-19 14:55:58 -08003420 char teeTime[16];
3421 struct timeval tv;
3422 gettimeofday(&tv, NULL);
3423 struct tm tm;
3424 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003425 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003426 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3427 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003428 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3429 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003430 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003431 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003432 char wavHeader[44];
3433 memcpy(wavHeader,
3434 "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",
3435 sizeof(wavHeader));
3436 NBAIO_Format format = teeSource->format();
3437 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003438 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003439 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003440 wavHeader[22] = channelCount; // number of channels
3441 wavHeader[24] = sampleRate; // sample rate
3442 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003443 wavHeader[32] = frameSize; // block alignment
3444 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003445 write(teeFd, wavHeader, sizeof(wavHeader));
3446 size_t total = 0;
3447 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003448#define TEE_SINK_READ 1024 // frames per I/O operation
3449 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003450 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003451 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003452 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003453 bool wasFirstRead = firstRead;
3454 firstRead = false;
3455 if (actual <= 0) {
3456 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3457 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003458 }
Eric Laurent81784c32012-11-19 14:55:58 -08003459 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003460 }
Eric Laurent81784c32012-11-19 14:55:58 -08003461 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003462 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003463 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003464 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003465 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003466 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003467 uint32_t temp = 44 + total * frameSize - 8;
3468 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003469 write(teeFd, &temp, sizeof(temp));
3470 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003471 temp = total * frameSize;
3472 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003473 write(teeFd, &temp, sizeof(temp));
3474 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003475 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003476 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003477 }
Eric Laurent59255e42011-07-27 19:49:51 -07003478 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003479 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003480 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003481 }
Eric Laurent59255e42011-07-27 19:49:51 -07003482 }
3483 }
3484}
Glenn Kasten46909e72013-02-26 09:20:22 -08003485#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003486
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487// ----------------------------------------------------------------------------
3488
3489status_t AudioFlinger::onTransact(
3490 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3491{
3492 return BnAudioFlinger::onTransact(code, data, reply, flags);
3493}
3494
Glenn Kasten63238ef2015-03-02 15:50:29 -08003495} // namespace android