blob: e7140c2771862757998a59d862b4d837d2f3e5f9 [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>
Eric Laurent38ccae22011-03-28 18:37:07 -070042#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
44#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,
324 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700325 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800326 }
327 if (ret != NO_ERROR) {
328 return ret;
329 }
330
331 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
332 // audio policy manager and we can retrieve it
333 sp<MmapThread> thread = mMmapThreads.valueFor(io);
334 if (thread != 0) {
335 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800336 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700337 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800338 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800339 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700340 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800341 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700342 } else {
Eric Laurente9ebcdb2018-01-29 14:27:18 -0800343 AudioSystem::releaseInput(io, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700344 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800345 ret = NO_INIT;
346 }
347
348 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
349
Eric Laurentfc235202016-12-20 18:48:17 -0800350 return ret;
351}
352
Eric Laurenta4c5a552012-03-29 10:12:40 -0700353static const char * const audio_interfaces[] = {
354 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
355 AUDIO_HARDWARE_MODULE_ID_A2DP,
356 AUDIO_HARDWARE_MODULE_ID_USB,
357};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700358
Phil Burk062e67a2015-02-11 13:40:50 -0800359AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700360 audio_module_handle_t module,
361 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700362{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700363 // if module is 0, the request comes from an old policy manager and we should load
364 // well known modules
365 if (module == 0) {
366 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700367 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700368 loadHwModule_l(audio_interfaces[i]);
369 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700370 // then try to find a module supporting the requested device.
371 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
372 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700373 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
374 uint32_t supportedDevices;
375 if (dev->getSupportedDevices(&supportedDevices) == OK &&
376 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700377 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700378 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700379 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700380 } else {
381 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700382 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
383 if (audioHwDevice != NULL) {
384 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700385 }
386 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700387
Dima Zavin799a70e2011-04-18 16:57:27 -0700388 return NULL;
389}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390
Glenn Kasten0f11b512014-01-31 16:18:54 -0800391void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392{
393 const size_t SIZE = 256;
394 char buffer[SIZE];
395 String8 result;
396
397 result.append("Clients:\n");
398 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800399 sp<Client> client = mClients.valueAt(i).promote();
400 if (client != 0) {
401 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
402 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 }
404 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700405
Eric Laurentd1b28d42013-09-18 18:47:13 -0700406 result.append("Notification Clients:\n");
407 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
408 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
409 result.append(buffer);
410 }
411
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700412 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800413 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700414 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
415 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800416 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700417 result.append(buffer);
418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420}
421
422
Glenn Kasten0f11b512014-01-31 16:18:54 -0800423void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800428 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429
John Grossman4ff14ba2012-02-08 16:37:41 -0800430 snprintf(buffer, SIZE, "Hardware status: %d\n"
431 "Standby Time mSec: %u\n",
432 hardwareStatus,
433 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 result.append(buffer);
435 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436}
437
Glenn Kasten0f11b512014-01-31 16:18:54 -0800438void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439{
440 const size_t SIZE = 256;
441 char buffer[SIZE];
442 String8 result;
443 snprintf(buffer, SIZE, "Permission Denial: "
444 "can't dump AudioFlinger from pid=%d, uid=%d\n",
445 IPCThreadState::self()->getCallingPid(),
446 IPCThreadState::self()->getCallingUid());
447 result.append(buffer);
448 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449}
450
Eric Laurent81784c32012-11-19 14:55:58 -0800451bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452{
453 bool locked = false;
454 for (int i = 0; i < kDumpLockRetries; ++i) {
455 if (mutex.tryLock() == NO_ERROR) {
456 locked = true;
457 break;
458 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800459 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 }
461 return locked;
462}
463
464status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
465{
Glenn Kasten44deb052012-02-05 18:09:08 -0800466 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 dumpPermissionDenial(fd, args);
468 } else {
469 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800470 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 if (!hardwareLocked) {
472 String8 result(kHardwareLockedString);
473 write(fd, result.string(), result.size());
474 } else {
475 mHardwareLock.unlock();
476 }
477
Eric Laurent81784c32012-11-19 14:55:58 -0800478 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479
480 // failed to lock - AudioFlinger is probably deadlocked
481 if (!locked) {
482 String8 result(kDeadlockedString);
483 write(fd, result.string(), result.size());
484 }
485
Eric Laurent021cf962014-05-13 10:18:14 -0700486 bool clientLocked = dumpTryLock(mClientLock);
487 if (!clientLocked) {
488 String8 result(kClientLockedString);
489 write(fd, result.string(), result.size());
490 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700491
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700492 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700493 mEffectsFactoryHal->dumpEffects(fd);
494 } else {
495 String8 result(kNoEffectsFactory);
496 write(fd, result.string(), result.size());
497 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700498
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700500 if (clientLocked) {
501 mClientLock.unlock();
502 }
503
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504 dumpInternals(fd, args);
505
506 // dump playback threads
507 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
508 mPlaybackThreads.valueAt(i)->dump(fd, args);
509 }
510
511 // dump record threads
512 for (size_t i = 0; i < mRecordThreads.size(); i++) {
513 mRecordThreads.valueAt(i)->dump(fd, args);
514 }
515
Eric Laurent6acd1d42017-01-04 14:23:29 -0800516 // dump mmap threads
517 for (size_t i = 0; i < mMmapThreads.size(); i++) {
518 mMmapThreads.valueAt(i)->dump(fd, args);
519 }
520
Eric Laurentaaa44472014-09-12 17:41:50 -0700521 // dump orphan effect chains
522 if (mOrphanEffectChains.size() != 0) {
523 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
524 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
525 mOrphanEffectChains.valueAt(i)->dump(fd, args);
526 }
527 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700528 // dump all hardware devs
529 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700530 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
531 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700533
Glenn Kasten46909e72013-02-26 09:20:22 -0800534#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700535 // dump the serially shared record tee sink
536 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700537 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700538 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800539#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700540
rago3bd1c872016-09-26 12:58:14 -0700541 BUFLOG_RESET;
542
Glenn Kastend65d73c2012-06-22 17:21:07 -0700543 if (locked) {
544 mLock.unlock();
545 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800546
547 // append a copy of media.log here by forwarding fd to it, but don't attempt
548 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700549 if (sMediaLogServiceAsBinder != 0) {
550 dprintf(fd, "\nmedia.log:\n");
551 Vector<String16> args;
552 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800553 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700554
555 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700556 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700557 bool unreachableMemory = false;
558 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700559 if (arg == String16("-m")) {
560 dumpMem = true;
561 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700562 unreachableMemory = true;
563 }
564 }
565
Andy Hung07b745e2016-05-23 16:21:07 -0700566 if (dumpMem) {
567 dprintf(fd, "\nDumping memory:\n");
568 std::string s = dumpMemoryAddresses(100 /* limit */);
569 write(fd, s.c_str(), s.size());
570 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700571 if (unreachableMemory) {
572 dprintf(fd, "\nDumping unreachable memory:\n");
573 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700574 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700575 write(fd, s.c_str(), s.size());
576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 }
578 return NO_ERROR;
579}
580
Eric Laurent021cf962014-05-13 10:18:14 -0700581sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800582{
Eric Laurent021cf962014-05-13 10:18:14 -0700583 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800584 // If pid is already in the mClients wp<> map, then use that entry
585 // (for which promote() is always != 0), otherwise create a new entry and Client.
586 sp<Client> client = mClients.valueFor(pid).promote();
587 if (client == 0) {
588 client = new Client(this, pid);
589 mClients.add(pid, client);
590 }
591
592 return client;
593}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594
Glenn Kasten9e58b552013-01-18 15:09:48 -0800595sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
596{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700597 // If there is no memory allocated for logs, return a dummy writer that does nothing.
598 // Similarly if we can't contact the media.log service, also return a dummy writer.
599 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800600 return new NBLog::Writer();
601 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700602 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
603 // If allocation fails, consult the vector of previously unregistered writers
604 // and garbage-collect one or more them until an allocation succeeds
605 if (shared == 0) {
606 Mutex::Autolock _l(mUnregisteredWritersLock);
607 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
608 {
609 // Pick the oldest stale writer to garbage-collect
610 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
611 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700612 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700613 // Now the media.log remote reference to IMemory is gone. When our last local
614 // reference to IMemory also drops to zero at end of this block,
615 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
616 }
617 // Re-attempt the allocation
618 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
619 if (shared != 0) {
620 goto success;
621 }
622 }
623 // Even after garbage-collecting all old writers, there is still not enough memory,
624 // so return a dummy writer
625 return new NBLog::Writer();
626 }
627success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800628 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
629 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
630 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700631 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800632 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800633}
634
635void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
636{
Glenn Kasten685ef092013-02-04 08:15:34 -0800637 if (writer == 0) {
638 return;
639 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800640 sp<IMemory> iMemory(writer->getIMemory());
641 if (iMemory == 0) {
642 return;
643 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700644 // Rather than removing the writer immediately, append it to a queue of old writers to
645 // be garbage-collected later. This allows us to continue to view old logs for a while.
646 Mutex::Autolock _l(mUnregisteredWritersLock);
647 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800648}
649
Mathias Agopian65ab4712010-07-14 17:59:35 -0700650// IAudioFlinger interface
651
Eric Laurent21da6472017-11-09 16:29:26 -0800652sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
653 CreateTrackOutput& output,
654 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655{
656 sp<PlaybackThread::Track> track;
657 sp<TrackHandle> trackHandle;
658 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800660 audio_stream_type_t streamType;
661 audio_port_handle_t portId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662
Eric Laurent21da6472017-11-09 16:29:26 -0800663 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700664 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800665 uid_t clientUid = input.clientInfo.clientUid;
666 if (!isTrustedCallingUid(callingUid)) {
667 ALOGW_IF(clientUid != callingUid,
668 "%s uid %d tried to pass itself off as %d",
669 __FUNCTION__, callingUid, clientUid);
670 clientUid = callingUid;
671 updatePid = true;
672 }
673 pid_t clientPid = input.clientInfo.clientPid;
674 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700675 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800676 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700677 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800678 __func__, callingUid, callingPid, clientPid);
679 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700680 }
681
Eric Laurent21da6472017-11-09 16:29:26 -0800682 audio_session_t sessionId = input.sessionId;
683 if (sessionId == AUDIO_SESSION_ALLOCATE) {
684 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800685 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
686 lStatus = BAD_VALUE;
687 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800688 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800689
Eric Laurent21da6472017-11-09 16:29:26 -0800690 output.sessionId = sessionId;
691 output.outputId = AUDIO_IO_HANDLE_NONE;
692 output.selectedDeviceId = input.selectedDeviceId;
693
694 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200695 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800696 &output.selectedDeviceId, &portId);
697
698 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
699 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
700 goto Exit;
701 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800702 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
703 // but if someone uses binder directly they could bypass that and cause us to crash
704 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000705 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 lStatus = BAD_VALUE;
707 goto Exit;
708 }
709
Glenn Kasten53b5d092014-02-05 10:00:23 -0800710 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800711 if (!audio_is_output_channel(input.config.channel_mask)) {
712 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800713 lStatus = BAD_VALUE;
714 goto Exit;
715 }
716
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700717 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800718 if (!audio_is_valid_format(input.config.format)) {
719 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700720 lStatus = BAD_VALUE;
721 goto Exit;
722 }
723
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 {
725 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800726 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800728 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 lStatus = BAD_VALUE;
730 goto Exit;
731 }
732
Eric Laurent21da6472017-11-09 16:29:26 -0800733 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734
Glenn Kastene848bd92014-03-13 15:00:32 -0700735 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800736 // check if an effect chain with the same session ID is present on another
737 // output thread and move it here.
738 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
739 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
740 if (mPlaybackThreads.keyAt(i) != output.outputId) {
741 uint32_t sessions = t->hasAudioSession(sessionId);
742 if (sessions & ThreadBase::EFFECT_SESSION) {
743 effectThread = t.get();
744 break;
Eric Laurentde070132010-07-13 04:45:46 -0700745 }
746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 }
Eric Laurent21da6472017-11-09 16:29:26 -0800748 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749
Eric Laurent21da6472017-11-09 16:29:26 -0800750 output.sampleRate = input.config.sample_rate;
751 output.frameCount = input.frameCount;
752 output.notificationFrameCount = input.notificationFrameCount;
753 output.flags = input.flags;
754
755 track = thread->createTrack_l(client, streamType, &output.sampleRate, input.config.format,
756 input.config.channel_mask,
757 &output.frameCount, &output.notificationFrameCount,
758 input.notificationsPerBuffer, input.speed,
759 input.sharedBuffer, sessionId, &output.flags,
760 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800761 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700762 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700763
Eric Laurent21da6472017-11-09 16:29:26 -0800764 output.afFrameCount = thread->frameCount();
765 output.afSampleRate = thread->sampleRate();
766 output.afLatencyMs = thread->latency();
767
Eric Laurent39e94f82010-07-28 01:32:47 -0700768 // move effect chain to this output thread if an effect on same session was waiting
769 // for a track to be created
770 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700771 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700772 Mutex::Autolock _dl(thread->mLock);
773 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800774 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700775 }
Eric Laurenta011e352012-03-29 15:51:43 -0700776
777 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700778 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800779 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700780 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700781 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700782 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700783 } else {
784 mPendingSyncEvents[i]->cancel();
785 }
Eric Laurenta011e352012-03-29 15:51:43 -0700786 mPendingSyncEvents.removeAt(i);
787 i--;
788 }
789 }
790 }
Glenn Kastene198c362013-08-13 09:13:36 -0700791
Eric Laurent21da6472017-11-09 16:29:26 -0800792 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 }
Glenn Kastene198c362013-08-13 09:13:36 -0700794
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700795 if (lStatus != NO_ERROR) {
796 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700797 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700798 // Don't hold mClientLock when releasing the reference on the track as the
799 // destructor will acquire it.
800 {
801 Mutex::Autolock _cl(mClientLock);
802 client.clear();
803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700805 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 }
807
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700808 // return handle to client
809 trackHandle = new TrackHandle(track);
810
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800812 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
813 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
814 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700815 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 return trackHandle;
817}
818
Glenn Kasten2c073da2016-02-26 09:14:08 -0800819uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820{
821 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800822 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800824 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 return 0;
826 }
827 return thread->sampleRate();
828}
829
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800830audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
832 Mutex::Autolock _l(mLock);
833 PlaybackThread *thread = checkPlaybackThread_l(output);
834 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000835 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800836 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 }
838 return thread->format();
839}
840
Glenn Kasten2c073da2016-02-26 09:14:08 -0800841size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842{
843 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800844 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800846 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 return 0;
848 }
Glenn Kasten58912562012-04-03 10:45:00 -0700849 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
850 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 return thread->frameCount();
852}
853
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700854size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
855{
856 Mutex::Autolock _l(mLock);
857 ThreadBase *thread = checkThread_l(ioHandle);
858 if (thread == NULL) {
859 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
860 return 0;
861 }
862 return thread->frameCountHAL();
863}
864
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800865uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866{
867 Mutex::Autolock _l(mLock);
868 PlaybackThread *thread = checkPlaybackThread_l(output);
869 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800870 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 return 0;
872 }
873 return thread->latency();
874}
875
876status_t AudioFlinger::setMasterVolume(float value)
877{
Eric Laurenta1884f92011-08-23 08:25:03 -0700878 status_t ret = initCheck();
879 if (ret != NO_ERROR) {
880 return ret;
881 }
882
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 // check calling permissions
884 if (!settingsAllowed()) {
885 return PERMISSION_DENIED;
886 }
887
Eric Laurenta4c5a552012-03-29 10:12:40 -0700888 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700889 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700890
John Grossmanee578c02012-07-23 17:05:46 -0700891 // Set master volume in the HALs which support it.
892 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
893 AutoMutex lock(mHardwareLock);
894 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800895
John Grossmanee578c02012-07-23 17:05:46 -0700896 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
897 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700898 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800899 }
John Grossmanee578c02012-07-23 17:05:46 -0700900 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902
John Grossmanee578c02012-07-23 17:05:46 -0700903 // Now set the master volume in each playback thread. Playback threads
904 // assigned to HALs which do not have master volume support will apply
905 // master volume during the mix operation. Threads with HALs which do
906 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700907 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
908 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
909 continue;
910 }
John Grossmanee578c02012-07-23 17:05:46 -0700911 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913
914 return NO_ERROR;
915}
916
Glenn Kastenf78aee72012-01-04 11:00:47 -0800917status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918{
Eric Laurenta1884f92011-08-23 08:25:03 -0700919 status_t ret = initCheck();
920 if (ret != NO_ERROR) {
921 return ret;
922 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923
924 // check calling permissions
925 if (!settingsAllowed()) {
926 return PERMISSION_DENIED;
927 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800928 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000929 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 return BAD_VALUE;
931 }
932
933 { // scope for the lock
934 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700935 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700937 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 mHardwareStatus = AUDIO_HW_IDLE;
939 }
940
941 if (NO_ERROR == ret) {
942 Mutex::Autolock _l(mLock);
943 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800944 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700945 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 }
947
948 return ret;
949}
950
951status_t AudioFlinger::setMicMute(bool state)
952{
Eric Laurenta1884f92011-08-23 08:25:03 -0700953 status_t ret = initCheck();
954 if (ret != NO_ERROR) {
955 return ret;
956 }
957
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958 // check calling permissions
959 if (!settingsAllowed()) {
960 return PERMISSION_DENIED;
961 }
962
963 AutoMutex lock(mHardwareLock);
964 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700965 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700966 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
967 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700968 if (result != NO_ERROR) {
969 ret = result;
970 }
971 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 mHardwareStatus = AUDIO_HW_IDLE;
973 return ret;
974}
975
976bool AudioFlinger::getMicMute() const
977{
Eric Laurenta1884f92011-08-23 08:25:03 -0700978 status_t ret = initCheck();
979 if (ret != NO_ERROR) {
980 return false;
981 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800982 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700983 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800984 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800986 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700987 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
988 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800989 if (result == NO_ERROR) {
990 mute = mute && state;
991 }
992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800994
995 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996}
997
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800998void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
999{
1000 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1001
1002 // TODO: Notify MmapThreads
1003
1004 AutoMutex lock(mLock);
1005 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1006 sp<RecordThread> thread = mRecordThreads.valueAt(i);
1007 if (thread != 0) {
1008 thread->setRecordSilenced(uid, silenced);
1009 }
1010 }
1011}
1012
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013status_t AudioFlinger::setMasterMute(bool muted)
1014{
John Grossmand8f178d2012-07-20 14:51:35 -07001015 status_t ret = initCheck();
1016 if (ret != NO_ERROR) {
1017 return ret;
1018 }
1019
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020 // check calling permissions
1021 if (!settingsAllowed()) {
1022 return PERMISSION_DENIED;
1023 }
1024
John Grossmanee578c02012-07-23 17:05:46 -07001025 Mutex::Autolock _l(mLock);
1026 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001027
John Grossmanee578c02012-07-23 17:05:46 -07001028 // Set master mute in the HALs which support it.
1029 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1030 AutoMutex lock(mHardwareLock);
1031 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001032
John Grossmanee578c02012-07-23 17:05:46 -07001033 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1034 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001035 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001036 }
John Grossmanee578c02012-07-23 17:05:46 -07001037 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001038 }
1039
John Grossmanee578c02012-07-23 17:05:46 -07001040 // Now set the master mute in each playback thread. Playback threads
1041 // assigned to HALs which do not have master mute support will apply master
1042 // mute during the mix operation. Threads with HALs which do support master
1043 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001044 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1045 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1046 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001047 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048
1049 return NO_ERROR;
1050}
1051
1052float AudioFlinger::masterVolume() const
1053{
Glenn Kasten98067102011-12-13 11:47:54 -08001054 Mutex::Autolock _l(mLock);
1055 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056}
1057
1058bool AudioFlinger::masterMute() const
1059{
Glenn Kasten98067102011-12-13 11:47:54 -08001060 Mutex::Autolock _l(mLock);
1061 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062}
1063
John Grossman4ff14ba2012-02-08 16:37:41 -08001064float AudioFlinger::masterVolume_l() const
1065{
John Grossman4ff14ba2012-02-08 16:37:41 -08001066 return mMasterVolume;
1067}
1068
John Grossmand8f178d2012-07-20 14:51:35 -07001069bool AudioFlinger::masterMute_l() const
1070{
John Grossmanee578c02012-07-23 17:05:46 -07001071 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001072}
1073
Eric Laurent223fd5c2014-11-11 13:43:36 -08001074status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1075{
1076 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001077 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001078 return BAD_VALUE;
1079 }
1080 pid_t caller = IPCThreadState::self()->getCallingPid();
1081 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001082 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001083 return PERMISSION_DENIED;
1084 }
1085
1086 return NO_ERROR;
1087}
1088
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001089status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1090 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092 // check calling permissions
1093 if (!settingsAllowed()) {
1094 return PERMISSION_DENIED;
1095 }
1096
Eric Laurent223fd5c2014-11-11 13:43:36 -08001097 status_t status = checkStreamType(stream);
1098 if (status != NO_ERROR) {
1099 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001101 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102
1103 AutoMutex lock(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001104 Vector<VolumeInterface *> volumeInterfaces;
Glenn Kasten142f5192014-03-25 17:44:59 -07001105 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001106 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1107 if (volumeInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 return BAD_VALUE;
1109 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001110 volumeInterfaces.add(volumeInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111 }
1112
1113 mStreamTypes[stream].volume = value;
1114
Eric Laurent6acd1d42017-01-04 14:23:29 -08001115 if (volumeInterfaces.size() == 0) {
1116 volumeInterfaces = getAllVolumeInterfaces_l();
1117 }
1118 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1119 volumeInterfaces[i]->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 }
1121
1122 return NO_ERROR;
1123}
1124
Glenn Kastenfff6d712012-01-12 16:38:12 -08001125status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126{
1127 // check calling permissions
1128 if (!settingsAllowed()) {
1129 return PERMISSION_DENIED;
1130 }
1131
Eric Laurent223fd5c2014-11-11 13:43:36 -08001132 status_t status = checkStreamType(stream);
1133 if (status != NO_ERROR) {
1134 return status;
1135 }
1136 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1137
1138 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001139 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 return BAD_VALUE;
1141 }
1142
Eric Laurent93575202011-01-18 18:39:02 -08001143 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001145 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1146 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1147 volumeInterfaces[i]->setStreamMute(stream, muted);
1148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149
1150 return NO_ERROR;
1151}
1152
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001153float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001155 status_t status = checkStreamType(stream);
1156 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 return 0.0f;
1158 }
1159
1160 AutoMutex lock(mLock);
1161 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001162 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001163 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1164 if (volumeInterface != NULL) {
1165 volume = volumeInterface->streamVolume(stream);
1166 } else {
1167 volume = 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001170 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 }
1172
1173 return volume;
1174}
1175
Glenn Kastenfff6d712012-01-12 16:38:12 -08001176bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001178 status_t status = checkStreamType(stream);
1179 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 return true;
1181 }
1182
Glenn Kasten6637baa2012-01-09 09:40:36 -08001183 AutoMutex lock(mLock);
1184 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185}
1186
Eric Laurent054d9d32015-04-24 08:48:48 -07001187
1188void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1189{
1190 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1191 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1192 }
1193}
1194
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001195status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001197 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1198 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001199
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 // check calling permissions
1201 if (!settingsAllowed()) {
1202 return PERMISSION_DENIED;
1203 }
1204
Glenn Kasten142f5192014-03-25 17:44:59 -07001205 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1206 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001207 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001208 // result will remain NO_INIT if no audio device is present
1209 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001210 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001211 AutoMutex lock(mHardwareLock);
1212 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1213 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001214 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1215 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001216 // return success if at least one audio device accepts the parameters as not all
1217 // HALs are requested to support all parameters. If no audio device supports the
1218 // requested parameters, the last error is reported.
1219 if (final_result != NO_ERROR) {
1220 final_result = result;
1221 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001222 }
1223 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001224 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001225 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1226 AudioParameter param = AudioParameter(keyValuePairs);
1227 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001228 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1229 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001230 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001231 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001232 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001233 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001234 }
1235 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001236 String8 screenState;
1237 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001238 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001239 if (isOff != (AudioFlinger::mScreenState & 1)) {
1240 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001241 }
1242 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001243 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 }
1245
1246 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1247 // and the thread is exited once the lock is released
1248 sp<ThreadBase> thread;
1249 {
1250 Mutex::Autolock _l(mLock);
1251 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001252 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001254 if (thread == 0) {
1255 thread = checkMmapThread_l(ioHandle);
1256 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001257 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001258 // indicate output device change to all input threads for pre processing
1259 AudioParameter param = AudioParameter(keyValuePairs);
1260 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001261 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1262 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001263 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 }
1266 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001267 if (thread != 0) {
1268 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 }
1270 return BAD_VALUE;
1271}
1272
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001273String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001275 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1276 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277
Eric Laurenta4c5a552012-03-29 10:12:40 -07001278 Mutex::Autolock _l(mLock);
1279
Glenn Kasten142f5192014-03-25 17:44:59 -07001280 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001281 String8 out_s8;
1282
Dima Zavin799a70e2011-04-18 16:57:27 -07001283 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001284 String8 s;
1285 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001286 {
1287 AutoMutex lock(mHardwareLock);
1288 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001289 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1290 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001291 mHardwareStatus = AUDIO_HW_IDLE;
1292 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001293 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001294 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001295 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 }
1297
Eric Laurent6acd1d42017-01-04 14:23:29 -08001298 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1299 if (thread == NULL) {
1300 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1301 if (thread == NULL) {
1302 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1303 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001304 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001305 }
1306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001308 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309}
1310
Glenn Kastendd8104c2012-07-02 12:42:44 -07001311size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1312 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313{
Eric Laurenta1884f92011-08-23 08:25:03 -07001314 status_t ret = initCheck();
1315 if (ret != NO_ERROR) {
1316 return 0;
1317 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001318 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001319 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001320 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001321 return 0;
1322 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001323
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001324 AutoMutex lock(mHardwareLock);
1325 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001326 audio_config_t config, proposed;
1327 memset(&proposed, 0, sizeof(proposed));
1328 proposed.sample_rate = sampleRate;
1329 proposed.channel_mask = channelMask;
1330 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001331
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001332 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001333 size_t frames;
1334 for (;;) {
1335 // Note: config is currently a const parameter for get_input_buffer_size()
1336 // but we use a copy from proposed in case config changes from the call.
1337 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001338 status_t result = dev->getInputBufferSize(&config, &frames);
1339 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001340 break; // hal success, config is the result
1341 }
1342 // change one parameter of the configuration each iteration to a more "common" value
1343 // to see if the device will support it.
1344 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1345 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1346 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1347 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1348 } else {
1349 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1350 "format %#x, channelMask 0x%X",
1351 sampleRate, format, channelMask);
1352 break; // retries failed, break out of loop with frames == 0.
1353 }
1354 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001355 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001356 if (frames > 0 && config.sample_rate != sampleRate) {
1357 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1358 }
1359 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360}
1361
Glenn Kasten5f972c02014-01-13 09:59:31 -08001362uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364 Mutex::Autolock _l(mLock);
1365
1366 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1367 if (recordThread != NULL) {
1368 return recordThread->getInputFramesLost();
1369 }
1370 return 0;
1371}
1372
1373status_t AudioFlinger::setVoiceVolume(float value)
1374{
Eric Laurenta1884f92011-08-23 08:25:03 -07001375 status_t ret = initCheck();
1376 if (ret != NO_ERROR) {
1377 return ret;
1378 }
1379
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 // check calling permissions
1381 if (!settingsAllowed()) {
1382 return PERMISSION_DENIED;
1383 }
1384
1385 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001386 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001387 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001388 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389 mHardwareStatus = AUDIO_HW_IDLE;
1390
1391 return ret;
1392}
1393
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001394status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001395 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397 Mutex::Autolock _l(mLock);
1398
1399 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1400 if (playbackThread != NULL) {
1401 return playbackThread->getRenderPosition(halFrames, dspFrames);
1402 }
1403
1404 return BAD_VALUE;
1405}
1406
1407void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1408{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001410 if (client == 0) {
1411 return;
1412 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001413 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001414 {
1415 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001416 if (mNotificationClients.indexOfKey(pid) < 0) {
1417 sp<NotificationClient> notificationClient = new NotificationClient(this,
1418 client,
1419 pid);
1420 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421
Eric Laurent021cf962014-05-13 10:18:14 -07001422 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423
Marco Nelissen06b46062014-11-14 07:58:25 -08001424 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001425 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001426 }
1427 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428
Eric Laurent021cf962014-05-13 10:18:14 -07001429 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001430 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001431 // the config change is always sent from playback or record threads to avoid deadlock
1432 // with AudioSystem::gLock
1433 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001434 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001437 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001438 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 }
1440}
1441
1442void AudioFlinger::removeNotificationClient(pid_t pid)
1443{
1444 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001445 {
1446 Mutex::Autolock _cl(mClientLock);
1447 mNotificationClients.removeItem(pid);
1448 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001449
Steve Block3856b092011-10-20 11:56:00 +01001450 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001451 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001452 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001453 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001454 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001455 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001456 if (ref->mPid == pid) {
1457 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001458 mAudioSessionRefs.removeAt(i);
1459 delete ref;
1460 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001461 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001462 } else {
1463 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001464 }
1465 }
1466 if (removed) {
1467 purgeStaleEffects_l();
1468 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469}
1470
Eric Laurent73e26b62015-04-27 16:55:58 -07001471void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001472 const sp<AudioIoDescriptor>& ioDesc,
1473 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474{
Eric Laurent021cf962014-05-13 10:18:14 -07001475 Mutex::Autolock _l(mClientLock);
1476 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001478 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1479 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 }
1482}
1483
Eric Laurent021cf962014-05-13 10:18:14 -07001484// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485void AudioFlinger::removeClient_l(pid_t pid)
1486{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001487 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001488 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 mClients.removeItem(pid);
1490}
1491
Eric Laurent717e1282012-06-29 16:36:52 -07001492// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001493sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1494 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001495{
1496 sp<PlaybackThread> thread;
1497
1498 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1499 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1500 ALOG_ASSERT(thread == 0);
1501 thread = mPlaybackThreads.valueAt(i);
1502 }
1503 }
1504
1505 return thread;
1506}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509
1510// ----------------------------------------------------------------------------
1511
1512AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1513 : RefBase(),
1514 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001515 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516{
Andy Hung6f248bb2018-01-23 14:04:37 -08001517 mMemoryDealer = new MemoryDealer(
1518 audioFlinger->getClientSharedHeapSize(),
1519 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520}
1521
Eric Laurent021cf962014-05-13 10:18:14 -07001522// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523AudioFlinger::Client::~Client()
1524{
1525 mAudioFlinger->removeClient_l(mPid);
1526}
1527
Glenn Kasten435dbe62012-01-30 10:15:48 -08001528sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529{
1530 return mMemoryDealer;
1531}
1532
1533// ----------------------------------------------------------------------------
1534
1535AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1536 const sp<IAudioFlingerClient>& client,
1537 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001538 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539{
1540}
1541
1542AudioFlinger::NotificationClient::~NotificationClient()
1543{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544}
1545
Glenn Kasten0f11b512014-01-31 16:18:54 -08001546void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547{
1548 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001549 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550}
1551
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001552// ----------------------------------------------------------------------------
1553AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1554 : mPendingRequests(false) {}
1555
1556
1557void AudioFlinger::MediaLogNotifier::requestMerge() {
1558 AutoMutex _l(mMutex);
1559 mPendingRequests = true;
1560 mCond.signal();
1561}
1562
1563bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001564 // Should already have been checked, but just in case
1565 if (sMediaLogService == 0) {
1566 return false;
1567 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001568 // Wait until there are pending requests
1569 {
1570 AutoMutex _l(mMutex);
1571 mPendingRequests = false; // to ignore past requests
1572 while (!mPendingRequests) {
1573 mCond.wait(mMutex);
1574 // TODO may also need an exitPending check
1575 }
1576 mPendingRequests = false;
1577 }
1578 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001579 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001580 usleep(kPostTriggerSleepPeriod);
1581 return true;
1582}
1583
1584void AudioFlinger::requestLogMerge() {
1585 mMediaLogNotifier->requestMerge();
1586}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587
1588// ----------------------------------------------------------------------------
1589
Eric Laurentf14db3c2017-12-08 14:20:36 -08001590sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1591 CreateRecordOutput& output,
1592 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593{
1594 sp<RecordThread::RecordTrack> recordTrack;
1595 sp<RecordHandle> recordHandle;
1596 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001598 audio_session_t sessionId = input.sessionId;
1599 audio_port_handle_t portId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600
Eric Laurentf14db3c2017-12-08 14:20:36 -08001601 output.cblk.clear();
1602 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001603 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001604
Eric Laurentf14db3c2017-12-08 14:20:36 -08001605 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001606 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001607 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001608 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001609 ALOGW_IF(clientUid != callingUid,
1610 "%s uid %d tried to pass itself off as %d",
1611 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001612 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001613 updatePid = true;
1614 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001615 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001616 if (updatePid) {
1617 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001618 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001619 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001620 __func__, callingUid, callingPid, clientPid);
1621 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001622 }
1623
Eric Laurent67651f92018-01-29 14:27:03 -08001624 // check calling permissions
1625 if (!recordingAllowed(input.opPackageName, input.clientInfo.clientTid, clientUid)) {
1626 ALOGE("createRecord() permission denied: recording not allowed");
1627 lStatus = PERMISSION_DENIED;
1628 goto Exit;
1629 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001630 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001631 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1632 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001633 lStatus = BAD_VALUE;
1634 goto Exit;
1635 }
1636
Glenn Kasten53b5d092014-02-05 10:00:23 -08001637 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001638 if (!audio_is_input_channel(input.config.channel_mask)) {
1639 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001640 lStatus = BAD_VALUE;
1641 goto Exit;
1642 }
1643
Eric Laurentf14db3c2017-12-08 14:20:36 -08001644 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1645 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1646 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1647 lStatus = BAD_VALUE;
1648 goto Exit;
1649 }
1650
1651 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001652 output.selectedDeviceId = input.selectedDeviceId;
1653 output.flags = input.flags;
1654
1655 client = registerPid(clientPid);
1656
1657 // Not a conventional loop, but a retry loop for at most two iterations total.
1658 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1659 // Exits loop via break on no error of got exit on error
1660 // The sp<> references will be dropped when re-entering scope.
1661 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1662 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001663 // release previously opened input if retrying.
1664 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1665 recordTrack.clear();
Eric Laurente9ebcdb2018-01-29 14:27:18 -08001666 AudioSystem::releaseInput(output.inputId, sessionId);
Eric Laurent896c9672017-12-08 14:08:45 -08001667 output.inputId = AUDIO_IO_HANDLE_NONE;
1668 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001669 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1670 sessionId,
1671 // FIXME compare to AudioTrack
1672 clientPid,
1673 clientUid,
1674 &input.config,
1675 output.flags, &output.selectedDeviceId, &portId);
1676
Glenn Kasten05997e22014-03-13 15:08:33 -07001677 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001679 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001681 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682 lStatus = BAD_VALUE;
1683 goto Exit;
1684 }
1685
Eric Laurentf14db3c2017-12-08 14:20:36 -08001686 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687
Eric Laurentf14db3c2017-12-08 14:20:36 -08001688 output.sampleRate = input.config.sample_rate;
1689 output.frameCount = input.frameCount;
1690 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001691
Eric Laurentf14db3c2017-12-08 14:20:36 -08001692 recordTrack = thread->createRecordTrack_l(client, &output.sampleRate,
1693 input.config.format, input.config.channel_mask,
1694 &output.frameCount, sessionId,
1695 &output.notificationFrameCount,
1696 clientUid, &output.flags,
1697 input.clientInfo.clientTid,
1698 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001699 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001700
Eric Laurentf14db3c2017-12-08 14:20:36 -08001701 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1702 // audio policy manager without FAST constraint
1703 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001704 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001705 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001706
1707 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001708 goto Exit;
1709 }
1710
1711 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1712 // session and move it to this thread.
1713 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1714 if (chain != 0) {
1715 Mutex::Autolock _l(thread->mLock);
1716 thread->addEffectChain_l(chain);
1717 }
1718 break;
1719 }
1720 // End of retry loop.
1721 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722 }
Glenn Kastene198c362013-08-13 09:13:36 -07001723
Eric Laurentf14db3c2017-12-08 14:20:36 -08001724 output.cblk = recordTrack->getCblk();
1725 output.buffers = recordTrack->getBuffers();
1726
1727 // return handle to client
1728 recordHandle = new RecordHandle(recordTrack);
1729
1730Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001731 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001732 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001733 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001734 // Don't hold mClientLock when releasing the reference on the track as the
1735 // destructor will acquire it.
1736 {
1737 Mutex::Autolock _cl(mClientLock);
1738 client.clear();
1739 }
Eric Laurent896c9672017-12-08 14:08:45 -08001740 recordTrack.clear();
1741 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurente9ebcdb2018-01-29 14:27:18 -08001742 AudioSystem::releaseInput(output.inputId, sessionId);
Eric Laurent896c9672017-12-08 14:08:45 -08001743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 }
1745
Glenn Kasten9156ef32013-08-06 15:39:08 -07001746 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 return recordHandle;
1748}
1749
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001750
1751
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752// ----------------------------------------------------------------------------
1753
Eric Laurenta4c5a552012-03-29 10:12:40 -07001754audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1755{
Eric Laurent44622db2014-08-01 19:00:33 -07001756 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001757 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001758 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001759 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001760 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001761 }
1762 Mutex::Autolock _l(mLock);
1763 return loadHwModule_l(name);
1764}
1765
1766// loadHwModule_l() must be called with AudioFlinger::mLock held
1767audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1768{
1769 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1770 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1771 ALOGW("loadHwModule() module %s already loaded", name);
1772 return mAudioHwDevs.keyAt(i);
1773 }
1774 }
1775
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001776 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001777
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001778 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001779 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001780 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001781 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001782 }
1783
1784 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001785 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001786 mHardwareStatus = AUDIO_HW_IDLE;
1787 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001788 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001789 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001790 }
1791
John Grossmanee578c02012-07-23 17:05:46 -07001792 // Check and cache this HAL's level of support for master mute and master
1793 // volume. If this is the first HAL opened, and it supports the get
1794 // methods, use the initial values provided by the HAL as the current
1795 // master mute and volume settings.
1796
1797 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1798 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001799 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001800
1801 if (0 == mAudioHwDevs.size()) {
1802 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001803 float mv;
1804 if (OK == dev->getMasterVolume(&mv)) {
1805 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001806 }
1807
1808 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001809 bool mm;
1810 if (OK == dev->getMasterMute(&mm)) {
1811 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001812 }
1813 }
1814
Eric Laurenta4c5a552012-03-29 10:12:40 -07001815 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001816 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001817 flags = static_cast<AudioHwDevice::Flags>(flags |
1818 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1819 }
1820
1821 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001822 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001823 flags = static_cast<AudioHwDevice::Flags>(flags |
1824 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1825 }
1826
Eric Laurenta4c5a552012-03-29 10:12:40 -07001827 mHardwareStatus = AUDIO_HW_IDLE;
1828 }
1829
Glenn Kastena13cde92016-03-28 15:26:02 -07001830 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001831 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001832
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001833 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001834
1835 return handle;
1836
1837}
1838
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001839// ----------------------------------------------------------------------------
1840
Glenn Kasten3b16c762012-11-14 08:44:39 -08001841uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001842{
1843 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001844 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001845 return thread != NULL ? thread->sampleRate() : 0;
1846}
1847
Glenn Kastene33054e2012-11-14 12:54:39 -08001848size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001849{
1850 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001851 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001852 return thread != NULL ? thread->frameCountHAL() : 0;
1853}
1854
1855// ----------------------------------------------------------------------------
1856
Andy Hung6f248bb2018-01-23 14:04:37 -08001857status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001858{
1859 uid_t uid = IPCThreadState::self()->getCallingUid();
1860 if (uid != AID_SYSTEM) {
1861 return PERMISSION_DENIED;
1862 }
1863 Mutex::Autolock _l(mLock);
1864 if (mIsDeviceTypeKnown) {
1865 return INVALID_OPERATION;
1866 }
1867 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001868 mTotalMemory = totalMemory;
1869 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1870 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1871 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1872 // though actual setting is determined through device configuration.
1873 constexpr int64_t GB = 1024 * 1024 * 1024;
1874 mClientSharedHeapSize =
1875 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1876 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1877 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1878 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1879 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001880 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001881
1882 // TODO: Cache the client shared heap size in a persistent property.
1883 // It's possible that a native process or Java service or app accesses audioserver
1884 // after it is registered by system server, but before AudioService updates
1885 // the memory info. This would occur immediately after boot or an audioserver
1886 // crash and restore. Before update from AudioService, the client would get the
1887 // minimum heap size.
1888
1889 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1890 (isLowRamDevice ? "true" : "false"),
1891 (long long)mTotalMemory,
1892 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001893 return NO_ERROR;
1894}
1895
Andy Hung6f248bb2018-01-23 14:04:37 -08001896size_t AudioFlinger::getClientSharedHeapSize() const
1897{
1898 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1899 if (heapSizeInBytes != 0) { // read-only property overrides all.
1900 return heapSizeInBytes;
1901 }
1902 return mClientSharedHeapSize;
1903}
1904
Eric Laurent93c3d412014-08-01 14:48:35 -07001905audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1906{
1907 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001908
1909 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1910 if (index >= 0) {
1911 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1912 mHwAvSyncIds.valueAt(index), sessionId);
1913 return mHwAvSyncIds.valueAt(index);
1914 }
1915
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001916 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001917 if (dev == NULL) {
1918 return AUDIO_HW_SYNC_INVALID;
1919 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001920 String8 reply;
1921 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001922 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001923 param = AudioParameter(reply);
1924 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001925
1926 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001927 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001928 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1929 return AUDIO_HW_SYNC_INVALID;
1930 }
1931
1932 // allow only one session for a given HW A/V sync ID.
1933 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1934 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1935 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1936 value, mHwAvSyncIds.keyAt(i));
1937 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001938 break;
1939 }
1940 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001941
1942 mHwAvSyncIds.add(sessionId, value);
1943
1944 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1945 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1946 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001947 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001948 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001949 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001950 thread->setParameters(param.toString());
1951 break;
1952 }
1953 }
1954
1955 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1956 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001957}
1958
Eric Laurent72e3f392015-05-20 14:43:50 -07001959status_t AudioFlinger::systemReady()
1960{
1961 Mutex::Autolock _l(mLock);
1962 ALOGI("%s", __FUNCTION__);
1963 if (mSystemReady) {
1964 ALOGW("%s called twice", __FUNCTION__);
1965 return NO_ERROR;
1966 }
1967 mSystemReady = true;
1968 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1969 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1970 thread->systemReady();
1971 }
1972 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1973 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1974 thread->systemReady();
1975 }
1976 return NO_ERROR;
1977}
1978
jiabin46a76fa2018-01-05 10:18:21 -08001979status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
1980{
1981 // Fake data
1982 size_t fakeNum = 2;
1983 audio_devices_t fakeTypes[] = { AUDIO_DEVICE_IN_BUILTIN_MIC, AUDIO_DEVICE_IN_BACK_MIC };
1984 for (size_t i = 0; i < fakeNum; i++) {
1985 struct audio_microphone_characteristic_t characteristics;
1986 sprintf(characteristics.device_id, "microphone:%zu", i);
rago1de79cf2018-02-01 15:21:02 -08001987 characteristics.device = fakeTypes[i];
jiabin46a76fa2018-01-05 10:18:21 -08001988 sprintf(characteristics.address, "");
1989 characteristics.location = AUDIO_MICROPHONE_LOCATION_MAINBODY;
1990 characteristics.group = 0;
1991 characteristics.index_in_the_group = i;
1992 characteristics.sensitivity = 1.0f;
1993 characteristics.max_spl = 100.0f;
1994 characteristics.min_spl = 0.0f;
1995 characteristics.directionality = AUDIO_MICROPHONE_DIRECTIONALITY_OMNI;
1996 characteristics.num_frequency_responses = 5 - i;
1997 for (size_t j = 0; j < characteristics.num_frequency_responses; j++) {
1998 characteristics.frequency_responses[0][j] = 100.0f - j;
1999 characteristics.frequency_responses[1][j] = 100.0f + j;
2000 }
2001 for (size_t j = 0; j < AUDIO_CHANNEL_COUNT_MAX; j++) {
2002 characteristics.channel_mapping[j] = AUDIO_MICROPHONE_CHANNEL_MAPPING_UNUSED;
2003 }
2004 characteristics.geometric_location.x = 0.1f;
2005 characteristics.geometric_location.y = 0.2f;
2006 characteristics.geometric_location.z = 0.3f;
2007 characteristics.orientation.x = 0.0f;
2008 characteristics.orientation.y = 1.0f;
2009 characteristics.orientation.z = 0.0f;
2010 media::MicrophoneInfo microphoneInfo = media::MicrophoneInfo(characteristics);
2011 microphones->push_back(microphoneInfo);
2012 }
2013 return NO_ERROR;
2014}
2015
Eric Laurentfa90e842014-10-17 18:12:31 -07002016// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2017void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2018{
2019 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2020 if (index >= 0) {
2021 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2022 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2023 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002024 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002025 thread->setParameters(param.toString());
2026 }
2027}
2028
2029
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002030// ----------------------------------------------------------------------------
2031
Eric Laurent83b88082014-06-20 18:31:16 -07002032
Eric Laurent6acd1d42017-01-04 14:23:29 -08002033sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002034 audio_io_handle_t *output,
2035 audio_config_t *config,
2036 audio_devices_t devices,
2037 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002038 audio_output_flags_t flags)
2039{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002040 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002041 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002042 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002043 }
2044
Eric Laurentcf2c0212014-07-25 16:20:43 -07002045 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002046 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2047 } else {
2048 // Audio Policy does not currently request a specific output handle.
2049 // If this is ever needed, see openInput_l() for example code.
2050 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2051 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002052 }
Eric Laurent83b88082014-06-20 18:31:16 -07002053
2054 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2055
Eric Laurent83b88082014-06-20 18:31:16 -07002056 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002057 // This if statement allows overriding the audio policy settings
2058 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2059 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2060 // Check only for Normal Mixing mode
2061 if (kEnableExtendedPrecision) {
2062 // Specify format (uncomment one below to choose)
2063 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2064 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2065 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2066 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002067 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002068 }
2069 if (kEnableExtendedChannels) {
2070 // Specify channel mask (uncomment one below to choose)
2071 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2072 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2073 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2074 }
Eric Laurent83b88082014-06-20 18:31:16 -07002075 }
2076
Phil Burk062e67a2015-02-11 13:40:50 -08002077 AudioStreamOut *outputStream = NULL;
2078 status_t status = outHwDev->openOutputStream(
2079 &outputStream,
2080 *output,
2081 devices,
2082 flags,
2083 config,
2084 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002085
2086 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002087
Phil Burk062e67a2015-02-11 13:40:50 -08002088 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002089 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2090 sp<MmapPlaybackThread> thread =
2091 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2092 devices, AUDIO_DEVICE_NONE, mSystemReady);
2093 mMmapThreads.add(*output, thread);
2094 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2095 *output, thread.get());
2096 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002097 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002098 sp<PlaybackThread> thread;
2099 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2100 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2101 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2102 *output, thread.get());
2103 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2104 || !isValidPcmSinkFormat(config->format)
2105 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2106 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2107 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2108 *output, thread.get());
2109 } else {
2110 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2111 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2112 *output, thread.get());
2113 }
2114 mPlaybackThreads.add(*output, thread);
2115 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002116 }
Eric Laurent83b88082014-06-20 18:31:16 -07002117 }
2118
2119 return 0;
2120}
2121
Eric Laurentcf2c0212014-07-25 16:20:43 -07002122status_t AudioFlinger::openOutput(audio_module_handle_t module,
2123 audio_io_handle_t *output,
2124 audio_config_t *config,
2125 audio_devices_t *devices,
2126 const String8& address,
2127 uint32_t *latencyMs,
2128 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002130 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2131 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002132 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002133 (devices != NULL) ? *devices : 0,
2134 config->sample_rate,
2135 config->format,
2136 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002137 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002139 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002140 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002142
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 Mutex::Autolock _l(mLock);
2144
Eric Laurent6acd1d42017-01-04 14:23:29 -08002145 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002146 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002147 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2148 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2149 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150
Eric Laurent6acd1d42017-01-04 14:23:29 -08002151 // notify client processes of the new output creation
2152 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002153
Eric Laurent6acd1d42017-01-04 14:23:29 -08002154 // the first primary output opened designates the primary hw device
2155 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002156 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002157 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002158
Eric Laurent6acd1d42017-01-04 14:23:29 -08002159 AutoMutex lock(mHardwareLock);
2160 mHardwareStatus = AUDIO_HW_SET_MODE;
2161 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2162 mHardwareStatus = AUDIO_HW_IDLE;
2163 }
2164 } else {
2165 MmapThread *mmapThread = (MmapThread *)thread.get();
2166 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002167 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002168 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 }
2170
Eric Laurentcf2c0212014-07-25 16:20:43 -07002171 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172}
2173
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002174audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2175 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176{
2177 Mutex::Autolock _l(mLock);
2178 MixerThread *thread1 = checkMixerThread_l(output1);
2179 MixerThread *thread2 = checkMixerThread_l(output2);
2180
2181 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002182 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2183 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002184 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185 }
2186
Glenn Kasteneeecb982016-02-26 10:44:04 -08002187 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002188 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 thread->addOutputTrack(thread2);
2190 mPlaybackThreads.add(id, thread);
2191 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002192 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 return id;
2194}
2195
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002196status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197{
Glenn Kastend96c5722012-04-25 13:44:49 -07002198 return closeOutput_nonvirtual(output);
2199}
2200
2201status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2202{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 // keep strong reference on the playback thread so that
2204 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002205 sp<PlaybackThread> playbackThread;
2206 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 {
2208 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002209 playbackThread = checkPlaybackThread_l(output);
2210 if (playbackThread != NULL) {
2211 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212
Eric Laurent6acd1d42017-01-04 14:23:29 -08002213 if (playbackThread->type() == ThreadBase::MIXER) {
2214 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2215 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2216 DuplicatingThread *dupThread =
2217 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2218 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2219 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002220 }
2221 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002222
2223
Eric Laurent6acd1d42017-01-04 14:23:29 -08002224 mPlaybackThreads.removeItem(output);
2225 // save all effects to the default thread
2226 if (mPlaybackThreads.size()) {
2227 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2228 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002229 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002230 Mutex::Autolock _dl(dstThread->mLock);
2231 Mutex::Autolock _sl(playbackThread->mLock);
2232 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2233 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002234 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2235 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002236 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 }
2238 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002239 } else {
2240 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2241 if (mmapThread == 0) {
2242 return BAD_VALUE;
2243 }
2244 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002245 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002247 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2248 ioDesc->mIoHandle = output;
2249 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002251 // The thread entity (active unit of execution) is no longer running here,
2252 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253
Eric Laurent6acd1d42017-01-04 14:23:29 -08002254 if (playbackThread != 0) {
2255 playbackThread->exit();
2256 if (!playbackThread->isDuplicating()) {
2257 closeOutputFinish(playbackThread);
2258 }
2259 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002260 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002261 mmapThread->exit();
2262 AudioStreamOut *out = mmapThread->clearOutput();
2263 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2264 // from now on thread->mOutput is NULL
2265 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 }
2267 return NO_ERROR;
2268}
2269
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002270void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002271{
2272 AudioStreamOut *out = thread->clearOutput();
2273 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2274 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002275 delete out;
2276}
2277
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002278void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002279{
2280 mPlaybackThreads.removeItem(thread->mId);
2281 thread->exit();
2282 closeOutputFinish(thread);
2283}
2284
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002285status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286{
2287 Mutex::Autolock _l(mLock);
2288 PlaybackThread *thread = checkPlaybackThread_l(output);
2289
2290 if (thread == NULL) {
2291 return BAD_VALUE;
2292 }
2293
Steve Block3856b092011-10-20 11:56:00 +01002294 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 thread->suspend();
2296
2297 return NO_ERROR;
2298}
2299
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002300status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301{
2302 Mutex::Autolock _l(mLock);
2303 PlaybackThread *thread = checkPlaybackThread_l(output);
2304
2305 if (thread == NULL) {
2306 return BAD_VALUE;
2307 }
2308
Steve Block3856b092011-10-20 11:56:00 +01002309 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310
2311 thread->restore();
2312
2313 return NO_ERROR;
2314}
2315
Eric Laurentcf2c0212014-07-25 16:20:43 -07002316status_t AudioFlinger::openInput(audio_module_handle_t module,
2317 audio_io_handle_t *input,
2318 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002319 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002320 const String8& address,
2321 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002322 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323{
Eric Laurent83b88082014-06-20 18:31:16 -07002324 Mutex::Autolock _l(mLock);
2325
Glenn Kastene7d66712015-03-05 13:46:52 -08002326 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002327 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002328 }
2329
Eric Laurent6acd1d42017-01-04 14:23:29 -08002330 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002331
2332 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002333 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002334 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002335 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002337 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002338}
Dima Zavin799a70e2011-04-18 16:57:27 -07002339
Eric Laurent6acd1d42017-01-04 14:23:29 -08002340sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002341 audio_io_handle_t *input,
2342 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002343 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002344 const String8& address,
2345 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002346 audio_input_flags_t flags)
2347{
Glenn Kastene7d66712015-03-05 13:46:52 -08002348 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002349 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002350 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002351 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002352 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002353
Glenn Kasteneeecb982016-02-26 10:44:04 -08002354 // Audio Policy can request a specific handle for hardware hotword.
2355 // The goal here is not to re-open an already opened input.
2356 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002357 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002358 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2359 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2360 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2361 return 0;
2362 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2363 // This should not happen in a transient state with current design.
2364 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2365 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002366 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002367
Eric Laurentcf2c0212014-07-25 16:20:43 -07002368 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002369 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002370 sp<StreamInHalInterface> inStream;
2371 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002372 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002373 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2374 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002375 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002376 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002377 halconfig.sample_rate,
2378 halconfig.format,
2379 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002380 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002381 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002383 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002384 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002385 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002386 audio_is_linear_pcm(config->format) &&
2387 audio_is_linear_pcm(halconfig.format) &&
2388 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002389 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2390 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002391 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002392 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002393 inStream.clear();
2394 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002395 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002396 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397 }
2398
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002399 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002400 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002401 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2402 sp<MmapCaptureThread> thread =
2403 new MmapCaptureThread(this, *input,
2404 inHwDev, inputStream,
2405 primaryOutputDevice_l(), devices, mSystemReady);
2406 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002407 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2408 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002409 return thread;
2410 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002411#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002412 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2413 // or (re-)create if current Pipe is idle and does not match the new format
2414 sp<NBAIO_Sink> teeSink;
2415 enum {
2416 TEE_SINK_NO, // don't copy input
2417 TEE_SINK_NEW, // copy input using a new pipe
2418 TEE_SINK_OLD, // copy input using an existing pipe
2419 } kind;
2420 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2421 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2422 if (!mTeeSinkInputEnabled) {
2423 kind = TEE_SINK_NO;
2424 } else if (!Format_isValid(format)) {
2425 kind = TEE_SINK_NO;
2426 } else if (mRecordTeeSink == 0) {
2427 kind = TEE_SINK_NEW;
2428 } else if (mRecordTeeSink->getStrongCount() != 1) {
2429 kind = TEE_SINK_NO;
2430 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2431 kind = TEE_SINK_OLD;
2432 } else {
2433 kind = TEE_SINK_NEW;
2434 }
2435 switch (kind) {
2436 case TEE_SINK_NEW: {
2437 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2438 size_t numCounterOffers = 0;
2439 const NBAIO_Format offers[1] = {format};
2440 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2441 ALOG_ASSERT(index == 0);
2442 PipeReader *pipeReader = new PipeReader(*pipe);
2443 numCounterOffers = 0;
2444 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2445 ALOG_ASSERT(index == 0);
2446 mRecordTeeSink = pipe;
2447 mRecordTeeSource = pipeReader;
2448 teeSink = pipe;
2449 }
2450 break;
2451 case TEE_SINK_OLD:
2452 teeSink = mRecordTeeSink;
2453 break;
2454 case TEE_SINK_NO:
2455 default:
2456 break;
2457 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002458#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002459
2460 // Start record thread
2461 // RecordThread requires both input and output device indication to forward to audio
2462 // pre processing modules
2463 sp<RecordThread> thread = new RecordThread(this,
2464 inputStream,
2465 *input,
2466 primaryOutputDevice_l(),
2467 devices,
2468 mSystemReady
2469#ifdef TEE_SINK
2470 , teeSink
2471#endif
2472 );
2473 mRecordThreads.add(*input, thread);
2474 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2475 return thread;
2476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 }
2478
Eric Laurentcf2c0212014-07-25 16:20:43 -07002479 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 return 0;
2481}
2482
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002483status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484{
Glenn Kastend96c5722012-04-25 13:44:49 -07002485 return closeInput_nonvirtual(input);
2486}
2487
2488status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2489{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 // keep strong reference on the record thread so that
2491 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002492 sp<RecordThread> recordThread;
2493 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 {
2495 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002496 recordThread = checkRecordThread_l(input);
2497 if (recordThread != 0) {
2498 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499
Eric Laurent6acd1d42017-01-04 14:23:29 -08002500 // If we still have effect chains, it means that a client still holds a handle
2501 // on at least one effect. We must either move the chain to an existing thread with the
2502 // same session ID or put it aside in case a new record thread is opened for a
2503 // new capture on the same session
2504 sp<EffectChain> chain;
2505 {
2506 Mutex::Autolock _sl(recordThread->mLock);
2507 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2508 // Note: maximum one chain per record thread
2509 if (effectChains.size() != 0) {
2510 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002511 }
2512 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002513 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002514 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002515 // This should only happen in case of overlap between one thread tear down and the
2516 // creation of its replacement
2517 size_t i;
2518 for (i = 0; i < mRecordThreads.size(); i++) {
2519 sp<RecordThread> t = mRecordThreads.valueAt(i);
2520 if (t == recordThread) {
2521 continue;
2522 }
2523 if (t->hasAudioSession(chain->sessionId()) != 0) {
2524 Mutex::Autolock _l(t->mLock);
2525 ALOGV("closeInput() found thread %d for effect session %d",
2526 t->id(), chain->sessionId());
2527 t->addEffectChain_l(chain);
2528 break;
2529 }
2530 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002531 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002532 if (i == mRecordThreads.size()) {
2533 putOrphanEffectChain_l(chain);
2534 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002535 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002536 mRecordThreads.removeItem(input);
2537 } else {
2538 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2539 if (mmapThread == 0) {
2540 return BAD_VALUE;
2541 }
2542 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002543 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002544 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2545 ioDesc->mIoHandle = input;
2546 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 }
Eric Laurent83b88082014-06-20 18:31:16 -07002548 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2549 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002550 if (recordThread != 0) {
2551 closeInputFinish(recordThread);
2552 } else if (mmapThread != 0) {
2553 mmapThread->exit();
2554 AudioStreamIn *in = mmapThread->clearInput();
2555 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2556 // from now on thread->mInput is NULL
2557 delete in;
2558 }
Eric Laurent83b88082014-06-20 18:31:16 -07002559 return NO_ERROR;
2560}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002562void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002563{
2564 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002565 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002566 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002567 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002568 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002569}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002571void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002572{
2573 mRecordThreads.removeItem(thread->mId);
2574 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575}
2576
Glenn Kastend2304db2014-02-03 07:40:31 -08002577status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578{
2579 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002580 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581
2582 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2583 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002584 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002585 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002586 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2587 mMmapThreads[i]->invalidateTracks(stream);
2588 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 return NO_ERROR;
2590}
2591
2592
Glenn Kasteneeecb982016-02-26 10:44:04 -08002593audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594{
Glenn Kasten9d003132016-04-06 14:38:09 -07002595 // This is a binder API, so a malicious client could pass in a bad parameter.
2596 // Check for that before calling the internal API nextUniqueId().
2597 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2598 ALOGE("newAudioUniqueId invalid use %d", use);
2599 return AUDIO_UNIQUE_ID_ALLOCATE;
2600 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002601 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602}
2603
Glenn Kastend848eb42016-03-08 13:42:11 -08002604void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002605{
2606 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002607 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002608 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2609 if (pid != -1 && (caller == getpid_cached)) {
2610 caller = pid;
2611 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002612
Eric Laurent021cf962014-05-13 10:18:14 -07002613 {
2614 Mutex::Autolock _cl(mClientLock);
2615 // Ignore requests received from processes not known as notification client. The request
2616 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2617 // called from a different pid leaving a stale session reference. Also we don't know how
2618 // to clear this reference if the client process dies.
2619 if (mNotificationClients.indexOfKey(caller) < 0) {
2620 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2621 return;
2622 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002623 }
2624
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002625 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002626 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002627 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002628 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2629 ref->mCnt++;
2630 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002631 return;
2632 }
2633 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002634 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2635 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002636}
2637
Glenn Kastend848eb42016-03-08 13:42:11 -08002638void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002639{
2640 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002641 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002642 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2643 if (pid != -1 && (caller == getpid_cached)) {
2644 caller = pid;
2645 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002646 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002647 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002648 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002649 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2650 ref->mCnt--;
2651 ALOGV(" decremented refcount to %d", ref->mCnt);
2652 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002653 mAudioSessionRefs.removeAt(i);
2654 delete ref;
2655 purgeStaleEffects_l();
2656 }
2657 return;
2658 }
2659 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002660 // If the caller is mediaserver it is likely that the session being released was acquired
2661 // on behalf of a process not in notification clients and we ignore the warning.
2662 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002663}
2664
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002665bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2666{
2667 size_t num = mAudioSessionRefs.size();
2668 for (size_t i = 0; i < num; i++) {
2669 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2670 if (ref->mSessionid == audioSession) {
2671 return true;
2672 }
2673 }
2674 return false;
2675}
2676
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002677void AudioFlinger::purgeStaleEffects_l() {
2678
Steve Block3856b092011-10-20 11:56:00 +01002679 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002680
2681 Vector< sp<EffectChain> > chains;
2682
2683 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2684 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002685 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002686 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2687 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002688 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2689 chains.push(ec);
2690 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002691 }
2692 }
2693 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2694 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002695 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002696 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2697 sp<EffectChain> ec = t->mEffectChains[j];
2698 chains.push(ec);
2699 }
2700 }
2701
2702 for (size_t i = 0; i < chains.size(); i++) {
2703 sp<EffectChain> ec = chains[i];
2704 int sessionid = ec->sessionId();
2705 sp<ThreadBase> t = ec->mThread.promote();
2706 if (t == 0) {
2707 continue;
2708 }
2709 size_t numsessionrefs = mAudioSessionRefs.size();
2710 bool found = false;
2711 for (size_t k = 0; k < numsessionrefs; k++) {
2712 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002713 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002714 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002715 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002716 found = true;
2717 break;
2718 }
2719 }
2720 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002721 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002722 // remove all effects from the chain
2723 while (ec->mEffects.size()) {
2724 sp<EffectModule> effect = ec->mEffects[0];
2725 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002726 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002727 if (effect->purgeHandles()) {
2728 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002729 }
2730 AudioSystem::unregisterEffect(effect->id());
2731 }
2732 }
2733 }
2734 return;
2735}
2736
Glenn Kasteneeecb982016-02-26 10:44:04 -08002737// checkThread_l() must be called with AudioFlinger::mLock held
2738AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2739{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002740 ThreadBase *thread = checkMmapThread_l(ioHandle);
2741 if (thread == 0) {
2742 switch (audio_unique_id_get_use(ioHandle)) {
2743 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2744 thread = checkPlaybackThread_l(ioHandle);
2745 break;
2746 case AUDIO_UNIQUE_ID_USE_INPUT:
2747 thread = checkRecordThread_l(ioHandle);
2748 break;
2749 default:
2750 break;
2751 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002752 }
2753 return thread;
2754}
2755
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002757AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758{
Glenn Kastena1117922012-01-26 10:53:32 -08002759 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760}
2761
2762// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002763AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764{
2765 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002766 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767}
2768
2769// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002770AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771{
Glenn Kastena1117922012-01-26 10:53:32 -08002772 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773}
2774
Eric Laurent6acd1d42017-01-04 14:23:29 -08002775// checkMmapThread_l() must be called with AudioFlinger::mLock held
2776AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2777{
2778 return mMmapThreads.valueFor(io).get();
2779}
2780
2781
2782// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2783AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2784{
Eric Laurent7459b902017-04-19 18:10:41 -07002785 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002786 if (volumeInterface == nullptr) {
2787 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2788 if (mmapThread != nullptr) {
2789 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002790 MmapPlaybackThread *mmapPlaybackThread =
2791 static_cast<MmapPlaybackThread *>(mmapThread);
2792 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002793 }
2794 }
2795 }
2796 return volumeInterface;
2797}
2798
2799Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2800{
2801 Vector <VolumeInterface *> volumeInterfaces;
2802 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002803 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002804 }
2805 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2806 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002807 MmapPlaybackThread *mmapPlaybackThread =
2808 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2809 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002810 }
2811 }
2812 return volumeInterfaces;
2813}
2814
Glenn Kasteneeecb982016-02-26 10:44:04 -08002815audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816{
Glenn Kasten9d003132016-04-06 14:38:09 -07002817 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002818 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002819 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2820 for (int retry = 0; retry < maxRetries; retry++) {
2821 // The cast allows wraparound from max positive to min negative instead of abort
2822 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2823 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2824 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2825 // allow wrap by skipping 0 and -1 for session ids
2826 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2827 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2828 return (audio_unique_id_t) (base | use);
2829 }
2830 }
2831 // We have no way of recovering from wraparound
2832 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2833 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834}
2835
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002836AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002837{
2838 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2839 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002840 if(thread->isDuplicating()) {
2841 continue;
2842 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002843 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002844 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002845 return thread;
2846 }
2847 }
2848 return NULL;
2849}
2850
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002851audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002852{
2853 PlaybackThread *thread = primaryPlaybackThread_l();
2854
2855 if (thread == NULL) {
2856 return 0;
2857 }
2858
Eric Laurentf1c04f92012-08-28 14:26:53 -07002859 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002860}
2861
Glenn Kastena7335632016-06-09 17:09:53 -07002862AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2863{
2864 size_t minFrameCount = 0;
2865 PlaybackThread *minThread = NULL;
2866 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2867 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2868 if (!thread->isDuplicating()) {
2869 size_t frameCount = thread->frameCountHAL();
2870 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2871 (frameCount == minFrameCount && thread->hasFastMixer() &&
2872 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2873 minFrameCount = frameCount;
2874 minThread = thread;
2875 }
2876 }
2877 }
2878 return minThread;
2879}
2880
Eric Laurenta011e352012-03-29 15:51:43 -07002881sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002882 audio_session_t triggerSession,
2883 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002884 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002885 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002886{
2887 Mutex::Autolock _l(mLock);
2888
2889 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2890 status_t playStatus = NAME_NOT_FOUND;
2891 status_t recStatus = NAME_NOT_FOUND;
2892 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2893 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2894 if (playStatus == NO_ERROR) {
2895 return event;
2896 }
2897 }
2898 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2899 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2900 if (recStatus == NO_ERROR) {
2901 return event;
2902 }
2903 }
2904 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2905 mPendingSyncEvents.add(event);
2906 } else {
2907 ALOGV("createSyncEvent() invalid event %d", event->type());
2908 event.clear();
2909 }
2910 return event;
2911}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002912
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913// ----------------------------------------------------------------------------
2914// Effect management
2915// ----------------------------------------------------------------------------
2916
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002917sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2918 return mEffectsFactoryHal;
2919}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920
Glenn Kastenf587ba52012-01-26 16:25:10 -08002921status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922{
2923 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002924 if (mEffectsFactoryHal.get()) {
2925 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2926 } else {
2927 return -ENODEV;
2928 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929}
2930
Glenn Kastenf587ba52012-01-26 16:25:10 -08002931status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932{
2933 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002934 if (mEffectsFactoryHal.get()) {
2935 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2936 } else {
2937 return -ENODEV;
2938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939}
2940
Glenn Kasten5e92a782012-01-30 07:40:52 -08002941status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002942 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943{
2944 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002945 if (mEffectsFactoryHal.get()) {
2946 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2947 } else {
2948 return -ENODEV;
2949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950}
2951
2952
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002953sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 effect_descriptor_t *pDesc,
2955 const sp<IEffectClient>& effectClient,
2956 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002957 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002958 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002959 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002960 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961 status_t *status,
2962 int *id,
2963 int *enabled)
2964{
2965 status_t lStatus = NO_ERROR;
2966 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968
Eric Laurentb6436272016-12-07 19:24:50 -08002969 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2970 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2971 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2972 ALOGW_IF(pid != -1 && pid != callingPid,
2973 "%s uid %d pid %d tried to pass itself off as pid %d",
2974 __func__, callingUid, callingPid, pid);
2975 pid = callingPid;
2976 }
2977
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002978 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2979 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980
2981 if (pDesc == NULL) {
2982 lStatus = BAD_VALUE;
2983 goto Exit;
2984 }
2985
Eric Laurent84e9a102010-09-23 16:10:16 -07002986 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002987 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002988 lStatus = PERMISSION_DENIED;
2989 goto Exit;
2990 }
2991
Dima Zavinfce7a472011-04-19 22:30:36 -07002992 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002993 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002994 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002995 lStatus = PERMISSION_DENIED;
2996 goto Exit;
2997 }
2998
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002999 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003000 lStatus = NO_INIT;
3001 goto Exit;
3002 }
3003
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003005 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003007 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003009 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010 goto Exit;
3011 }
3012 } else {
3013 // if uuid is not specified, look for an available implementation
3014 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003015 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003016 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017 lStatus = BAD_VALUE;
3018 goto Exit;
3019 }
3020 uint32_t numEffects = 0;
3021 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003022 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 bool found = false;
3024
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003025 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003027 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028 goto Exit;
3029 }
3030 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003031 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003033 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034 continue;
3035 }
3036 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3037 // If matching type found save effect descriptor. If the session is
3038 // 0 and the effect is not auxiliary, continue enumeration in case
3039 // an auxiliary version of this effect type is available
3040 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003041 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003042 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3044 break;
3045 }
3046 }
3047 }
3048 if (!found) {
3049 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003050 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 goto Exit;
3052 }
3053 // For same effect type, chose auxiliary version over insert version if
3054 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003055 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003057 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 }
3059 }
3060
3061 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003062 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3064 lStatus = INVALID_OPERATION;
3065 goto Exit;
3066 }
3067
Eric Laurent59255e42011-07-27 19:49:51 -07003068 // check recording permission for visualizer
3069 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07003070 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003071 lStatus = PERMISSION_DENIED;
3072 goto Exit;
3073 }
3074
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003076 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003077 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003078 // if the output returned by getOutputForEffect() is removed before we lock the
3079 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3080 // and we will exit safely
3081 io = AudioSystem::getOutputForEffect(&desc);
3082 ALOGV("createEffect got output %d", io);
3083 }
3084
3085 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086
3087 // If output is not specified try to find a matching audio session ID in one of the
3088 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003089 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3090 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003091 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003092 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003093 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3094 // output must be specified by AudioPolicyManager when using session
3095 // AUDIO_SESSION_OUTPUT_STAGE
3096 lStatus = BAD_VALUE;
3097 goto Exit;
3098 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003099 // look for the thread where the specified audio session is present
3100 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3101 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3102 io = mPlaybackThreads.keyAt(i);
3103 break;
3104 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003106 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003107 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3108 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3109 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003110 break;
3111 }
3112 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003113 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003114 if (io == AUDIO_IO_HANDLE_NONE) {
3115 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3116 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3117 io = mMmapThreads.keyAt(i);
3118 break;
3119 }
3120 }
3121 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003122 // If no output thread contains the requested session ID, default to
3123 // first output. The effect chain will be moved to the correct output
3124 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003125 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003126 io = mPlaybackThreads.keyAt(0);
3127 }
Steve Block3856b092011-10-20 11:56:00 +01003128 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003129 }
3130 ThreadBase *thread = checkRecordThread_l(io);
3131 if (thread == NULL) {
3132 thread = checkPlaybackThread_l(io);
3133 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003134 thread = checkMmapThread_l(io);
3135 if (thread == NULL) {
3136 ALOGE("createEffect() unknown output thread");
3137 lStatus = BAD_VALUE;
3138 goto Exit;
3139 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003140 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003141 } else {
3142 // Check if one effect chain was awaiting for an effect to be created on this
3143 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003144 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003145 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003146 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003147 thread->addEffectChain_l(chain);
3148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003150
Eric Laurent021cf962014-05-13 10:18:14 -07003151 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003153 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003154 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003155 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003156 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 if (handle != 0 && id != NULL) {
3158 *id = handle->id();
3159 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003160 if (handle == 0) {
3161 // remove local strong reference to Client with mClientLock held
3162 Mutex::Autolock _cl(mClientLock);
3163 client.clear();
3164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 }
3166
3167Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003168 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 return handle;
3170}
3171
Glenn Kastend848eb42016-03-08 13:42:11 -08003172status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003173 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003174{
Steve Block3856b092011-10-20 11:56:00 +01003175 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003176 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003177 Mutex::Autolock _l(mLock);
3178 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003179 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003180 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 }
Eric Laurentde070132010-07-13 04:45:46 -07003182 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3183 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003184 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003185 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 }
Eric Laurentde070132010-07-13 04:45:46 -07003187 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3188 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003189 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003190 return BAD_VALUE;
3191 }
3192
3193 Mutex::Autolock _dl(dstThread->mLock);
3194 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003195 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196}
3197
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003198// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003199status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003200 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003201 AudioFlinger::PlaybackThread *dstThread,
3202 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003203{
Steve Block3856b092011-10-20 11:56:00 +01003204 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003205 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003206
Eric Laurent59255e42011-07-27 19:49:51 -07003207 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003208 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003209 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003210 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003211 return INVALID_OPERATION;
3212 }
3213
Eric Laurent4c415062016-06-17 16:14:16 -07003214 // Check whether the destination thread and all effects in the chain are compatible
3215 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003216 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003217 " destination thread %p is not compatible with effects in the chain",
3218 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003219 return INVALID_OPERATION;
3220 }
3221
Eric Laurent39e94f82010-07-28 01:32:47 -07003222 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003223 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003224 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003225 // removed.
3226 srcThread->removeEffectChain_l(chain);
3227
3228 // transfer all effects one by one so that new effect chain is created on new thread with
3229 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003230 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003231 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003232 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003233 Vector< sp<EffectModule> > removed;
3234 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003235 while (effect != 0) {
3236 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003237 removed.add(effect);
3238 status = dstThread->addEffect_l(effect);
3239 if (status != NO_ERROR) {
3240 break;
3241 }
Eric Laurentec35a142011-10-05 17:42:25 -07003242 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3243 if (effect->state() == EffectModule::ACTIVE ||
3244 effect->state() == EffectModule::STOPPING) {
3245 effect->start();
3246 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003247 // if the move request is not received from audio policy manager, the effect must be
3248 // re-registered with the new strategy and output
3249 if (dstChain == 0) {
3250 dstChain = effect->chain().promote();
3251 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003252 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003253 status = NO_INIT;
3254 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003255 }
3256 strategy = dstChain->strategy();
3257 }
3258 if (reRegister) {
3259 AudioSystem::unregisterEffect(effect->id());
3260 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003261 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003262 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003263 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003264 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003265 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003266 }
Eric Laurentde070132010-07-13 04:45:46 -07003267 effect = chain->getEffectFromId_l(0);
3268 }
3269
Eric Laurent5baf2af2013-09-12 17:37:00 -07003270 if (status != NO_ERROR) {
3271 for (size_t i = 0; i < removed.size(); i++) {
3272 srcThread->addEffect_l(removed[i]);
3273 if (dstChain != 0 && reRegister) {
3274 AudioSystem::unregisterEffect(removed[i]->id());
3275 AudioSystem::registerEffect(&removed[i]->desc(),
3276 srcThread->id(),
3277 strategy,
3278 sessionId,
3279 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003280 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003281 }
3282 }
3283 }
3284
3285 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286}
3287
Eric Laurent5baf2af2013-09-12 17:37:00 -07003288bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003289{
3290 if (mGlobalEffectEnableTime != 0 &&
3291 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3292 return true;
3293 }
3294
3295 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3296 sp<EffectChain> ec =
3297 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003298 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003299 return true;
3300 }
3301 }
3302 return false;
3303}
3304
Eric Laurent5baf2af2013-09-12 17:37:00 -07003305void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003306{
3307 Mutex::Autolock _l(mLock);
3308
3309 mGlobalEffectEnableTime = systemTime();
3310
3311 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3312 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3313 if (t->mType == ThreadBase::OFFLOAD) {
3314 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3315 }
3316 }
3317
3318}
3319
Eric Laurentaaa44472014-09-12 17:41:50 -07003320status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3321{
Eric Laurentd8365c52017-07-16 15:27:05 -07003322 // clear possible suspended state before parking the chain so that it starts in default state
3323 // when attached to a new record thread
3324 chain->setEffectSuspended_l(FX_IID_AEC, false);
3325 chain->setEffectSuspended_l(FX_IID_NS, false);
3326
Glenn Kastend848eb42016-03-08 13:42:11 -08003327 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003328 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003329 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003330 if (index >= 0) {
3331 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3332 return ALREADY_EXISTS;
3333 }
3334 mOrphanEffectChains.add(session, chain);
3335 return NO_ERROR;
3336}
3337
3338sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3339{
3340 sp<EffectChain> chain;
3341 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003342 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003343 if (index >= 0) {
3344 chain = mOrphanEffectChains.valueAt(index);
3345 mOrphanEffectChains.removeItemsAt(index);
3346 }
3347 return chain;
3348}
3349
3350bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3351{
3352 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003353 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003354 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003355 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003356 if (index >= 0) {
3357 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003358 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003359 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003360 mOrphanEffectChains.removeItemsAt(index);
3361 }
3362 return true;
3363 }
3364 return false;
3365}
3366
3367
Glenn Kastenda6ef132013-01-10 12:31:01 -08003368struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003369#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3370 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003371};
3372
3373int comparEntry(const void *p1, const void *p2)
3374{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003375 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003376}
3377
Glenn Kasten46909e72013-02-26 09:20:22 -08003378#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003379void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380{
Eric Laurent81784c32012-11-19 14:55:58 -08003381 NBAIO_Source *teeSource = source.get();
3382 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003383 // .wav rotation
3384 // There is a benign race condition if 2 threads call this simultaneously.
3385 // They would both traverse the directory, but the result would simply be
3386 // failures at unlink() which are ignored. It's also unlikely since
3387 // normally dumpsys is only done by bugreport or from the command line.
3388 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003389 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003390 size_t teePathLen = strlen(teePath);
3391 DIR *dir = opendir(teePath);
3392 teePath[teePathLen++] = '/';
3393 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003394#define TEE_MAX_SORT 20 // number of entries to sort
3395#define TEE_MAX_KEEP 10 // number of entries to keep
3396 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003397 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003398 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003399 struct dirent de;
3400 struct dirent *result = NULL;
3401 int rc = readdir_r(dir, &de, &result);
3402 if (rc != 0) {
3403 ALOGW("readdir_r failed %d", rc);
3404 break;
3405 }
3406 if (result == NULL) {
3407 break;
3408 }
3409 if (result != &de) {
3410 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3411 break;
3412 }
3413 // ignore non .wav file entries
3414 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003415 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003416 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3417 continue;
3418 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003419 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003420 }
3421 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003422 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003423 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003424 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3425 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003426 (void) unlink(teePath);
3427 }
3428 }
3429 } else {
3430 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003431 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003432 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003433 }
3434 }
Eric Laurent81784c32012-11-19 14:55:58 -08003435 char teeTime[16];
3436 struct timeval tv;
3437 gettimeofday(&tv, NULL);
3438 struct tm tm;
3439 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003440 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003441 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3442 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003443 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3444 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003445 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003446 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003447 char wavHeader[44];
3448 memcpy(wavHeader,
3449 "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",
3450 sizeof(wavHeader));
3451 NBAIO_Format format = teeSource->format();
3452 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003453 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003454 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003455 wavHeader[22] = channelCount; // number of channels
3456 wavHeader[24] = sampleRate; // sample rate
3457 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003458 wavHeader[32] = frameSize; // block alignment
3459 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003460 write(teeFd, wavHeader, sizeof(wavHeader));
3461 size_t total = 0;
3462 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003463#define TEE_SINK_READ 1024 // frames per I/O operation
3464 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003465 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003466 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003467 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003468 bool wasFirstRead = firstRead;
3469 firstRead = false;
3470 if (actual <= 0) {
3471 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3472 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003473 }
Eric Laurent81784c32012-11-19 14:55:58 -08003474 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003475 }
Eric Laurent81784c32012-11-19 14:55:58 -08003476 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003477 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003478 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003479 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003480 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003481 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003482 uint32_t temp = 44 + total * frameSize - 8;
3483 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003484 write(teeFd, &temp, sizeof(temp));
3485 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003486 temp = total * frameSize;
3487 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003488 write(teeFd, &temp, sizeof(temp));
3489 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003490 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003491 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003492 }
Eric Laurent59255e42011-07-27 19:49:51 -07003493 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003494 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003495 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003496 }
Eric Laurent59255e42011-07-27 19:49:51 -07003497 }
3498 }
3499}
Glenn Kasten46909e72013-02-26 09:20:22 -08003500#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003501
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502// ----------------------------------------------------------------------------
3503
3504status_t AudioFlinger::onTransact(
3505 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3506{
3507 return BnAudioFlinger::onTransact(code, data, reply, flags);
3508}
3509
Glenn Kasten63238ef2015-03-02 15:50:29 -08003510} // namespace android