blob: f28132de3d0efe0786c11f30ef4b168fb4ae90dd [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
Eric Laurentf1047e82018-04-16 19:18:20 -070031#include <cutils/multiuser.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070033#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070035#include <media/audiohal/DeviceHalInterface.h>
36#include <media/audiohal/DevicesFactoryHalInterface.h>
37#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070038#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070040#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <utils/String16.h>
42#include <utils/threads.h>
43
Steven Morelandf0c02ce2018-02-23 14:53:55 -080044#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_visualizer.h>
55#include <system/audio_effects/effect_ns.h>
56#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten9e58b552013-01-18 15:09:48 -080062#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070063#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080064#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070066#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
rago3bd1c872016-09-26 12:58:14 -070070//#define BUFLOG_NDEBUG 0
71#include <BufLog.h>
72
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080073#include "TypedLogger.h"
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
John Grossman1c345192012-03-27 14:00:17 -070077// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
Eric Laurentde070132010-07-13 04:45:46 -070089
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Glenn Kastenec1d6b52011-12-12 09:04:45 -080092static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
93static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070094static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070095static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070096
Glenn Kasten58912562012-04-03 10:45:00 -070097
John Grossman4ff14ba2012-02-08 16:37:41 -080098nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700101
Eric Laurentfc235202016-12-20 18:48:17 -0800102
Glenn Kasten46909e72013-02-26 09:20:22 -0800103#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800104bool AudioFlinger::mTeeSinkInputEnabled = false;
105bool AudioFlinger::mTeeSinkOutputEnabled = false;
106bool AudioFlinger::mTeeSinkTrackEnabled = false;
107
108size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
109size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
110size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800111#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800112
Eric Laurent813e2a72013-08-31 12:59:48 -0700113// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
114// we define a minimum time during which a global effect is considered enabled.
115static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
116
Eric Laurentfc235202016-12-20 18:48:17 -0800117Mutex gLock;
118wp<AudioFlinger> gAudioFlinger;
119
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700120// Keep a strong reference to media.log service around forever.
121// The service is within our parent process so it can never die in a way that we could observe.
122// These two variables are const after initialization.
123static sp<IBinder> sMediaLogServiceAsBinder;
124static sp<IMediaLogService> sMediaLogService;
125
126static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
127
128static void sMediaLogInit()
129{
130 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
131 if (sMediaLogServiceAsBinder != 0) {
132 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
133 }
134}
135
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136// ----------------------------------------------------------------------------
137
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700138std::string formatToString(audio_format_t format) {
139 std::string result;
140 FormatConverter::toString(format, result);
141 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800142}
143
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144// ----------------------------------------------------------------------------
145
146AudioFlinger::AudioFlinger()
147 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800148 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800149 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800150 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700151 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800152 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700154 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800155 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700156 mBtNrecIsOff(false),
157 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700158 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800159 mTotalMemory(0),
160 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700161 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700162 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700163 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700164{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700165 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
166 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
167 // zero ID has a special meaning, so unavailable
168 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
169 }
170
Glenn Kasten949a9262013-04-16 12:35:20 -0700171 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800172 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800173 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800174 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
175 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700176 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800177 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700178
Wei Jia3f273d12015-11-24 09:06:49 -0800179 // reset battery stats.
180 // if the audio service has crashed, battery stats could be left
181 // in bad state, reset the state upon service start.
182 BatteryNotifier::getInstance().noteResetAudio();
183
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700184 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700185 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
186
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800187 mMediaLogNotifier->run("MediaLogNotifier");
188
Glenn Kasten46909e72013-02-26 09:20:22 -0800189#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800190 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800191 (void) property_get("ro.debuggable", value, "0");
192 int debuggable = atoi(value);
193 int teeEnabled = 0;
194 if (debuggable) {
195 (void) property_get("af.tee", value, "0");
196 teeEnabled = atoi(value);
197 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800198 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700199 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700201 }
202 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800203 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700204 }
205 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800206 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700207 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800208#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700209}
210
211void AudioFlinger::onFirstRef()
212{
Eric Laurent93575202011-01-18 18:39:02 -0800213 Mutex::Autolock _l(mLock);
214
Dima Zavin799a70e2011-04-18 16:57:27 -0700215 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 char val_str[PROPERTY_VALUE_MAX] = { 0 };
217 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
218 uint32_t int_val;
219 if (1 == sscanf(val_str, "%u", &int_val)) {
220 mStandbyTimeInNsecs = milliseconds(int_val);
221 ALOGI("Using %u mSec as standby time.", int_val);
222 } else {
223 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
224 ALOGI("Using default %u mSec as standby time.",
225 (uint32_t)(mStandbyTimeInNsecs / 1000000));
226 }
227 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228
Eric Laurenta4c5a552012-03-29 10:12:40 -0700229 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800230
231 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232}
233
234AudioFlinger::~AudioFlinger()
235{
236 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700237 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700238 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239 }
240 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700241 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700242 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700244
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800245 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
246 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700247 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700249
250 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700251 if (sMediaLogService != 0) {
252 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
253 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
254 mUnregisteredWriters.pop();
255 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700256 }
257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258}
259
Eric Laurentfc235202016-12-20 18:48:17 -0800260//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800261__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800262status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
263 const audio_attributes_t *attr,
264 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700265 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800266 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800267 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800268 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700269 sp<MmapStreamInterface>& interface,
270 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800271{
272 sp<AudioFlinger> af;
273 {
274 Mutex::Autolock _l(gLock);
275 af = gAudioFlinger.promote();
276 }
277 status_t ret = NO_INIT;
278 if (af != 0) {
279 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800280 direction, attr, config, client, deviceId,
281 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800282 }
283 return ret;
284}
285
Eric Laurent6acd1d42017-01-04 14:23:29 -0800286status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
287 const audio_attributes_t *attr,
288 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700289 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800290 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800291 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800292 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700293 sp<MmapStreamInterface>& interface,
294 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800295{
296 status_t ret = initCheck();
297 if (ret != NO_ERROR) {
298 return ret;
299 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800300 audio_session_t actualSessionId = *sessionId;
301 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
302 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
303 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800304 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700305 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800306 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
307 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
308 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
309 fullConfig.sample_rate = config->sample_rate;
310 fullConfig.channel_mask = config->channel_mask;
311 fullConfig.format = config->format;
312 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800313 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200314 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800315 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800316 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
317 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700318 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800319 } else {
320 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800321 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800322 client.clientPid,
323 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800324 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800325 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700326 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800327 }
328 if (ret != NO_ERROR) {
329 return ret;
330 }
331
332 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
333 // audio policy manager and we can retrieve it
334 sp<MmapThread> thread = mMmapThreads.valueFor(io);
335 if (thread != 0) {
336 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800337 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700338 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800339 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800340 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700341 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800342 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700343 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800344 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700345 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800346 ret = NO_INIT;
347 }
348
349 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
350
Eric Laurentfc235202016-12-20 18:48:17 -0800351 return ret;
352}
353
Eric Laurenta4c5a552012-03-29 10:12:40 -0700354static const char * const audio_interfaces[] = {
355 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
356 AUDIO_HARDWARE_MODULE_ID_A2DP,
357 AUDIO_HARDWARE_MODULE_ID_USB,
358};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700359
Phil Burk062e67a2015-02-11 13:40:50 -0800360AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700361 audio_module_handle_t module,
362 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700363{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700364 // if module is 0, the request comes from an old policy manager and we should load
365 // well known modules
366 if (module == 0) {
367 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700368 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700369 loadHwModule_l(audio_interfaces[i]);
370 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700371 // then try to find a module supporting the requested device.
372 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
373 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700374 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
375 uint32_t supportedDevices;
376 if (dev->getSupportedDevices(&supportedDevices) == OK &&
377 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700378 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700379 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700380 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700381 } else {
382 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700383 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
384 if (audioHwDevice != NULL) {
385 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700386 }
387 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700388
Dima Zavin799a70e2011-04-18 16:57:27 -0700389 return NULL;
390}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700391
Glenn Kasten0f11b512014-01-31 16:18:54 -0800392void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393{
394 const size_t SIZE = 256;
395 char buffer[SIZE];
396 String8 result;
397
398 result.append("Clients:\n");
399 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800400 sp<Client> client = mClients.valueAt(i).promote();
401 if (client != 0) {
402 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
403 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 }
405 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700406
Eric Laurentd1b28d42013-09-18 18:47:13 -0700407 result.append("Notification Clients:\n");
408 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
409 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
410 result.append(buffer);
411 }
412
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700413 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800414 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700415 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
416 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800417 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700418 result.append(buffer);
419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421}
422
423
Glenn Kasten0f11b512014-01-31 16:18:54 -0800424void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425{
426 const size_t SIZE = 256;
427 char buffer[SIZE];
428 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800429 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700430
John Grossman4ff14ba2012-02-08 16:37:41 -0800431 snprintf(buffer, SIZE, "Hardware status: %d\n"
432 "Standby Time mSec: %u\n",
433 hardwareStatus,
434 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 result.append(buffer);
436 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437}
438
Glenn Kasten0f11b512014-01-31 16:18:54 -0800439void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440{
441 const size_t SIZE = 256;
442 char buffer[SIZE];
443 String8 result;
444 snprintf(buffer, SIZE, "Permission Denial: "
445 "can't dump AudioFlinger from pid=%d, uid=%d\n",
446 IPCThreadState::self()->getCallingPid(),
447 IPCThreadState::self()->getCallingUid());
448 result.append(buffer);
449 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450}
451
Eric Laurent81784c32012-11-19 14:55:58 -0800452bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453{
454 bool locked = false;
455 for (int i = 0; i < kDumpLockRetries; ++i) {
456 if (mutex.tryLock() == NO_ERROR) {
457 locked = true;
458 break;
459 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800460 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 }
462 return locked;
463}
464
465status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
466{
Glenn Kasten44deb052012-02-05 18:09:08 -0800467 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468 dumpPermissionDenial(fd, args);
469 } else {
470 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800471 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 if (!hardwareLocked) {
473 String8 result(kHardwareLockedString);
474 write(fd, result.string(), result.size());
475 } else {
476 mHardwareLock.unlock();
477 }
478
Eric Laurent81784c32012-11-19 14:55:58 -0800479 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480
481 // failed to lock - AudioFlinger is probably deadlocked
482 if (!locked) {
483 String8 result(kDeadlockedString);
484 write(fd, result.string(), result.size());
485 }
486
Eric Laurent021cf962014-05-13 10:18:14 -0700487 bool clientLocked = dumpTryLock(mClientLock);
488 if (!clientLocked) {
489 String8 result(kClientLockedString);
490 write(fd, result.string(), result.size());
491 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700492
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700493 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700494 mEffectsFactoryHal->dumpEffects(fd);
495 } else {
496 String8 result(kNoEffectsFactory);
497 write(fd, result.string(), result.size());
498 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700499
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700501 if (clientLocked) {
502 mClientLock.unlock();
503 }
504
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505 dumpInternals(fd, args);
506
507 // dump playback threads
508 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
509 mPlaybackThreads.valueAt(i)->dump(fd, args);
510 }
511
512 // dump record threads
513 for (size_t i = 0; i < mRecordThreads.size(); i++) {
514 mRecordThreads.valueAt(i)->dump(fd, args);
515 }
516
Eric Laurent6acd1d42017-01-04 14:23:29 -0800517 // dump mmap threads
518 for (size_t i = 0; i < mMmapThreads.size(); i++) {
519 mMmapThreads.valueAt(i)->dump(fd, args);
520 }
521
Eric Laurentaaa44472014-09-12 17:41:50 -0700522 // dump orphan effect chains
523 if (mOrphanEffectChains.size() != 0) {
524 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
525 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
526 mOrphanEffectChains.valueAt(i)->dump(fd, args);
527 }
528 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700529 // dump all hardware devs
530 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700531 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
532 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700534
Glenn Kasten46909e72013-02-26 09:20:22 -0800535#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700536 // dump the serially shared record tee sink
537 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700538 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700539 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800540#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700541
rago3bd1c872016-09-26 12:58:14 -0700542 BUFLOG_RESET;
543
Glenn Kastend65d73c2012-06-22 17:21:07 -0700544 if (locked) {
545 mLock.unlock();
546 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800547
548 // append a copy of media.log here by forwarding fd to it, but don't attempt
549 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700550 if (sMediaLogServiceAsBinder != 0) {
551 dprintf(fd, "\nmedia.log:\n");
552 Vector<String16> args;
553 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800554 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700555
556 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700557 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700558 bool unreachableMemory = false;
559 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700560 if (arg == String16("-m")) {
561 dumpMem = true;
562 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700563 unreachableMemory = true;
564 }
565 }
566
Andy Hung07b745e2016-05-23 16:21:07 -0700567 if (dumpMem) {
568 dprintf(fd, "\nDumping memory:\n");
569 std::string s = dumpMemoryAddresses(100 /* limit */);
570 write(fd, s.c_str(), s.size());
571 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700572 if (unreachableMemory) {
573 dprintf(fd, "\nDumping unreachable memory:\n");
574 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700575 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700576 write(fd, s.c_str(), s.size());
577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 }
579 return NO_ERROR;
580}
581
Eric Laurent021cf962014-05-13 10:18:14 -0700582sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800583{
Eric Laurent021cf962014-05-13 10:18:14 -0700584 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800585 // If pid is already in the mClients wp<> map, then use that entry
586 // (for which promote() is always != 0), otherwise create a new entry and Client.
587 sp<Client> client = mClients.valueFor(pid).promote();
588 if (client == 0) {
589 client = new Client(this, pid);
590 mClients.add(pid, client);
591 }
592
593 return client;
594}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595
Glenn Kasten9e58b552013-01-18 15:09:48 -0800596sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
597{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700598 // If there is no memory allocated for logs, return a dummy writer that does nothing.
599 // Similarly if we can't contact the media.log service, also return a dummy writer.
600 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800601 return new NBLog::Writer();
602 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700603 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
604 // If allocation fails, consult the vector of previously unregistered writers
605 // and garbage-collect one or more them until an allocation succeeds
606 if (shared == 0) {
607 Mutex::Autolock _l(mUnregisteredWritersLock);
608 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
609 {
610 // Pick the oldest stale writer to garbage-collect
611 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
612 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700613 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700614 // Now the media.log remote reference to IMemory is gone. When our last local
615 // reference to IMemory also drops to zero at end of this block,
616 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
617 }
618 // Re-attempt the allocation
619 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
620 if (shared != 0) {
621 goto success;
622 }
623 }
624 // Even after garbage-collecting all old writers, there is still not enough memory,
625 // so return a dummy writer
626 return new NBLog::Writer();
627 }
628success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800629 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
630 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
631 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700632 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800633 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800634}
635
636void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
637{
Glenn Kasten685ef092013-02-04 08:15:34 -0800638 if (writer == 0) {
639 return;
640 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800641 sp<IMemory> iMemory(writer->getIMemory());
642 if (iMemory == 0) {
643 return;
644 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700645 // Rather than removing the writer immediately, append it to a queue of old writers to
646 // be garbage-collected later. This allows us to continue to view old logs for a while.
647 Mutex::Autolock _l(mUnregisteredWritersLock);
648 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800649}
650
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651// IAudioFlinger interface
652
Eric Laurent21da6472017-11-09 16:29:26 -0800653sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
654 CreateTrackOutput& output,
655 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656{
657 sp<PlaybackThread::Track> track;
658 sp<TrackHandle> trackHandle;
659 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800661 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800662 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663
Eric Laurent21da6472017-11-09 16:29:26 -0800664 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700665 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800666 uid_t clientUid = input.clientInfo.clientUid;
667 if (!isTrustedCallingUid(callingUid)) {
668 ALOGW_IF(clientUid != callingUid,
669 "%s uid %d tried to pass itself off as %d",
670 __FUNCTION__, callingUid, clientUid);
671 clientUid = callingUid;
672 updatePid = true;
673 }
674 pid_t clientPid = input.clientInfo.clientPid;
675 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700676 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800677 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700678 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800679 __func__, callingUid, callingPid, clientPid);
680 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700681 }
682
Eric Laurent21da6472017-11-09 16:29:26 -0800683 audio_session_t sessionId = input.sessionId;
684 if (sessionId == AUDIO_SESSION_ALLOCATE) {
685 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800686 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
687 lStatus = BAD_VALUE;
688 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800689 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800690
Eric Laurent21da6472017-11-09 16:29:26 -0800691 output.sessionId = sessionId;
692 output.outputId = AUDIO_IO_HANDLE_NONE;
693 output.selectedDeviceId = input.selectedDeviceId;
694
695 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200696 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800697 &output.selectedDeviceId, &portId);
698
699 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
700 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
701 goto Exit;
702 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800703 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
704 // but if someone uses binder directly they could bypass that and cause us to crash
705 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000706 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 lStatus = BAD_VALUE;
708 goto Exit;
709 }
710
Glenn Kasten53b5d092014-02-05 10:00:23 -0800711 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800712 if (!audio_is_output_channel(input.config.channel_mask)) {
713 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800714 lStatus = BAD_VALUE;
715 goto Exit;
716 }
717
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700718 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800719 if (!audio_is_valid_format(input.config.format)) {
720 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700721 lStatus = BAD_VALUE;
722 goto Exit;
723 }
724
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 {
726 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800727 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800729 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 lStatus = BAD_VALUE;
731 goto Exit;
732 }
733
Eric Laurent21da6472017-11-09 16:29:26 -0800734 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735
Glenn Kastene848bd92014-03-13 15:00:32 -0700736 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800737 // check if an effect chain with the same session ID is present on another
738 // output thread and move it here.
739 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
740 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
741 if (mPlaybackThreads.keyAt(i) != output.outputId) {
742 uint32_t sessions = t->hasAudioSession(sessionId);
743 if (sessions & ThreadBase::EFFECT_SESSION) {
744 effectThread = t.get();
745 break;
Eric Laurentde070132010-07-13 04:45:46 -0700746 }
747 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 }
Eric Laurent21da6472017-11-09 16:29:26 -0800749 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750
Eric Laurent21da6472017-11-09 16:29:26 -0800751 output.sampleRate = input.config.sample_rate;
752 output.frameCount = input.frameCount;
753 output.notificationFrameCount = input.notificationFrameCount;
754 output.flags = input.flags;
755
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700756 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
757 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800758 &output.frameCount, &output.notificationFrameCount,
759 input.notificationsPerBuffer, input.speed,
760 input.sharedBuffer, sessionId, &output.flags,
761 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800762 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700763 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700764
Eric Laurent21da6472017-11-09 16:29:26 -0800765 output.afFrameCount = thread->frameCount();
766 output.afSampleRate = thread->sampleRate();
767 output.afLatencyMs = thread->latency();
768
Eric Laurent39e94f82010-07-28 01:32:47 -0700769 // move effect chain to this output thread if an effect on same session was waiting
770 // for a track to be created
771 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700772 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700773 Mutex::Autolock _dl(thread->mLock);
774 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800775 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700776 }
Eric Laurenta011e352012-03-29 15:51:43 -0700777
778 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700779 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800780 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700781 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700782 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700783 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700784 } else {
785 mPendingSyncEvents[i]->cancel();
786 }
Eric Laurenta011e352012-03-29 15:51:43 -0700787 mPendingSyncEvents.removeAt(i);
788 i--;
789 }
790 }
791 }
Glenn Kastene198c362013-08-13 09:13:36 -0700792
Eric Laurent21da6472017-11-09 16:29:26 -0800793 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 }
Glenn Kastene198c362013-08-13 09:13:36 -0700795
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700796 if (lStatus != NO_ERROR) {
797 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700798 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700799 // Don't hold mClientLock when releasing the reference on the track as the
800 // destructor will acquire it.
801 {
802 Mutex::Autolock _cl(mClientLock);
803 client.clear();
804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700806 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 }
808
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700809 // return handle to client
810 trackHandle = new TrackHandle(track);
811
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800813 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
814 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
815 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700816 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return trackHandle;
818}
819
Glenn Kasten2c073da2016-02-26 09:14:08 -0800820uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821{
822 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800823 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800825 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 return 0;
827 }
828 return thread->sampleRate();
829}
830
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800831audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832{
833 Mutex::Autolock _l(mLock);
834 PlaybackThread *thread = checkPlaybackThread_l(output);
835 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000836 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800837 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 }
839 return thread->format();
840}
841
Glenn Kasten2c073da2016-02-26 09:14:08 -0800842size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843{
844 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800845 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800847 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 return 0;
849 }
Glenn Kasten58912562012-04-03 10:45:00 -0700850 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
851 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 return thread->frameCount();
853}
854
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700855size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
856{
857 Mutex::Autolock _l(mLock);
858 ThreadBase *thread = checkThread_l(ioHandle);
859 if (thread == NULL) {
860 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
861 return 0;
862 }
863 return thread->frameCountHAL();
864}
865
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800866uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867{
868 Mutex::Autolock _l(mLock);
869 PlaybackThread *thread = checkPlaybackThread_l(output);
870 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800871 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 return 0;
873 }
874 return thread->latency();
875}
876
877status_t AudioFlinger::setMasterVolume(float value)
878{
Eric Laurenta1884f92011-08-23 08:25:03 -0700879 status_t ret = initCheck();
880 if (ret != NO_ERROR) {
881 return ret;
882 }
883
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 // check calling permissions
885 if (!settingsAllowed()) {
886 return PERMISSION_DENIED;
887 }
888
Eric Laurenta4c5a552012-03-29 10:12:40 -0700889 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700890 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700891
John Grossmanee578c02012-07-23 17:05:46 -0700892 // Set master volume in the HALs which support it.
893 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
894 AutoMutex lock(mHardwareLock);
895 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800896
John Grossmanee578c02012-07-23 17:05:46 -0700897 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
898 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700899 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800900 }
John Grossmanee578c02012-07-23 17:05:46 -0700901 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903
John Grossmanee578c02012-07-23 17:05:46 -0700904 // Now set the master volume in each playback thread. Playback threads
905 // assigned to HALs which do not have master volume support will apply
906 // master volume during the mix operation. Threads with HALs which do
907 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700908 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
909 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
910 continue;
911 }
John Grossmanee578c02012-07-23 17:05:46 -0700912 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914
915 return NO_ERROR;
916}
917
Glenn Kastenf78aee72012-01-04 11:00:47 -0800918status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919{
Eric Laurenta1884f92011-08-23 08:25:03 -0700920 status_t ret = initCheck();
921 if (ret != NO_ERROR) {
922 return ret;
923 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924
925 // check calling permissions
926 if (!settingsAllowed()) {
927 return PERMISSION_DENIED;
928 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800929 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000930 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 return BAD_VALUE;
932 }
933
934 { // scope for the lock
935 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700936 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700938 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 mHardwareStatus = AUDIO_HW_IDLE;
940 }
941
942 if (NO_ERROR == ret) {
943 Mutex::Autolock _l(mLock);
944 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800945 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700946 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 }
948
949 return ret;
950}
951
952status_t AudioFlinger::setMicMute(bool state)
953{
Eric Laurenta1884f92011-08-23 08:25:03 -0700954 status_t ret = initCheck();
955 if (ret != NO_ERROR) {
956 return ret;
957 }
958
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959 // check calling permissions
960 if (!settingsAllowed()) {
961 return PERMISSION_DENIED;
962 }
963
964 AutoMutex lock(mHardwareLock);
965 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700966 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700967 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
968 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700969 if (result != NO_ERROR) {
970 ret = result;
971 }
972 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973 mHardwareStatus = AUDIO_HW_IDLE;
974 return ret;
975}
976
977bool AudioFlinger::getMicMute() const
978{
Eric Laurenta1884f92011-08-23 08:25:03 -0700979 status_t ret = initCheck();
980 if (ret != NO_ERROR) {
981 return false;
982 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800983 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700984 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800985 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800987 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700988 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
989 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800990 if (result == NO_ERROR) {
991 mute = mute && state;
992 }
993 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800995
996 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997}
998
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800999void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1000{
1001 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1002
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001003 AutoMutex lock(mLock);
1004 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001005 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1006 }
1007 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1008 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001009 }
1010}
1011
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012status_t AudioFlinger::setMasterMute(bool muted)
1013{
John Grossmand8f178d2012-07-20 14:51:35 -07001014 status_t ret = initCheck();
1015 if (ret != NO_ERROR) {
1016 return ret;
1017 }
1018
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 // check calling permissions
1020 if (!settingsAllowed()) {
1021 return PERMISSION_DENIED;
1022 }
1023
John Grossmanee578c02012-07-23 17:05:46 -07001024 Mutex::Autolock _l(mLock);
1025 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001026
John Grossmanee578c02012-07-23 17:05:46 -07001027 // Set master mute in the HALs which support it.
1028 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1029 AutoMutex lock(mHardwareLock);
1030 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001031
John Grossmanee578c02012-07-23 17:05:46 -07001032 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1033 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001034 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001035 }
John Grossmanee578c02012-07-23 17:05:46 -07001036 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001037 }
1038
John Grossmanee578c02012-07-23 17:05:46 -07001039 // Now set the master mute in each playback thread. Playback threads
1040 // assigned to HALs which do not have master mute support will apply master
1041 // mute during the mix operation. Threads with HALs which do support master
1042 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001043 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1044 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1045 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047
1048 return NO_ERROR;
1049}
1050
1051float AudioFlinger::masterVolume() const
1052{
Glenn Kasten98067102011-12-13 11:47:54 -08001053 Mutex::Autolock _l(mLock);
1054 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055}
1056
1057bool AudioFlinger::masterMute() const
1058{
Glenn Kasten98067102011-12-13 11:47:54 -08001059 Mutex::Autolock _l(mLock);
1060 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061}
1062
John Grossman4ff14ba2012-02-08 16:37:41 -08001063float AudioFlinger::masterVolume_l() const
1064{
John Grossman4ff14ba2012-02-08 16:37:41 -08001065 return mMasterVolume;
1066}
1067
John Grossmand8f178d2012-07-20 14:51:35 -07001068bool AudioFlinger::masterMute_l() const
1069{
John Grossmanee578c02012-07-23 17:05:46 -07001070 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001071}
1072
Eric Laurent223fd5c2014-11-11 13:43:36 -08001073status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1074{
1075 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001076 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001077 return BAD_VALUE;
1078 }
1079 pid_t caller = IPCThreadState::self()->getCallingPid();
1080 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001081 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001082 return PERMISSION_DENIED;
1083 }
1084
1085 return NO_ERROR;
1086}
1087
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001088status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1089 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090{
1091 // check calling permissions
1092 if (!settingsAllowed()) {
1093 return PERMISSION_DENIED;
1094 }
1095
Eric Laurent223fd5c2014-11-11 13:43:36 -08001096 status_t status = checkStreamType(stream);
1097 if (status != NO_ERROR) {
1098 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 }
Eric Laurent98e38192018-02-15 18:31:53 -08001100 if (output == AUDIO_IO_HANDLE_NONE) {
1101 return BAD_VALUE;
1102 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001103 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104
1105 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001106 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1107 if (volumeInterface == NULL) {
1108 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 }
Eric Laurent98e38192018-02-15 18:31:53 -08001110 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111
1112 return NO_ERROR;
1113}
1114
Glenn Kastenfff6d712012-01-12 16:38:12 -08001115status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116{
1117 // check calling permissions
1118 if (!settingsAllowed()) {
1119 return PERMISSION_DENIED;
1120 }
1121
Eric Laurent223fd5c2014-11-11 13:43:36 -08001122 status_t status = checkStreamType(stream);
1123 if (status != NO_ERROR) {
1124 return status;
1125 }
1126 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1127
1128 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001129 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 return BAD_VALUE;
1131 }
1132
Eric Laurent93575202011-01-18 18:39:02 -08001133 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001135 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1136 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1137 volumeInterfaces[i]->setStreamMute(stream, muted);
1138 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139
1140 return NO_ERROR;
1141}
1142
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001143float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001145 status_t status = checkStreamType(stream);
1146 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 return 0.0f;
1148 }
Eric Laurent98e38192018-02-15 18:31:53 -08001149 if (output == AUDIO_IO_HANDLE_NONE) {
1150 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 }
1152
Eric Laurent98e38192018-02-15 18:31:53 -08001153 AutoMutex lock(mLock);
1154 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1155 if (volumeInterface == NULL) {
1156 return 0.0f;
1157 }
1158
1159 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160}
1161
Glenn Kastenfff6d712012-01-12 16:38:12 -08001162bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001164 status_t status = checkStreamType(stream);
1165 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 return true;
1167 }
1168
Glenn Kasten6637baa2012-01-09 09:40:36 -08001169 AutoMutex lock(mLock);
1170 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171}
1172
Eric Laurent054d9d32015-04-24 08:48:48 -07001173
1174void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1175{
1176 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1177 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1178 }
1179}
1180
Eric Laurentf1047e82018-04-16 19:18:20 -07001181// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1182// Some keys are used for audio routing and audio path configuration and should be reserved for use
1183// by audio policy and audio flinger for functional, privacy and security reasons.
1184void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1185{
1186 static const String8 kReservedParameters[] = {
1187 String8(AudioParameter::keyRouting),
1188 String8(AudioParameter::keySamplingRate),
1189 String8(AudioParameter::keyFormat),
1190 String8(AudioParameter::keyChannels),
1191 String8(AudioParameter::keyFrameCount),
1192 String8(AudioParameter::keyInputSource),
1193 String8(AudioParameter::keyMonoOutput),
1194 String8(AudioParameter::keyStreamConnect),
1195 String8(AudioParameter::keyStreamDisconnect),
1196 String8(AudioParameter::keyStreamSupportedFormats),
1197 String8(AudioParameter::keyStreamSupportedChannels),
1198 String8(AudioParameter::keyStreamSupportedSamplingRates),
1199 };
1200
1201 // multiuser friendly app ID check for requests coming from audioserver
1202 if (multiuser_get_app_id(callingUid) == AID_AUDIOSERVER) {
1203 return;
1204 }
1205
1206 AudioParameter param = AudioParameter(keyValuePairs);
1207 String8 value;
1208 for (auto& key : kReservedParameters) {
1209 if (param.get(key, value) == NO_ERROR) {
1210 ALOGW("%s: filtering key %s value %s from uid %d",
1211 __func__, key.string(), value.string(), callingUid);
1212 param.remove(key);
1213 }
1214 }
1215 keyValuePairs = param.toString();
1216}
1217
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001218status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219{
Eric Laurentf1047e82018-04-16 19:18:20 -07001220 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1221 ioHandle, keyValuePairs.string(),
1222 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001223
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 // check calling permissions
1225 if (!settingsAllowed()) {
1226 return PERMISSION_DENIED;
1227 }
1228
Eric Laurentf1047e82018-04-16 19:18:20 -07001229 String8 filteredKeyValuePairs = keyValuePairs;
1230 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1231
1232 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1233
Glenn Kasten142f5192014-03-25 17:44:59 -07001234 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1235 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001236 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001237 // result will remain NO_INIT if no audio device is present
1238 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001239 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001240 AutoMutex lock(mHardwareLock);
1241 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1242 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001243 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001244 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001245 // return success if at least one audio device accepts the parameters as not all
1246 // HALs are requested to support all parameters. If no audio device supports the
1247 // requested parameters, the last error is reported.
1248 if (final_result != NO_ERROR) {
1249 final_result = result;
1250 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001251 }
1252 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001253 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001254 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001255 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001256 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001257 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1258 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001259 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001260 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001261 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001262 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001263 }
1264 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001265 String8 screenState;
1266 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001267 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001268 if (isOff != (AudioFlinger::mScreenState & 1)) {
1269 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001270 }
1271 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001272 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273 }
1274
1275 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1276 // and the thread is exited once the lock is released
1277 sp<ThreadBase> thread;
1278 {
1279 Mutex::Autolock _l(mLock);
1280 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001281 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001283 if (thread == 0) {
1284 thread = checkMmapThread_l(ioHandle);
1285 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001286 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001287 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001288 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001289 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001290 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1291 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001292 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001293 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001294 }
1295 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001296 if (thread != 0) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001297 return thread->setParameters(filteredKeyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298 }
1299 return BAD_VALUE;
1300}
1301
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001302String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001304 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1305 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306
Eric Laurenta4c5a552012-03-29 10:12:40 -07001307 Mutex::Autolock _l(mLock);
1308
Glenn Kasten142f5192014-03-25 17:44:59 -07001309 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001310 String8 out_s8;
1311
Dima Zavin799a70e2011-04-18 16:57:27 -07001312 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001313 String8 s;
1314 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001315 {
1316 AutoMutex lock(mHardwareLock);
1317 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001318 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1319 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001320 mHardwareStatus = AUDIO_HW_IDLE;
1321 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001322 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001323 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001324 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325 }
1326
Eric Laurent6acd1d42017-01-04 14:23:29 -08001327 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1328 if (thread == NULL) {
1329 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1330 if (thread == NULL) {
1331 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1332 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001333 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001334 }
1335 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001337 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338}
1339
Glenn Kastendd8104c2012-07-02 12:42:44 -07001340size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1341 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342{
Eric Laurenta1884f92011-08-23 08:25:03 -07001343 status_t ret = initCheck();
1344 if (ret != NO_ERROR) {
1345 return 0;
1346 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001347 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001348 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001349 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001350 return 0;
1351 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001352
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001353 AutoMutex lock(mHardwareLock);
1354 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001355 audio_config_t config, proposed;
1356 memset(&proposed, 0, sizeof(proposed));
1357 proposed.sample_rate = sampleRate;
1358 proposed.channel_mask = channelMask;
1359 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001360
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001361 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001362 size_t frames;
1363 for (;;) {
1364 // Note: config is currently a const parameter for get_input_buffer_size()
1365 // but we use a copy from proposed in case config changes from the call.
1366 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001367 status_t result = dev->getInputBufferSize(&config, &frames);
1368 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001369 break; // hal success, config is the result
1370 }
1371 // change one parameter of the configuration each iteration to a more "common" value
1372 // to see if the device will support it.
1373 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1374 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1375 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1376 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1377 } else {
1378 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1379 "format %#x, channelMask 0x%X",
1380 sampleRate, format, channelMask);
1381 break; // retries failed, break out of loop with frames == 0.
1382 }
1383 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001384 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001385 if (frames > 0 && config.sample_rate != sampleRate) {
1386 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1387 }
1388 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389}
1390
Glenn Kasten5f972c02014-01-13 09:59:31 -08001391uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393 Mutex::Autolock _l(mLock);
1394
1395 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1396 if (recordThread != NULL) {
1397 return recordThread->getInputFramesLost();
1398 }
1399 return 0;
1400}
1401
1402status_t AudioFlinger::setVoiceVolume(float value)
1403{
Eric Laurenta1884f92011-08-23 08:25:03 -07001404 status_t ret = initCheck();
1405 if (ret != NO_ERROR) {
1406 return ret;
1407 }
1408
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409 // check calling permissions
1410 if (!settingsAllowed()) {
1411 return PERMISSION_DENIED;
1412 }
1413
1414 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001415 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001416 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001417 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001418 mHardwareStatus = AUDIO_HW_IDLE;
1419
1420 return ret;
1421}
1422
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001423status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001424 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426 Mutex::Autolock _l(mLock);
1427
1428 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1429 if (playbackThread != NULL) {
1430 return playbackThread->getRenderPosition(halFrames, dspFrames);
1431 }
1432
1433 return BAD_VALUE;
1434}
1435
1436void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1437{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001439 if (client == 0) {
1440 return;
1441 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001442 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001443 {
1444 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001445 if (mNotificationClients.indexOfKey(pid) < 0) {
1446 sp<NotificationClient> notificationClient = new NotificationClient(this,
1447 client,
1448 pid);
1449 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450
Eric Laurent021cf962014-05-13 10:18:14 -07001451 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452
Marco Nelissen06b46062014-11-14 07:58:25 -08001453 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001454 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001455 }
1456 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457
Eric Laurent021cf962014-05-13 10:18:14 -07001458 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001459 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001460 // the config change is always sent from playback or record threads to avoid deadlock
1461 // with AudioSystem::gLock
1462 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001463 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001465
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001466 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001467 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 }
1469}
1470
1471void AudioFlinger::removeNotificationClient(pid_t pid)
1472{
1473 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001474 {
1475 Mutex::Autolock _cl(mClientLock);
1476 mNotificationClients.removeItem(pid);
1477 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001478
Steve Block3856b092011-10-20 11:56:00 +01001479 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001480 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001481 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001482 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001483 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001484 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001485 if (ref->mPid == pid) {
1486 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001487 mAudioSessionRefs.removeAt(i);
1488 delete ref;
1489 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001490 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001491 } else {
1492 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001493 }
1494 }
1495 if (removed) {
1496 purgeStaleEffects_l();
1497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498}
1499
Eric Laurent73e26b62015-04-27 16:55:58 -07001500void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001501 const sp<AudioIoDescriptor>& ioDesc,
1502 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503{
Eric Laurent021cf962014-05-13 10:18:14 -07001504 Mutex::Autolock _l(mClientLock);
1505 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001507 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1508 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 }
1511}
1512
Eric Laurent021cf962014-05-13 10:18:14 -07001513// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514void AudioFlinger::removeClient_l(pid_t pid)
1515{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001516 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001517 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518 mClients.removeItem(pid);
1519}
1520
Eric Laurent717e1282012-06-29 16:36:52 -07001521// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001522sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1523 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001524{
1525 sp<PlaybackThread> thread;
1526
1527 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1528 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1529 ALOG_ASSERT(thread == 0);
1530 thread = mPlaybackThreads.valueAt(i);
1531 }
1532 }
1533
1534 return thread;
1535}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538
1539// ----------------------------------------------------------------------------
1540
1541AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1542 : RefBase(),
1543 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001544 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545{
Andy Hung6f248bb2018-01-23 14:04:37 -08001546 mMemoryDealer = new MemoryDealer(
1547 audioFlinger->getClientSharedHeapSize(),
1548 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549}
1550
Eric Laurent021cf962014-05-13 10:18:14 -07001551// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552AudioFlinger::Client::~Client()
1553{
1554 mAudioFlinger->removeClient_l(mPid);
1555}
1556
Glenn Kasten435dbe62012-01-30 10:15:48 -08001557sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558{
1559 return mMemoryDealer;
1560}
1561
1562// ----------------------------------------------------------------------------
1563
1564AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1565 const sp<IAudioFlingerClient>& client,
1566 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001567 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568{
1569}
1570
1571AudioFlinger::NotificationClient::~NotificationClient()
1572{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573}
1574
Glenn Kasten0f11b512014-01-31 16:18:54 -08001575void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576{
1577 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001578 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579}
1580
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001581// ----------------------------------------------------------------------------
1582AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1583 : mPendingRequests(false) {}
1584
1585
1586void AudioFlinger::MediaLogNotifier::requestMerge() {
1587 AutoMutex _l(mMutex);
1588 mPendingRequests = true;
1589 mCond.signal();
1590}
1591
1592bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001593 // Should already have been checked, but just in case
1594 if (sMediaLogService == 0) {
1595 return false;
1596 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001597 // Wait until there are pending requests
1598 {
1599 AutoMutex _l(mMutex);
1600 mPendingRequests = false; // to ignore past requests
1601 while (!mPendingRequests) {
1602 mCond.wait(mMutex);
1603 // TODO may also need an exitPending check
1604 }
1605 mPendingRequests = false;
1606 }
1607 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001608 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001609 usleep(kPostTriggerSleepPeriod);
1610 return true;
1611}
1612
1613void AudioFlinger::requestLogMerge() {
1614 mMediaLogNotifier->requestMerge();
1615}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616
1617// ----------------------------------------------------------------------------
1618
Eric Laurentf14db3c2017-12-08 14:20:36 -08001619sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1620 CreateRecordOutput& output,
1621 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622{
1623 sp<RecordThread::RecordTrack> recordTrack;
1624 sp<RecordHandle> recordHandle;
1625 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001627 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001628 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629
Eric Laurentf14db3c2017-12-08 14:20:36 -08001630 output.cblk.clear();
1631 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001632 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001633
Eric Laurentf14db3c2017-12-08 14:20:36 -08001634 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001635 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001636 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001637 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001638 ALOGW_IF(clientUid != callingUid,
1639 "%s uid %d tried to pass itself off as %d",
1640 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001641 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001642 updatePid = true;
1643 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001644 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001645 if (updatePid) {
1646 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001647 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001648 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001649 __func__, callingUid, callingPid, clientPid);
1650 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001651 }
1652
Andy Hung6770c6f2015-04-07 13:43:36 -07001653 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001654 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1655 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001656 lStatus = BAD_VALUE;
1657 goto Exit;
1658 }
1659
Glenn Kasten53b5d092014-02-05 10:00:23 -08001660 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001661 if (!audio_is_input_channel(input.config.channel_mask)) {
1662 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001663 lStatus = BAD_VALUE;
1664 goto Exit;
1665 }
1666
Eric Laurentf14db3c2017-12-08 14:20:36 -08001667 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1668 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1669 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1670 lStatus = BAD_VALUE;
1671 goto Exit;
1672 }
1673
1674 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001675 output.selectedDeviceId = input.selectedDeviceId;
1676 output.flags = input.flags;
1677
1678 client = registerPid(clientPid);
1679
1680 // Not a conventional loop, but a retry loop for at most two iterations total.
1681 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1682 // Exits loop via break on no error of got exit on error
1683 // The sp<> references will be dropped when re-entering scope.
1684 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1685 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001686 // release previously opened input if retrying.
1687 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1688 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001689 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001690 output.inputId = AUDIO_IO_HANDLE_NONE;
Eric Laurent77881cd2018-02-09 16:01:31 -08001691 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001692 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001693 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1694 sessionId,
1695 // FIXME compare to AudioTrack
1696 clientPid,
1697 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001698 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001699 &input.config,
1700 output.flags, &output.selectedDeviceId, &portId);
1701
Glenn Kasten05997e22014-03-13 15:08:33 -07001702 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001704 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001706 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707 lStatus = BAD_VALUE;
1708 goto Exit;
1709 }
1710
Eric Laurentf14db3c2017-12-08 14:20:36 -08001711 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712
Eric Laurentf14db3c2017-12-08 14:20:36 -08001713 output.sampleRate = input.config.sample_rate;
1714 output.frameCount = input.frameCount;
1715 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001716
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001717 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001718 input.config.format, input.config.channel_mask,
1719 &output.frameCount, sessionId,
1720 &output.notificationFrameCount,
1721 clientUid, &output.flags,
1722 input.clientInfo.clientTid,
1723 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001724 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001725
Eric Laurentf14db3c2017-12-08 14:20:36 -08001726 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1727 // audio policy manager without FAST constraint
1728 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001729 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001730 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001731
1732 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001733 goto Exit;
1734 }
1735
1736 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1737 // session and move it to this thread.
1738 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1739 if (chain != 0) {
1740 Mutex::Autolock _l(thread->mLock);
1741 thread->addEffectChain_l(chain);
1742 }
1743 break;
1744 }
1745 // End of retry loop.
1746 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 }
Glenn Kastene198c362013-08-13 09:13:36 -07001748
Eric Laurentf14db3c2017-12-08 14:20:36 -08001749 output.cblk = recordTrack->getCblk();
1750 output.buffers = recordTrack->getBuffers();
1751
1752 // return handle to client
1753 recordHandle = new RecordHandle(recordTrack);
1754
1755Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001756 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001757 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001758 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001759 // Don't hold mClientLock when releasing the reference on the track as the
1760 // destructor will acquire it.
1761 {
1762 Mutex::Autolock _cl(mClientLock);
1763 client.clear();
1764 }
Eric Laurent896c9672017-12-08 14:08:45 -08001765 recordTrack.clear();
1766 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001767 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001768 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 }
1770
Glenn Kasten9156ef32013-08-06 15:39:08 -07001771 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 return recordHandle;
1773}
1774
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001775
1776
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777// ----------------------------------------------------------------------------
1778
Eric Laurenta4c5a552012-03-29 10:12:40 -07001779audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1780{
Eric Laurent44622db2014-08-01 19:00:33 -07001781 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001782 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001783 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001784 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001785 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001786 }
1787 Mutex::Autolock _l(mLock);
1788 return loadHwModule_l(name);
1789}
1790
1791// loadHwModule_l() must be called with AudioFlinger::mLock held
1792audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1793{
1794 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1795 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1796 ALOGW("loadHwModule() module %s already loaded", name);
1797 return mAudioHwDevs.keyAt(i);
1798 }
1799 }
1800
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001801 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001802
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001803 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001804 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001805 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001806 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001807 }
1808
1809 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001810 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001811 mHardwareStatus = AUDIO_HW_IDLE;
1812 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001813 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001814 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001815 }
1816
John Grossmanee578c02012-07-23 17:05:46 -07001817 // Check and cache this HAL's level of support for master mute and master
1818 // volume. If this is the first HAL opened, and it supports the get
1819 // methods, use the initial values provided by the HAL as the current
1820 // master mute and volume settings.
1821
1822 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1823 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001824 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001825
1826 if (0 == mAudioHwDevs.size()) {
1827 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001828 float mv;
1829 if (OK == dev->getMasterVolume(&mv)) {
1830 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001831 }
1832
1833 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001834 bool mm;
1835 if (OK == dev->getMasterMute(&mm)) {
1836 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001837 }
1838 }
1839
Eric Laurenta4c5a552012-03-29 10:12:40 -07001840 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001841 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001842 flags = static_cast<AudioHwDevice::Flags>(flags |
1843 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1844 }
1845
1846 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001847 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001848 flags = static_cast<AudioHwDevice::Flags>(flags |
1849 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1850 }
1851
Eric Laurenta4c5a552012-03-29 10:12:40 -07001852 mHardwareStatus = AUDIO_HW_IDLE;
1853 }
1854
Glenn Kastena13cde92016-03-28 15:26:02 -07001855 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001856 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001857
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001858 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001859
1860 return handle;
1861
1862}
1863
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001864// ----------------------------------------------------------------------------
1865
Glenn Kasten3b16c762012-11-14 08:44:39 -08001866uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001867{
1868 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001869 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001870 return thread != NULL ? thread->sampleRate() : 0;
1871}
1872
Glenn Kastene33054e2012-11-14 12:54:39 -08001873size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001874{
1875 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001876 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001877 return thread != NULL ? thread->frameCountHAL() : 0;
1878}
1879
1880// ----------------------------------------------------------------------------
1881
Andy Hung6f248bb2018-01-23 14:04:37 -08001882status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001883{
1884 uid_t uid = IPCThreadState::self()->getCallingUid();
1885 if (uid != AID_SYSTEM) {
1886 return PERMISSION_DENIED;
1887 }
1888 Mutex::Autolock _l(mLock);
1889 if (mIsDeviceTypeKnown) {
1890 return INVALID_OPERATION;
1891 }
1892 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001893 mTotalMemory = totalMemory;
1894 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1895 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1896 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1897 // though actual setting is determined through device configuration.
1898 constexpr int64_t GB = 1024 * 1024 * 1024;
1899 mClientSharedHeapSize =
1900 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1901 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1902 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1903 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1904 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001905 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001906
1907 // TODO: Cache the client shared heap size in a persistent property.
1908 // It's possible that a native process or Java service or app accesses audioserver
1909 // after it is registered by system server, but before AudioService updates
1910 // the memory info. This would occur immediately after boot or an audioserver
1911 // crash and restore. Before update from AudioService, the client would get the
1912 // minimum heap size.
1913
1914 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1915 (isLowRamDevice ? "true" : "false"),
1916 (long long)mTotalMemory,
1917 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001918 return NO_ERROR;
1919}
1920
Andy Hung6f248bb2018-01-23 14:04:37 -08001921size_t AudioFlinger::getClientSharedHeapSize() const
1922{
1923 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1924 if (heapSizeInBytes != 0) { // read-only property overrides all.
1925 return heapSizeInBytes;
1926 }
1927 return mClientSharedHeapSize;
1928}
1929
Mikhail Naganovdea53042018-04-26 13:10:21 -07001930status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1931{
1932 ALOGV(__func__);
1933
1934 audio_module_handle_t module;
1935 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1936 module = config->ext.device.hw_module;
1937 } else {
1938 module = config->ext.mix.hw_module;
1939 }
1940
1941 Mutex::Autolock _l(mLock);
1942 ssize_t index = mAudioHwDevs.indexOfKey(module);
1943 if (index < 0) {
1944 ALOGW("%s() bad hw module %d", __func__, module);
1945 return BAD_VALUE;
1946 }
1947
1948 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
1949 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
1950}
1951
Eric Laurent93c3d412014-08-01 14:48:35 -07001952audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1953{
1954 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001955
1956 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1957 if (index >= 0) {
1958 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1959 mHwAvSyncIds.valueAt(index), sessionId);
1960 return mHwAvSyncIds.valueAt(index);
1961 }
1962
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001963 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001964 if (dev == NULL) {
1965 return AUDIO_HW_SYNC_INVALID;
1966 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001967 String8 reply;
1968 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001969 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001970 param = AudioParameter(reply);
1971 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001972
1973 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001974 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001975 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1976 return AUDIO_HW_SYNC_INVALID;
1977 }
1978
1979 // allow only one session for a given HW A/V sync ID.
1980 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1981 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1982 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1983 value, mHwAvSyncIds.keyAt(i));
1984 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001985 break;
1986 }
1987 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001988
1989 mHwAvSyncIds.add(sessionId, value);
1990
1991 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1992 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1993 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001994 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001995 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001996 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001997 thread->setParameters(param.toString());
1998 break;
1999 }
2000 }
2001
2002 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2003 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002004}
2005
Eric Laurent72e3f392015-05-20 14:43:50 -07002006status_t AudioFlinger::systemReady()
2007{
2008 Mutex::Autolock _l(mLock);
2009 ALOGI("%s", __FUNCTION__);
2010 if (mSystemReady) {
2011 ALOGW("%s called twice", __FUNCTION__);
2012 return NO_ERROR;
2013 }
2014 mSystemReady = true;
2015 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2016 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2017 thread->systemReady();
2018 }
2019 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2020 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2021 thread->systemReady();
2022 }
2023 return NO_ERROR;
2024}
2025
jiabin46a76fa2018-01-05 10:18:21 -08002026status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2027{
jiabin9ff780e2018-03-19 18:19:52 -07002028 AutoMutex lock(mHardwareLock);
2029 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2030 status_t status = dev->getMicrophones(microphones);
2031 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002032}
2033
Eric Laurentfa90e842014-10-17 18:12:31 -07002034// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2035void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2036{
2037 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2038 if (index >= 0) {
2039 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2040 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2041 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002042 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002043 thread->setParameters(param.toString());
2044 }
2045}
2046
2047
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002048// ----------------------------------------------------------------------------
2049
Eric Laurent83b88082014-06-20 18:31:16 -07002050
Eric Laurent6acd1d42017-01-04 14:23:29 -08002051sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002052 audio_io_handle_t *output,
2053 audio_config_t *config,
2054 audio_devices_t devices,
2055 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002056 audio_output_flags_t flags)
2057{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002058 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002059 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002060 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002061 }
2062
Eric Laurentcf2c0212014-07-25 16:20:43 -07002063 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002064 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2065 } else {
2066 // Audio Policy does not currently request a specific output handle.
2067 // If this is ever needed, see openInput_l() for example code.
2068 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2069 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002070 }
Eric Laurent83b88082014-06-20 18:31:16 -07002071
2072 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2073
Eric Laurent83b88082014-06-20 18:31:16 -07002074 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002075 // This if statement allows overriding the audio policy settings
2076 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2077 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2078 // Check only for Normal Mixing mode
2079 if (kEnableExtendedPrecision) {
2080 // Specify format (uncomment one below to choose)
2081 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2082 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2083 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2084 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002085 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002086 }
2087 if (kEnableExtendedChannels) {
2088 // Specify channel mask (uncomment one below to choose)
2089 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2090 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2091 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2092 }
Eric Laurent83b88082014-06-20 18:31:16 -07002093 }
2094
Phil Burk062e67a2015-02-11 13:40:50 -08002095 AudioStreamOut *outputStream = NULL;
2096 status_t status = outHwDev->openOutputStream(
2097 &outputStream,
2098 *output,
2099 devices,
2100 flags,
2101 config,
2102 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002103
2104 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002105
Phil Burk062e67a2015-02-11 13:40:50 -08002106 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002107 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2108 sp<MmapPlaybackThread> thread =
2109 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2110 devices, AUDIO_DEVICE_NONE, mSystemReady);
2111 mMmapThreads.add(*output, thread);
2112 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2113 *output, thread.get());
2114 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002115 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002116 sp<PlaybackThread> thread;
2117 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2118 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2119 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2120 *output, thread.get());
2121 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2122 || !isValidPcmSinkFormat(config->format)
2123 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2124 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2125 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2126 *output, thread.get());
2127 } else {
2128 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2129 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2130 *output, thread.get());
2131 }
2132 mPlaybackThreads.add(*output, thread);
2133 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002134 }
Eric Laurent83b88082014-06-20 18:31:16 -07002135 }
2136
2137 return 0;
2138}
2139
Eric Laurentcf2c0212014-07-25 16:20:43 -07002140status_t AudioFlinger::openOutput(audio_module_handle_t module,
2141 audio_io_handle_t *output,
2142 audio_config_t *config,
2143 audio_devices_t *devices,
2144 const String8& address,
2145 uint32_t *latencyMs,
2146 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002148 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2149 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002150 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002151 (devices != NULL) ? *devices : 0,
2152 config->sample_rate,
2153 config->format,
2154 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002155 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002157 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002158 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002160
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 Mutex::Autolock _l(mLock);
2162
Eric Laurent6acd1d42017-01-04 14:23:29 -08002163 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002164 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002165 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2166 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2167 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168
Eric Laurent6acd1d42017-01-04 14:23:29 -08002169 // notify client processes of the new output creation
2170 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002171
Eric Laurent6acd1d42017-01-04 14:23:29 -08002172 // the first primary output opened designates the primary hw device
2173 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002174 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002175 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002176
Eric Laurent6acd1d42017-01-04 14:23:29 -08002177 AutoMutex lock(mHardwareLock);
2178 mHardwareStatus = AUDIO_HW_SET_MODE;
2179 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2180 mHardwareStatus = AUDIO_HW_IDLE;
2181 }
2182 } else {
2183 MmapThread *mmapThread = (MmapThread *)thread.get();
2184 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002185 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002186 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 }
2188
Eric Laurentcf2c0212014-07-25 16:20:43 -07002189 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190}
2191
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002192audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2193 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194{
2195 Mutex::Autolock _l(mLock);
2196 MixerThread *thread1 = checkMixerThread_l(output1);
2197 MixerThread *thread2 = checkMixerThread_l(output2);
2198
2199 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002200 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2201 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002202 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
2204
Glenn Kasteneeecb982016-02-26 10:44:04 -08002205 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002206 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 thread->addOutputTrack(thread2);
2208 mPlaybackThreads.add(id, thread);
2209 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002210 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211 return id;
2212}
2213
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002214status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215{
Glenn Kastend96c5722012-04-25 13:44:49 -07002216 return closeOutput_nonvirtual(output);
2217}
2218
2219status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2220{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221 // keep strong reference on the playback thread so that
2222 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002223 sp<PlaybackThread> playbackThread;
2224 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225 {
2226 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002227 playbackThread = checkPlaybackThread_l(output);
2228 if (playbackThread != NULL) {
2229 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230
Eric Laurent6acd1d42017-01-04 14:23:29 -08002231 if (playbackThread->type() == ThreadBase::MIXER) {
2232 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2233 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2234 DuplicatingThread *dupThread =
2235 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2236 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2237 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238 }
2239 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240
2241
Eric Laurent6acd1d42017-01-04 14:23:29 -08002242 mPlaybackThreads.removeItem(output);
2243 // save all effects to the default thread
2244 if (mPlaybackThreads.size()) {
2245 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2246 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002247 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002248 Mutex::Autolock _dl(dstThread->mLock);
2249 Mutex::Autolock _sl(playbackThread->mLock);
2250 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2251 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002252 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2253 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002254 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 }
2256 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002257 } else {
2258 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2259 if (mmapThread == 0) {
2260 return BAD_VALUE;
2261 }
2262 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002263 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002265 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2266 ioDesc->mIoHandle = output;
2267 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002269 // The thread entity (active unit of execution) is no longer running here,
2270 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271
Eric Laurent6acd1d42017-01-04 14:23:29 -08002272 if (playbackThread != 0) {
2273 playbackThread->exit();
2274 if (!playbackThread->isDuplicating()) {
2275 closeOutputFinish(playbackThread);
2276 }
2277 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002278 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002279 mmapThread->exit();
2280 AudioStreamOut *out = mmapThread->clearOutput();
2281 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2282 // from now on thread->mOutput is NULL
2283 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 }
2285 return NO_ERROR;
2286}
2287
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002288void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002289{
2290 AudioStreamOut *out = thread->clearOutput();
2291 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2292 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002293 delete out;
2294}
2295
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002296void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002297{
2298 mPlaybackThreads.removeItem(thread->mId);
2299 thread->exit();
2300 closeOutputFinish(thread);
2301}
2302
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002303status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304{
2305 Mutex::Autolock _l(mLock);
2306 PlaybackThread *thread = checkPlaybackThread_l(output);
2307
2308 if (thread == NULL) {
2309 return BAD_VALUE;
2310 }
2311
Steve Block3856b092011-10-20 11:56:00 +01002312 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313 thread->suspend();
2314
2315 return NO_ERROR;
2316}
2317
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002318status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319{
2320 Mutex::Autolock _l(mLock);
2321 PlaybackThread *thread = checkPlaybackThread_l(output);
2322
2323 if (thread == NULL) {
2324 return BAD_VALUE;
2325 }
2326
Steve Block3856b092011-10-20 11:56:00 +01002327 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328
2329 thread->restore();
2330
2331 return NO_ERROR;
2332}
2333
Eric Laurentcf2c0212014-07-25 16:20:43 -07002334status_t AudioFlinger::openInput(audio_module_handle_t module,
2335 audio_io_handle_t *input,
2336 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002337 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002338 const String8& address,
2339 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002340 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341{
Eric Laurent83b88082014-06-20 18:31:16 -07002342 Mutex::Autolock _l(mLock);
2343
Glenn Kastene7d66712015-03-05 13:46:52 -08002344 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002345 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002346 }
2347
Eric Laurent6acd1d42017-01-04 14:23:29 -08002348 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002349
2350 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002351 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002352 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002353 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002355 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002356}
Dima Zavin799a70e2011-04-18 16:57:27 -07002357
Eric Laurent6acd1d42017-01-04 14:23:29 -08002358sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002359 audio_io_handle_t *input,
2360 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002361 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002362 const String8& address,
2363 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002364 audio_input_flags_t flags)
2365{
Glenn Kastene7d66712015-03-05 13:46:52 -08002366 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002367 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002368 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002369 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002370 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002371
Glenn Kasteneeecb982016-02-26 10:44:04 -08002372 // Audio Policy can request a specific handle for hardware hotword.
2373 // The goal here is not to re-open an already opened input.
2374 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002375 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002376 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2377 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2378 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2379 return 0;
2380 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2381 // This should not happen in a transient state with current design.
2382 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2383 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002384 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002385
Eric Laurentcf2c0212014-07-25 16:20:43 -07002386 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002387 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002388 sp<StreamInHalInterface> inStream;
2389 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002390 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002391 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2392 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002393 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002394 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002395 halconfig.sample_rate,
2396 halconfig.format,
2397 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002398 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002399 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002401 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002402 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002403 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002404 audio_is_linear_pcm(config->format) &&
2405 audio_is_linear_pcm(halconfig.format) &&
2406 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002407 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2408 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002409 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002410 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002411 inStream.clear();
2412 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002413 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002414 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 }
2416
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002417 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002418 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002419 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2420 sp<MmapCaptureThread> thread =
2421 new MmapCaptureThread(this, *input,
2422 inHwDev, inputStream,
2423 primaryOutputDevice_l(), devices, mSystemReady);
2424 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002425 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2426 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002427 return thread;
2428 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002429#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002430 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2431 // or (re-)create if current Pipe is idle and does not match the new format
2432 sp<NBAIO_Sink> teeSink;
2433 enum {
2434 TEE_SINK_NO, // don't copy input
2435 TEE_SINK_NEW, // copy input using a new pipe
2436 TEE_SINK_OLD, // copy input using an existing pipe
2437 } kind;
2438 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2439 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2440 if (!mTeeSinkInputEnabled) {
2441 kind = TEE_SINK_NO;
2442 } else if (!Format_isValid(format)) {
2443 kind = TEE_SINK_NO;
2444 } else if (mRecordTeeSink == 0) {
2445 kind = TEE_SINK_NEW;
2446 } else if (mRecordTeeSink->getStrongCount() != 1) {
2447 kind = TEE_SINK_NO;
2448 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2449 kind = TEE_SINK_OLD;
2450 } else {
2451 kind = TEE_SINK_NEW;
2452 }
2453 switch (kind) {
2454 case TEE_SINK_NEW: {
2455 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2456 size_t numCounterOffers = 0;
2457 const NBAIO_Format offers[1] = {format};
2458 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2459 ALOG_ASSERT(index == 0);
2460 PipeReader *pipeReader = new PipeReader(*pipe);
2461 numCounterOffers = 0;
2462 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2463 ALOG_ASSERT(index == 0);
2464 mRecordTeeSink = pipe;
2465 mRecordTeeSource = pipeReader;
2466 teeSink = pipe;
2467 }
2468 break;
2469 case TEE_SINK_OLD:
2470 teeSink = mRecordTeeSink;
2471 break;
2472 case TEE_SINK_NO:
2473 default:
2474 break;
2475 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002476#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002477
2478 // Start record thread
2479 // RecordThread requires both input and output device indication to forward to audio
2480 // pre processing modules
2481 sp<RecordThread> thread = new RecordThread(this,
2482 inputStream,
2483 *input,
2484 primaryOutputDevice_l(),
2485 devices,
2486 mSystemReady
2487#ifdef TEE_SINK
2488 , teeSink
2489#endif
2490 );
2491 mRecordThreads.add(*input, thread);
2492 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2493 return thread;
2494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 }
2496
Eric Laurentcf2c0212014-07-25 16:20:43 -07002497 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 return 0;
2499}
2500
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002501status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502{
Glenn Kastend96c5722012-04-25 13:44:49 -07002503 return closeInput_nonvirtual(input);
2504}
2505
2506status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2507{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 // keep strong reference on the record thread so that
2509 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002510 sp<RecordThread> recordThread;
2511 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 {
2513 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002514 recordThread = checkRecordThread_l(input);
2515 if (recordThread != 0) {
2516 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517
Eric Laurent6acd1d42017-01-04 14:23:29 -08002518 // If we still have effect chains, it means that a client still holds a handle
2519 // on at least one effect. We must either move the chain to an existing thread with the
2520 // same session ID or put it aside in case a new record thread is opened for a
2521 // new capture on the same session
2522 sp<EffectChain> chain;
2523 {
2524 Mutex::Autolock _sl(recordThread->mLock);
2525 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2526 // Note: maximum one chain per record thread
2527 if (effectChains.size() != 0) {
2528 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002529 }
2530 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002531 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002532 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002533 // This should only happen in case of overlap between one thread tear down and the
2534 // creation of its replacement
2535 size_t i;
2536 for (i = 0; i < mRecordThreads.size(); i++) {
2537 sp<RecordThread> t = mRecordThreads.valueAt(i);
2538 if (t == recordThread) {
2539 continue;
2540 }
2541 if (t->hasAudioSession(chain->sessionId()) != 0) {
2542 Mutex::Autolock _l(t->mLock);
2543 ALOGV("closeInput() found thread %d for effect session %d",
2544 t->id(), chain->sessionId());
2545 t->addEffectChain_l(chain);
2546 break;
2547 }
2548 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002549 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002550 if (i == mRecordThreads.size()) {
2551 putOrphanEffectChain_l(chain);
2552 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002553 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002554 mRecordThreads.removeItem(input);
2555 } else {
2556 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2557 if (mmapThread == 0) {
2558 return BAD_VALUE;
2559 }
2560 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002561 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002562 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2563 ioDesc->mIoHandle = input;
2564 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565 }
Eric Laurent83b88082014-06-20 18:31:16 -07002566 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2567 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002568 if (recordThread != 0) {
2569 closeInputFinish(recordThread);
2570 } else if (mmapThread != 0) {
2571 mmapThread->exit();
2572 AudioStreamIn *in = mmapThread->clearInput();
2573 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2574 // from now on thread->mInput is NULL
2575 delete in;
2576 }
Eric Laurent83b88082014-06-20 18:31:16 -07002577 return NO_ERROR;
2578}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002580void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002581{
2582 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002583 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002584 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002585 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002586 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002587}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002589void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002590{
2591 mRecordThreads.removeItem(thread->mId);
2592 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593}
2594
Glenn Kastend2304db2014-02-03 07:40:31 -08002595status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596{
2597 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002598 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599
2600 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2601 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002602 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002603 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002604 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2605 mMmapThreads[i]->invalidateTracks(stream);
2606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 return NO_ERROR;
2608}
2609
2610
Glenn Kasteneeecb982016-02-26 10:44:04 -08002611audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612{
Glenn Kasten9d003132016-04-06 14:38:09 -07002613 // This is a binder API, so a malicious client could pass in a bad parameter.
2614 // Check for that before calling the internal API nextUniqueId().
2615 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2616 ALOGE("newAudioUniqueId invalid use %d", use);
2617 return AUDIO_UNIQUE_ID_ALLOCATE;
2618 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002619 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620}
2621
Glenn Kastend848eb42016-03-08 13:42:11 -08002622void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002623{
2624 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002625 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002626 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2627 if (pid != -1 && (caller == getpid_cached)) {
2628 caller = pid;
2629 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002630
Eric Laurent021cf962014-05-13 10:18:14 -07002631 {
2632 Mutex::Autolock _cl(mClientLock);
2633 // Ignore requests received from processes not known as notification client. The request
2634 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2635 // called from a different pid leaving a stale session reference. Also we don't know how
2636 // to clear this reference if the client process dies.
2637 if (mNotificationClients.indexOfKey(caller) < 0) {
2638 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2639 return;
2640 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002641 }
2642
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002643 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002644 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002645 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002646 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2647 ref->mCnt++;
2648 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002649 return;
2650 }
2651 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002652 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2653 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002654}
2655
Glenn Kastend848eb42016-03-08 13:42:11 -08002656void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002657{
2658 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002659 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002660 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2661 if (pid != -1 && (caller == getpid_cached)) {
2662 caller = pid;
2663 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002664 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002665 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002666 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002667 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2668 ref->mCnt--;
2669 ALOGV(" decremented refcount to %d", ref->mCnt);
2670 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002671 mAudioSessionRefs.removeAt(i);
2672 delete ref;
2673 purgeStaleEffects_l();
2674 }
2675 return;
2676 }
2677 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002678 // If the caller is mediaserver it is likely that the session being released was acquired
2679 // on behalf of a process not in notification clients and we ignore the warning.
2680 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002681}
2682
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002683bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2684{
2685 size_t num = mAudioSessionRefs.size();
2686 for (size_t i = 0; i < num; i++) {
2687 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2688 if (ref->mSessionid == audioSession) {
2689 return true;
2690 }
2691 }
2692 return false;
2693}
2694
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002695void AudioFlinger::purgeStaleEffects_l() {
2696
Steve Block3856b092011-10-20 11:56:00 +01002697 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002698
2699 Vector< sp<EffectChain> > chains;
2700
2701 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2702 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002703 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002704 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2705 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002706 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2707 chains.push(ec);
2708 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002709 }
2710 }
2711 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2712 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002713 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002714 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2715 sp<EffectChain> ec = t->mEffectChains[j];
2716 chains.push(ec);
2717 }
2718 }
2719
2720 for (size_t i = 0; i < chains.size(); i++) {
2721 sp<EffectChain> ec = chains[i];
2722 int sessionid = ec->sessionId();
2723 sp<ThreadBase> t = ec->mThread.promote();
2724 if (t == 0) {
2725 continue;
2726 }
2727 size_t numsessionrefs = mAudioSessionRefs.size();
2728 bool found = false;
2729 for (size_t k = 0; k < numsessionrefs; k++) {
2730 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002731 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002732 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002733 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002734 found = true;
2735 break;
2736 }
2737 }
2738 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002739 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002740 // remove all effects from the chain
2741 while (ec->mEffects.size()) {
2742 sp<EffectModule> effect = ec->mEffects[0];
2743 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002744 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002745 if (effect->purgeHandles()) {
2746 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002747 }
2748 AudioSystem::unregisterEffect(effect->id());
2749 }
2750 }
2751 }
2752 return;
2753}
2754
Glenn Kasteneeecb982016-02-26 10:44:04 -08002755// checkThread_l() must be called with AudioFlinger::mLock held
2756AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2757{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002758 ThreadBase *thread = checkMmapThread_l(ioHandle);
2759 if (thread == 0) {
2760 switch (audio_unique_id_get_use(ioHandle)) {
2761 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2762 thread = checkPlaybackThread_l(ioHandle);
2763 break;
2764 case AUDIO_UNIQUE_ID_USE_INPUT:
2765 thread = checkRecordThread_l(ioHandle);
2766 break;
2767 default:
2768 break;
2769 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002770 }
2771 return thread;
2772}
2773
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002775AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776{
Glenn Kastena1117922012-01-26 10:53:32 -08002777 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778}
2779
2780// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002781AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002782{
2783 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002784 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785}
2786
2787// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002788AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789{
Glenn Kastena1117922012-01-26 10:53:32 -08002790 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791}
2792
Eric Laurent6acd1d42017-01-04 14:23:29 -08002793// checkMmapThread_l() must be called with AudioFlinger::mLock held
2794AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2795{
2796 return mMmapThreads.valueFor(io).get();
2797}
2798
2799
2800// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2801AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2802{
Eric Laurent7459b902017-04-19 18:10:41 -07002803 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002804 if (volumeInterface == nullptr) {
2805 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2806 if (mmapThread != nullptr) {
2807 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002808 MmapPlaybackThread *mmapPlaybackThread =
2809 static_cast<MmapPlaybackThread *>(mmapThread);
2810 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002811 }
2812 }
2813 }
2814 return volumeInterface;
2815}
2816
2817Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2818{
2819 Vector <VolumeInterface *> volumeInterfaces;
2820 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002821 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002822 }
2823 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2824 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002825 MmapPlaybackThread *mmapPlaybackThread =
2826 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2827 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002828 }
2829 }
2830 return volumeInterfaces;
2831}
2832
Glenn Kasteneeecb982016-02-26 10:44:04 -08002833audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834{
Glenn Kasten9d003132016-04-06 14:38:09 -07002835 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002836 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002837 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2838 for (int retry = 0; retry < maxRetries; retry++) {
2839 // The cast allows wraparound from max positive to min negative instead of abort
2840 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2841 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2842 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2843 // allow wrap by skipping 0 and -1 for session ids
2844 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2845 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2846 return (audio_unique_id_t) (base | use);
2847 }
2848 }
2849 // We have no way of recovering from wraparound
2850 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2851 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852}
2853
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002854AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002855{
2856 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2857 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002858 if(thread->isDuplicating()) {
2859 continue;
2860 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002861 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002862 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002863 return thread;
2864 }
2865 }
2866 return NULL;
2867}
2868
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002869audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002870{
2871 PlaybackThread *thread = primaryPlaybackThread_l();
2872
2873 if (thread == NULL) {
2874 return 0;
2875 }
2876
Eric Laurentf1c04f92012-08-28 14:26:53 -07002877 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002878}
2879
Glenn Kastena7335632016-06-09 17:09:53 -07002880AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2881{
2882 size_t minFrameCount = 0;
2883 PlaybackThread *minThread = NULL;
2884 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2885 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2886 if (!thread->isDuplicating()) {
2887 size_t frameCount = thread->frameCountHAL();
2888 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2889 (frameCount == minFrameCount && thread->hasFastMixer() &&
2890 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2891 minFrameCount = frameCount;
2892 minThread = thread;
2893 }
2894 }
2895 }
2896 return minThread;
2897}
2898
Eric Laurenta011e352012-03-29 15:51:43 -07002899sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002900 audio_session_t triggerSession,
2901 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002902 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002903 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002904{
2905 Mutex::Autolock _l(mLock);
2906
2907 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2908 status_t playStatus = NAME_NOT_FOUND;
2909 status_t recStatus = NAME_NOT_FOUND;
2910 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2911 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2912 if (playStatus == NO_ERROR) {
2913 return event;
2914 }
2915 }
2916 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2917 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2918 if (recStatus == NO_ERROR) {
2919 return event;
2920 }
2921 }
2922 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2923 mPendingSyncEvents.add(event);
2924 } else {
2925 ALOGV("createSyncEvent() invalid event %d", event->type());
2926 event.clear();
2927 }
2928 return event;
2929}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002930
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931// ----------------------------------------------------------------------------
2932// Effect management
2933// ----------------------------------------------------------------------------
2934
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002935sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2936 return mEffectsFactoryHal;
2937}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938
Glenn Kastenf587ba52012-01-26 16:25:10 -08002939status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940{
2941 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002942 if (mEffectsFactoryHal.get()) {
2943 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2944 } else {
2945 return -ENODEV;
2946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947}
2948
Glenn Kastenf587ba52012-01-26 16:25:10 -08002949status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950{
2951 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002952 if (mEffectsFactoryHal.get()) {
2953 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2954 } else {
2955 return -ENODEV;
2956 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002957}
2958
Glenn Kasten5e92a782012-01-30 07:40:52 -08002959status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002960 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961{
2962 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002963 if (mEffectsFactoryHal.get()) {
2964 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2965 } else {
2966 return -ENODEV;
2967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968}
2969
2970
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002971sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 effect_descriptor_t *pDesc,
2973 const sp<IEffectClient>& effectClient,
2974 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002975 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002976 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002977 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002978 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 status_t *status,
2980 int *id,
2981 int *enabled)
2982{
2983 status_t lStatus = NO_ERROR;
2984 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986
Eric Laurentb6436272016-12-07 19:24:50 -08002987 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2988 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2989 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2990 ALOGW_IF(pid != -1 && pid != callingPid,
2991 "%s uid %d pid %d tried to pass itself off as pid %d",
2992 __func__, callingUid, callingPid, pid);
2993 pid = callingPid;
2994 }
2995
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002996 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2997 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998
2999 if (pDesc == NULL) {
3000 lStatus = BAD_VALUE;
3001 goto Exit;
3002 }
3003
Eric Laurent84e9a102010-09-23 16:10:16 -07003004 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003005 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003006 lStatus = PERMISSION_DENIED;
3007 goto Exit;
3008 }
3009
Dima Zavinfce7a472011-04-19 22:30:36 -07003010 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07003011 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08003012 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003013 lStatus = PERMISSION_DENIED;
3014 goto Exit;
3015 }
3016
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003017 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003018 lStatus = NO_INIT;
3019 goto Exit;
3020 }
3021
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003023 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003025 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003027 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028 goto Exit;
3029 }
3030 } else {
3031 // if uuid is not specified, look for an available implementation
3032 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003033 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003034 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 lStatus = BAD_VALUE;
3036 goto Exit;
3037 }
3038 uint32_t numEffects = 0;
3039 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003040 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 bool found = false;
3042
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003043 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003045 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 goto Exit;
3047 }
3048 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003049 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003051 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 continue;
3053 }
3054 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3055 // If matching type found save effect descriptor. If the session is
3056 // 0 and the effect is not auxiliary, continue enumeration in case
3057 // an auxiliary version of this effect type is available
3058 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003059 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003060 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3062 break;
3063 }
3064 }
3065 }
3066 if (!found) {
3067 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003068 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 goto Exit;
3070 }
3071 // For same effect type, chose auxiliary version over insert version if
3072 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003073 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003075 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 }
3077 }
3078
3079 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003080 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3082 lStatus = INVALID_OPERATION;
3083 goto Exit;
3084 }
3085
Eric Laurent59255e42011-07-27 19:49:51 -07003086 // check recording permission for visualizer
3087 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003088 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003089 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003090 lStatus = PERMISSION_DENIED;
3091 goto Exit;
3092 }
3093
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003095 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003096 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003097 // if the output returned by getOutputForEffect() is removed before we lock the
3098 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3099 // and we will exit safely
3100 io = AudioSystem::getOutputForEffect(&desc);
3101 ALOGV("createEffect got output %d", io);
3102 }
3103
3104 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105
3106 // If output is not specified try to find a matching audio session ID in one of the
3107 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003108 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3109 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003110 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003111 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003112 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3113 // output must be specified by AudioPolicyManager when using session
3114 // AUDIO_SESSION_OUTPUT_STAGE
3115 lStatus = BAD_VALUE;
3116 goto Exit;
3117 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003118 // look for the thread where the specified audio session is present
3119 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3120 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3121 io = mPlaybackThreads.keyAt(i);
3122 break;
3123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003125 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003126 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3127 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3128 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003129 break;
3130 }
3131 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003132 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003133 if (io == AUDIO_IO_HANDLE_NONE) {
3134 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3135 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3136 io = mMmapThreads.keyAt(i);
3137 break;
3138 }
3139 }
3140 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003141 // If no output thread contains the requested session ID, default to
3142 // first output. The effect chain will be moved to the correct output
3143 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003144 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003145 io = mPlaybackThreads.keyAt(0);
3146 }
Steve Block3856b092011-10-20 11:56:00 +01003147 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003148 }
3149 ThreadBase *thread = checkRecordThread_l(io);
3150 if (thread == NULL) {
3151 thread = checkPlaybackThread_l(io);
3152 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003153 thread = checkMmapThread_l(io);
3154 if (thread == NULL) {
3155 ALOGE("createEffect() unknown output thread");
3156 lStatus = BAD_VALUE;
3157 goto Exit;
3158 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003159 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003160 } else {
3161 // Check if one effect chain was awaiting for an effect to be created on this
3162 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003163 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003164 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003165 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003166 thread->addEffectChain_l(chain);
3167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003169
Eric Laurent021cf962014-05-13 10:18:14 -07003170 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003172 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003173 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003174 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003175 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003176 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003177 // remove local strong reference to Client with mClientLock held
3178 Mutex::Autolock _cl(mClientLock);
3179 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003180 } else {
3181 // handle must be valid here, but check again to be safe.
3182 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 }
3185
haobo101735295ff7b0d2017-03-17 17:44:03 +08003186 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3187 // handle must be cleared outside lock.
3188 handle.clear();
3189 }
3190
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003192 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 return handle;
3194}
3195
Glenn Kastend848eb42016-03-08 13:42:11 -08003196status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003197 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003198{
Steve Block3856b092011-10-20 11:56:00 +01003199 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003200 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003201 Mutex::Autolock _l(mLock);
3202 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003203 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003204 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 }
Eric Laurentde070132010-07-13 04:45:46 -07003206 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3207 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003208 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003209 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210 }
Eric Laurentde070132010-07-13 04:45:46 -07003211 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3212 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003213 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003214 return BAD_VALUE;
3215 }
3216
3217 Mutex::Autolock _dl(dstThread->mLock);
3218 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003219 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220}
3221
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003222// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003223status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003224 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003225 AudioFlinger::PlaybackThread *dstThread,
3226 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003227{
Steve Block3856b092011-10-20 11:56:00 +01003228 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003229 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003230
Eric Laurent59255e42011-07-27 19:49:51 -07003231 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003232 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003233 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003234 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003235 return INVALID_OPERATION;
3236 }
3237
Eric Laurent4c415062016-06-17 16:14:16 -07003238 // Check whether the destination thread and all effects in the chain are compatible
3239 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003240 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003241 " destination thread %p is not compatible with effects in the chain",
3242 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003243 return INVALID_OPERATION;
3244 }
3245
Eric Laurent39e94f82010-07-28 01:32:47 -07003246 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003247 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003248 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003249 // removed.
3250 srcThread->removeEffectChain_l(chain);
3251
3252 // transfer all effects one by one so that new effect chain is created on new thread with
3253 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003254 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003255 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003256 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003257 Vector< sp<EffectModule> > removed;
3258 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003259 while (effect != 0) {
3260 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003261 removed.add(effect);
3262 status = dstThread->addEffect_l(effect);
3263 if (status != NO_ERROR) {
3264 break;
3265 }
Eric Laurentec35a142011-10-05 17:42:25 -07003266 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3267 if (effect->state() == EffectModule::ACTIVE ||
3268 effect->state() == EffectModule::STOPPING) {
3269 effect->start();
3270 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003271 // if the move request is not received from audio policy manager, the effect must be
3272 // re-registered with the new strategy and output
3273 if (dstChain == 0) {
3274 dstChain = effect->chain().promote();
3275 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003276 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003277 status = NO_INIT;
3278 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003279 }
3280 strategy = dstChain->strategy();
3281 }
3282 if (reRegister) {
3283 AudioSystem::unregisterEffect(effect->id());
3284 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003285 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003286 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003287 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003288 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003289 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003290 }
Eric Laurentde070132010-07-13 04:45:46 -07003291 effect = chain->getEffectFromId_l(0);
3292 }
3293
Eric Laurent5baf2af2013-09-12 17:37:00 -07003294 if (status != NO_ERROR) {
3295 for (size_t i = 0; i < removed.size(); i++) {
3296 srcThread->addEffect_l(removed[i]);
3297 if (dstChain != 0 && reRegister) {
3298 AudioSystem::unregisterEffect(removed[i]->id());
3299 AudioSystem::registerEffect(&removed[i]->desc(),
3300 srcThread->id(),
3301 strategy,
3302 sessionId,
3303 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003304 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003305 }
3306 }
3307 }
3308
3309 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310}
3311
Eric Laurent5baf2af2013-09-12 17:37:00 -07003312bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003313{
3314 if (mGlobalEffectEnableTime != 0 &&
3315 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3316 return true;
3317 }
3318
3319 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3320 sp<EffectChain> ec =
3321 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003322 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003323 return true;
3324 }
3325 }
3326 return false;
3327}
3328
Eric Laurent5baf2af2013-09-12 17:37:00 -07003329void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003330{
3331 Mutex::Autolock _l(mLock);
3332
3333 mGlobalEffectEnableTime = systemTime();
3334
3335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3336 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3337 if (t->mType == ThreadBase::OFFLOAD) {
3338 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3339 }
3340 }
3341
3342}
3343
Eric Laurentaaa44472014-09-12 17:41:50 -07003344status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3345{
Eric Laurentd8365c52017-07-16 15:27:05 -07003346 // clear possible suspended state before parking the chain so that it starts in default state
3347 // when attached to a new record thread
3348 chain->setEffectSuspended_l(FX_IID_AEC, false);
3349 chain->setEffectSuspended_l(FX_IID_NS, false);
3350
Glenn Kastend848eb42016-03-08 13:42:11 -08003351 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003352 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003353 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003354 if (index >= 0) {
3355 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3356 return ALREADY_EXISTS;
3357 }
3358 mOrphanEffectChains.add(session, chain);
3359 return NO_ERROR;
3360}
3361
3362sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3363{
3364 sp<EffectChain> chain;
3365 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003366 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003367 if (index >= 0) {
3368 chain = mOrphanEffectChains.valueAt(index);
3369 mOrphanEffectChains.removeItemsAt(index);
3370 }
3371 return chain;
3372}
3373
3374bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3375{
3376 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003377 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003378 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003379 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003380 if (index >= 0) {
3381 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003382 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003383 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003384 mOrphanEffectChains.removeItemsAt(index);
3385 }
3386 return true;
3387 }
3388 return false;
3389}
3390
3391
Glenn Kastenda6ef132013-01-10 12:31:01 -08003392struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003393#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3394 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003395};
3396
3397int comparEntry(const void *p1, const void *p2)
3398{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003399 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003400}
3401
Glenn Kasten46909e72013-02-26 09:20:22 -08003402#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003403void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404{
Eric Laurent81784c32012-11-19 14:55:58 -08003405 NBAIO_Source *teeSource = source.get();
3406 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003407 // .wav rotation
3408 // There is a benign race condition if 2 threads call this simultaneously.
3409 // They would both traverse the directory, but the result would simply be
3410 // failures at unlink() which are ignored. It's also unlikely since
3411 // normally dumpsys is only done by bugreport or from the command line.
Andy Hungb1fe6e12018-04-19 19:20:00 -07003412 char teePath[PATH_MAX] = "/data/misc/audioserver";
Glenn Kastenda6ef132013-01-10 12:31:01 -08003413 size_t teePathLen = strlen(teePath);
3414 DIR *dir = opendir(teePath);
3415 teePath[teePathLen++] = '/';
3416 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003417#define TEE_MAX_SORT 20 // number of entries to sort
3418#define TEE_MAX_KEEP 10 // number of entries to keep
3419 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003420 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003421 while (entryCount < TEE_MAX_SORT) {
Andy Hungb1fe6e12018-04-19 19:20:00 -07003422 errno = 0; // clear errno before readdir() to track potential errors.
3423 const struct dirent *result = readdir(dir);
3424 if (result == nullptr) {
3425 ALOGW_IF(errno != 0, "tee readdir() failure %s", strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003426 break;
3427 }
3428 // ignore non .wav file entries
Andy Hungb1fe6e12018-04-19 19:20:00 -07003429 const size_t nameLen = strlen(result->d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003430 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Andy Hungb1fe6e12018-04-19 19:20:00 -07003431 strcmp(&result->d_name[nameLen - 4], ".wav")) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003432 continue;
3433 }
Andy Hungb1fe6e12018-04-19 19:20:00 -07003434 (void)audio_utils_strlcpy(entries[entryCount++].mFileName, result->d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003435 }
3436 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003437 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003438 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003439 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3440 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003441 (void) unlink(teePath);
3442 }
3443 }
3444 } else {
3445 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003446 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003447 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003448 }
3449 }
Eric Laurent81784c32012-11-19 14:55:58 -08003450 char teeTime[16];
3451 struct timeval tv;
3452 gettimeofday(&tv, NULL);
3453 struct tm tm;
3454 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003455 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003456 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3457 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003458 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3459 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003460 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003461 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003462 char wavHeader[44];
3463 memcpy(wavHeader,
3464 "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",
3465 sizeof(wavHeader));
3466 NBAIO_Format format = teeSource->format();
3467 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003468 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003469 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003470 wavHeader[22] = channelCount; // number of channels
3471 wavHeader[24] = sampleRate; // sample rate
3472 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003473 wavHeader[32] = frameSize; // block alignment
3474 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003475 write(teeFd, wavHeader, sizeof(wavHeader));
3476 size_t total = 0;
3477 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003478#define TEE_SINK_READ 1024 // frames per I/O operation
3479 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003480 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003481 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003482 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003483 bool wasFirstRead = firstRead;
3484 firstRead = false;
3485 if (actual <= 0) {
3486 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3487 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003488 }
Eric Laurent81784c32012-11-19 14:55:58 -08003489 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003490 }
Eric Laurent81784c32012-11-19 14:55:58 -08003491 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003492 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003493 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003494 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003495 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003496 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003497 uint32_t temp = 44 + total * frameSize - 8;
3498 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003499 write(teeFd, &temp, sizeof(temp));
3500 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003501 temp = total * frameSize;
3502 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003503 write(teeFd, &temp, sizeof(temp));
3504 close(teeFd);
Glenn Kasten9e756632017-10-03 13:01:09 -07003505 // TODO Should create file with temporary name and then rename to final if non-empty.
3506 if (total > 0) {
3507 if (fd >= 0) {
3508 dprintf(fd, "tee copied to %s\n", teePath);
3509 }
3510 } else {
3511 unlink(teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003512 }
Eric Laurent59255e42011-07-27 19:49:51 -07003513 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003514 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003515 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003516 }
Eric Laurent59255e42011-07-27 19:49:51 -07003517 }
3518 }
3519}
Glenn Kasten46909e72013-02-26 09:20:22 -08003520#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003521
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522// ----------------------------------------------------------------------------
3523
3524status_t AudioFlinger::onTransact(
3525 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3526{
3527 return BnAudioFlinger::onTransact(code, data, reply, flags);
3528}
3529
Glenn Kasten63238ef2015-03-02 15:50:29 -08003530} // namespace android