blob: 706837735537bab1c45ccbc2df337a2a2c02a8a5 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
Eric Laurentf1047e82018-04-16 19:18:20 -070031#include <cutils/multiuser.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070033#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070035#include <media/audiohal/DeviceHalInterface.h>
36#include <media/audiohal/DevicesFactoryHalInterface.h>
37#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070038#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070040#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <utils/String16.h>
42#include <utils/threads.h>
43
Steven Morelandf0c02ce2018-02-23 14:53:55 -080044#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_visualizer.h>
55#include <system/audio_effects/effect_ns.h>
56#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
Andy Hung7ad78182018-05-10 20:54:29 -070059#include <audio_utils/string.h>
Glenn Kasten3b21c502011-12-15 09:52:39 -080060
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070067#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080074#include "TypedLogger.h"
75
Mathias Agopian65ab4712010-07-14 17:59:35 -070076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
John Grossman1c345192012-03-27 14:00:17 -070078// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
Eric Laurentde070132010-07-13 04:45:46 -070090
Mathias Agopian65ab4712010-07-14 17:59:35 -070091namespace android {
92
Glenn Kastenec1d6b52011-12-12 09:04:45 -080093static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
94static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070095static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070096static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten58912562012-04-03 10:45:00 -070098
John Grossman4ff14ba2012-02-08 16:37:41 -080099nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700102
Eric Laurentfc235202016-12-20 18:48:17 -0800103
Glenn Kasten46909e72013-02-26 09:20:22 -0800104#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800105bool AudioFlinger::mTeeSinkInputEnabled = false;
106bool AudioFlinger::mTeeSinkOutputEnabled = false;
107bool AudioFlinger::mTeeSinkTrackEnabled = false;
108
109size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
110size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
111size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800112#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800113
Eric Laurent813e2a72013-08-31 12:59:48 -0700114// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
115// we define a minimum time during which a global effect is considered enabled.
116static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
117
Eric Laurentfc235202016-12-20 18:48:17 -0800118Mutex gLock;
119wp<AudioFlinger> gAudioFlinger;
120
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700121// Keep a strong reference to media.log service around forever.
122// The service is within our parent process so it can never die in a way that we could observe.
123// These two variables are const after initialization.
124static sp<IBinder> sMediaLogServiceAsBinder;
125static sp<IMediaLogService> sMediaLogService;
126
127static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
128
129static void sMediaLogInit()
130{
131 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
132 if (sMediaLogServiceAsBinder != 0) {
133 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
134 }
135}
136
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137// ----------------------------------------------------------------------------
138
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700139std::string formatToString(audio_format_t format) {
140 std::string result;
141 FormatConverter::toString(format, result);
142 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
147AudioFlinger::AudioFlinger()
148 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800149 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800150 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800151 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700152 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700155 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800156 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700157 mBtNrecIsOff(false),
158 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700159 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800160 mTotalMemory(0),
161 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700162 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700163 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700164 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700166 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
167 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
168 // zero ID has a special meaning, so unavailable
169 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
170 }
171
Glenn Kasten949a9262013-04-16 12:35:20 -0700172 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800173 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800174 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800175 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
176 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700177 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800178 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700179
Wei Jia3f273d12015-11-24 09:06:49 -0800180 // reset battery stats.
181 // if the audio service has crashed, battery stats could be left
182 // in bad state, reset the state upon service start.
183 BatteryNotifier::getInstance().noteResetAudio();
184
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700185 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700186 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
187
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800188 mMediaLogNotifier->run("MediaLogNotifier");
189
Glenn Kasten46909e72013-02-26 09:20:22 -0800190#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800191 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800192 (void) property_get("ro.debuggable", value, "0");
193 int debuggable = atoi(value);
194 int teeEnabled = 0;
195 if (debuggable) {
196 (void) property_get("af.tee", value, "0");
197 teeEnabled = atoi(value);
198 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800199 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700200 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700202 }
203 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800204 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700205 }
206 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800207 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700208 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800209#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700210}
211
212void AudioFlinger::onFirstRef()
213{
Eric Laurent93575202011-01-18 18:39:02 -0800214 Mutex::Autolock _l(mLock);
215
Dima Zavin799a70e2011-04-18 16:57:27 -0700216 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800217 char val_str[PROPERTY_VALUE_MAX] = { 0 };
218 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
219 uint32_t int_val;
220 if (1 == sscanf(val_str, "%u", &int_val)) {
221 mStandbyTimeInNsecs = milliseconds(int_val);
222 ALOGI("Using %u mSec as standby time.", int_val);
223 } else {
224 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
225 ALOGI("Using default %u mSec as standby time.",
226 (uint32_t)(mStandbyTimeInNsecs / 1000000));
227 }
228 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229
Eric Laurenta4c5a552012-03-29 10:12:40 -0700230 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800231
232 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233}
234
235AudioFlinger::~AudioFlinger()
236{
237 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700238 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700239 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240 }
241 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700242 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700243 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700245
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800246 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
247 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700248 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700250
251 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700252 if (sMediaLogService != 0) {
253 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
254 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
255 mUnregisteredWriters.pop();
256 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700257 }
258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259}
260
Eric Laurentfc235202016-12-20 18:48:17 -0800261//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800262__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800263status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
264 const audio_attributes_t *attr,
265 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700266 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800267 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800268 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800269 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700270 sp<MmapStreamInterface>& interface,
271 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800272{
273 sp<AudioFlinger> af;
274 {
275 Mutex::Autolock _l(gLock);
276 af = gAudioFlinger.promote();
277 }
278 status_t ret = NO_INIT;
279 if (af != 0) {
280 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800281 direction, attr, config, client, deviceId,
282 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800283 }
284 return ret;
285}
286
Eric Laurent6acd1d42017-01-04 14:23:29 -0800287status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
288 const audio_attributes_t *attr,
289 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700290 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800291 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800292 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800293 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700294 sp<MmapStreamInterface>& interface,
295 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800296{
297 status_t ret = initCheck();
298 if (ret != NO_ERROR) {
299 return ret;
300 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800301 audio_session_t actualSessionId = *sessionId;
302 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
303 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
304 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800305 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700306 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800307 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
308 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
309 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
310 fullConfig.sample_rate = config->sample_rate;
311 fullConfig.channel_mask = config->channel_mask;
312 fullConfig.format = config->format;
313 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800314 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200315 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800316 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800317 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
318 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700319 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800320 } else {
321 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800322 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800323 client.clientPid,
324 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800325 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800326 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700327 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800328 }
329 if (ret != NO_ERROR) {
330 return ret;
331 }
332
333 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
334 // audio policy manager and we can retrieve it
335 sp<MmapThread> thread = mMmapThreads.valueFor(io);
336 if (thread != 0) {
337 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800338 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700339 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800340 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800341 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700342 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800343 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700344 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800345 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700346 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800347 ret = NO_INIT;
348 }
349
350 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
351
Eric Laurentfc235202016-12-20 18:48:17 -0800352 return ret;
353}
354
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355static const char * const audio_interfaces[] = {
356 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
357 AUDIO_HARDWARE_MODULE_ID_A2DP,
358 AUDIO_HARDWARE_MODULE_ID_USB,
359};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700360
Phil Burk062e67a2015-02-11 13:40:50 -0800361AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700362 audio_module_handle_t module,
363 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700364{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700365 // if module is 0, the request comes from an old policy manager and we should load
366 // well known modules
367 if (module == 0) {
368 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700369 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700370 loadHwModule_l(audio_interfaces[i]);
371 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700372 // then try to find a module supporting the requested device.
373 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
374 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700375 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
376 uint32_t supportedDevices;
377 if (dev->getSupportedDevices(&supportedDevices) == OK &&
378 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700379 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700380 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700381 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700382 } else {
383 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700384 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
385 if (audioHwDevice != NULL) {
386 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700387 }
388 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700389
Dima Zavin799a70e2011-04-18 16:57:27 -0700390 return NULL;
391}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392
Glenn Kasten0f11b512014-01-31 16:18:54 -0800393void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700394{
395 const size_t SIZE = 256;
396 char buffer[SIZE];
397 String8 result;
398
399 result.append("Clients:\n");
400 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800401 sp<Client> client = mClients.valueAt(i).promote();
402 if (client != 0) {
403 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
404 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 }
406 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700407
Eric Laurentd1b28d42013-09-18 18:47:13 -0700408 result.append("Notification Clients:\n");
409 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
410 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
411 result.append(buffer);
412 }
413
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700414 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800415 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700416 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
417 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800418 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700419 result.append(buffer);
420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422}
423
424
Glenn Kasten0f11b512014-01-31 16:18:54 -0800425void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426{
427 const size_t SIZE = 256;
428 char buffer[SIZE];
429 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800430 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431
John Grossman4ff14ba2012-02-08 16:37:41 -0800432 snprintf(buffer, SIZE, "Hardware status: %d\n"
433 "Standby Time mSec: %u\n",
434 hardwareStatus,
435 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 result.append(buffer);
437 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438}
439
Glenn Kasten0f11b512014-01-31 16:18:54 -0800440void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441{
442 const size_t SIZE = 256;
443 char buffer[SIZE];
444 String8 result;
445 snprintf(buffer, SIZE, "Permission Denial: "
446 "can't dump AudioFlinger from pid=%d, uid=%d\n",
447 IPCThreadState::self()->getCallingPid(),
448 IPCThreadState::self()->getCallingUid());
449 result.append(buffer);
450 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451}
452
Eric Laurent81784c32012-11-19 14:55:58 -0800453bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454{
455 bool locked = false;
456 for (int i = 0; i < kDumpLockRetries; ++i) {
457 if (mutex.tryLock() == NO_ERROR) {
458 locked = true;
459 break;
460 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800461 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 }
463 return locked;
464}
465
466status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
467{
Glenn Kasten44deb052012-02-05 18:09:08 -0800468 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 dumpPermissionDenial(fd, args);
470 } else {
471 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800472 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 if (!hardwareLocked) {
474 String8 result(kHardwareLockedString);
475 write(fd, result.string(), result.size());
476 } else {
477 mHardwareLock.unlock();
478 }
479
Eric Laurent81784c32012-11-19 14:55:58 -0800480 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481
482 // failed to lock - AudioFlinger is probably deadlocked
483 if (!locked) {
484 String8 result(kDeadlockedString);
485 write(fd, result.string(), result.size());
486 }
487
Eric Laurent021cf962014-05-13 10:18:14 -0700488 bool clientLocked = dumpTryLock(mClientLock);
489 if (!clientLocked) {
490 String8 result(kClientLockedString);
491 write(fd, result.string(), result.size());
492 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700493
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700494 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700495 mEffectsFactoryHal->dumpEffects(fd);
496 } else {
497 String8 result(kNoEffectsFactory);
498 write(fd, result.string(), result.size());
499 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700500
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700502 if (clientLocked) {
503 mClientLock.unlock();
504 }
505
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 dumpInternals(fd, args);
507
508 // dump playback threads
509 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
510 mPlaybackThreads.valueAt(i)->dump(fd, args);
511 }
512
513 // dump record threads
514 for (size_t i = 0; i < mRecordThreads.size(); i++) {
515 mRecordThreads.valueAt(i)->dump(fd, args);
516 }
517
Eric Laurent6acd1d42017-01-04 14:23:29 -0800518 // dump mmap threads
519 for (size_t i = 0; i < mMmapThreads.size(); i++) {
520 mMmapThreads.valueAt(i)->dump(fd, args);
521 }
522
Eric Laurentaaa44472014-09-12 17:41:50 -0700523 // dump orphan effect chains
524 if (mOrphanEffectChains.size() != 0) {
525 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
526 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
527 mOrphanEffectChains.valueAt(i)->dump(fd, args);
528 }
529 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700530 // dump all hardware devs
531 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700532 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
533 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700535
Mikhail Naganov201369b2018-05-16 16:52:32 -0700536 mPatchPanel.dump(fd);
537
Glenn Kasten46909e72013-02-26 09:20:22 -0800538#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700539 // dump the serially shared record tee sink
540 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700541 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700542 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800543#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700544
rago3bd1c872016-09-26 12:58:14 -0700545 BUFLOG_RESET;
546
Glenn Kastend65d73c2012-06-22 17:21:07 -0700547 if (locked) {
548 mLock.unlock();
549 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800550
551 // append a copy of media.log here by forwarding fd to it, but don't attempt
552 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700553 if (sMediaLogServiceAsBinder != 0) {
554 dprintf(fd, "\nmedia.log:\n");
555 Vector<String16> args;
556 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800557 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700558
559 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700560 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700561 bool unreachableMemory = false;
562 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700563 if (arg == String16("-m")) {
564 dumpMem = true;
565 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700566 unreachableMemory = true;
567 }
568 }
569
Andy Hung07b745e2016-05-23 16:21:07 -0700570 if (dumpMem) {
571 dprintf(fd, "\nDumping memory:\n");
572 std::string s = dumpMemoryAddresses(100 /* limit */);
573 write(fd, s.c_str(), s.size());
574 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700575 if (unreachableMemory) {
576 dprintf(fd, "\nDumping unreachable memory:\n");
577 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700578 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700579 write(fd, s.c_str(), s.size());
580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 }
582 return NO_ERROR;
583}
584
Eric Laurent021cf962014-05-13 10:18:14 -0700585sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800586{
Eric Laurent021cf962014-05-13 10:18:14 -0700587 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800588 // If pid is already in the mClients wp<> map, then use that entry
589 // (for which promote() is always != 0), otherwise create a new entry and Client.
590 sp<Client> client = mClients.valueFor(pid).promote();
591 if (client == 0) {
592 client = new Client(this, pid);
593 mClients.add(pid, client);
594 }
595
596 return client;
597}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598
Glenn Kasten9e58b552013-01-18 15:09:48 -0800599sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
600{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700601 // If there is no memory allocated for logs, return a dummy writer that does nothing.
602 // Similarly if we can't contact the media.log service, also return a dummy writer.
603 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800604 return new NBLog::Writer();
605 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700606 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
607 // If allocation fails, consult the vector of previously unregistered writers
608 // and garbage-collect one or more them until an allocation succeeds
609 if (shared == 0) {
610 Mutex::Autolock _l(mUnregisteredWritersLock);
611 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
612 {
613 // Pick the oldest stale writer to garbage-collect
614 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
615 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700616 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700617 // Now the media.log remote reference to IMemory is gone. When our last local
618 // reference to IMemory also drops to zero at end of this block,
619 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
620 }
621 // Re-attempt the allocation
622 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
623 if (shared != 0) {
624 goto success;
625 }
626 }
627 // Even after garbage-collecting all old writers, there is still not enough memory,
628 // so return a dummy writer
629 return new NBLog::Writer();
630 }
631success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800632 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
633 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
634 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700635 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800636 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800637}
638
639void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
640{
Glenn Kasten685ef092013-02-04 08:15:34 -0800641 if (writer == 0) {
642 return;
643 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800644 sp<IMemory> iMemory(writer->getIMemory());
645 if (iMemory == 0) {
646 return;
647 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700648 // Rather than removing the writer immediately, append it to a queue of old writers to
649 // be garbage-collected later. This allows us to continue to view old logs for a while.
650 Mutex::Autolock _l(mUnregisteredWritersLock);
651 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800652}
653
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654// IAudioFlinger interface
655
Eric Laurent21da6472017-11-09 16:29:26 -0800656sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
657 CreateTrackOutput& output,
658 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659{
660 sp<PlaybackThread::Track> track;
661 sp<TrackHandle> trackHandle;
662 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800664 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800665 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666
Eric Laurent21da6472017-11-09 16:29:26 -0800667 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700668 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800669 uid_t clientUid = input.clientInfo.clientUid;
670 if (!isTrustedCallingUid(callingUid)) {
671 ALOGW_IF(clientUid != callingUid,
672 "%s uid %d tried to pass itself off as %d",
673 __FUNCTION__, callingUid, clientUid);
674 clientUid = callingUid;
675 updatePid = true;
676 }
677 pid_t clientPid = input.clientInfo.clientPid;
678 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700679 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800680 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700681 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800682 __func__, callingUid, callingPid, clientPid);
683 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700684 }
685
Eric Laurent21da6472017-11-09 16:29:26 -0800686 audio_session_t sessionId = input.sessionId;
687 if (sessionId == AUDIO_SESSION_ALLOCATE) {
688 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800689 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
690 lStatus = BAD_VALUE;
691 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800692 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800693
Eric Laurent21da6472017-11-09 16:29:26 -0800694 output.sessionId = sessionId;
695 output.outputId = AUDIO_IO_HANDLE_NONE;
696 output.selectedDeviceId = input.selectedDeviceId;
697
698 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200699 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800700 &output.selectedDeviceId, &portId);
701
702 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
703 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
704 goto Exit;
705 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800706 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
707 // but if someone uses binder directly they could bypass that and cause us to crash
708 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000709 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710 lStatus = BAD_VALUE;
711 goto Exit;
712 }
713
Glenn Kasten53b5d092014-02-05 10:00:23 -0800714 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800715 if (!audio_is_output_channel(input.config.channel_mask)) {
716 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800717 lStatus = BAD_VALUE;
718 goto Exit;
719 }
720
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700721 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800722 if (!audio_is_valid_format(input.config.format)) {
723 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700724 lStatus = BAD_VALUE;
725 goto Exit;
726 }
727
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728 {
729 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800730 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800732 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733 lStatus = BAD_VALUE;
734 goto Exit;
735 }
736
Eric Laurent21da6472017-11-09 16:29:26 -0800737 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738
Glenn Kastene848bd92014-03-13 15:00:32 -0700739 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800740 // check if an effect chain with the same session ID is present on another
741 // output thread and move it here.
742 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
743 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
744 if (mPlaybackThreads.keyAt(i) != output.outputId) {
745 uint32_t sessions = t->hasAudioSession(sessionId);
746 if (sessions & ThreadBase::EFFECT_SESSION) {
747 effectThread = t.get();
748 break;
Eric Laurentde070132010-07-13 04:45:46 -0700749 }
750 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751 }
Eric Laurent21da6472017-11-09 16:29:26 -0800752 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753
Eric Laurent21da6472017-11-09 16:29:26 -0800754 output.sampleRate = input.config.sample_rate;
755 output.frameCount = input.frameCount;
756 output.notificationFrameCount = input.notificationFrameCount;
757 output.flags = input.flags;
758
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700759 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
760 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800761 &output.frameCount, &output.notificationFrameCount,
762 input.notificationsPerBuffer, input.speed,
763 input.sharedBuffer, sessionId, &output.flags,
764 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800765 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700766 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700767
Eric Laurent21da6472017-11-09 16:29:26 -0800768 output.afFrameCount = thread->frameCount();
769 output.afSampleRate = thread->sampleRate();
770 output.afLatencyMs = thread->latency();
771
Eric Laurent39e94f82010-07-28 01:32:47 -0700772 // move effect chain to this output thread if an effect on same session was waiting
773 // for a track to be created
774 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700775 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700776 Mutex::Autolock _dl(thread->mLock);
777 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800778 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700779 }
Eric Laurenta011e352012-03-29 15:51:43 -0700780
781 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700782 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800783 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700784 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700785 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700786 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700787 } else {
788 mPendingSyncEvents[i]->cancel();
789 }
Eric Laurenta011e352012-03-29 15:51:43 -0700790 mPendingSyncEvents.removeAt(i);
791 i--;
792 }
793 }
794 }
Glenn Kastene198c362013-08-13 09:13:36 -0700795
Eric Laurent21da6472017-11-09 16:29:26 -0800796 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 }
Glenn Kastene198c362013-08-13 09:13:36 -0700798
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700799 if (lStatus != NO_ERROR) {
800 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700801 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700802 // Don't hold mClientLock when releasing the reference on the track as the
803 // destructor will acquire it.
804 {
805 Mutex::Autolock _cl(mClientLock);
806 client.clear();
807 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700809 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
811
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700812 // return handle to client
813 trackHandle = new TrackHandle(track);
814
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800816 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
817 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
818 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700819 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 return trackHandle;
821}
822
Glenn Kasten2c073da2016-02-26 09:14:08 -0800823uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824{
825 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800826 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800828 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 return 0;
830 }
831 return thread->sampleRate();
832}
833
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800834audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835{
836 Mutex::Autolock _l(mLock);
837 PlaybackThread *thread = checkPlaybackThread_l(output);
838 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000839 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800840 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841 }
842 return thread->format();
843}
844
Glenn Kasten2c073da2016-02-26 09:14:08 -0800845size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846{
847 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800848 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800850 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 return 0;
852 }
Glenn Kasten58912562012-04-03 10:45:00 -0700853 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
854 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855 return thread->frameCount();
856}
857
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700858size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
859{
860 Mutex::Autolock _l(mLock);
861 ThreadBase *thread = checkThread_l(ioHandle);
862 if (thread == NULL) {
863 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
864 return 0;
865 }
866 return thread->frameCountHAL();
867}
868
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800869uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870{
871 Mutex::Autolock _l(mLock);
872 PlaybackThread *thread = checkPlaybackThread_l(output);
873 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800874 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 return 0;
876 }
877 return thread->latency();
878}
879
880status_t AudioFlinger::setMasterVolume(float value)
881{
Eric Laurenta1884f92011-08-23 08:25:03 -0700882 status_t ret = initCheck();
883 if (ret != NO_ERROR) {
884 return ret;
885 }
886
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887 // check calling permissions
888 if (!settingsAllowed()) {
889 return PERMISSION_DENIED;
890 }
891
Eric Laurenta4c5a552012-03-29 10:12:40 -0700892 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700893 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700894
John Grossmanee578c02012-07-23 17:05:46 -0700895 // Set master volume in the HALs which support it.
896 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
897 AutoMutex lock(mHardwareLock);
898 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800899
John Grossmanee578c02012-07-23 17:05:46 -0700900 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
901 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700902 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800903 }
John Grossmanee578c02012-07-23 17:05:46 -0700904 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906
John Grossmanee578c02012-07-23 17:05:46 -0700907 // Now set the master volume in each playback thread. Playback threads
908 // assigned to HALs which do not have master volume support will apply
909 // master volume during the mix operation. Threads with HALs which do
910 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700911 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
912 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
913 continue;
914 }
John Grossmanee578c02012-07-23 17:05:46 -0700915 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917
918 return NO_ERROR;
919}
920
Glenn Kastenf78aee72012-01-04 11:00:47 -0800921status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922{
Eric Laurenta1884f92011-08-23 08:25:03 -0700923 status_t ret = initCheck();
924 if (ret != NO_ERROR) {
925 return ret;
926 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927
928 // check calling permissions
929 if (!settingsAllowed()) {
930 return PERMISSION_DENIED;
931 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800932 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000933 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934 return BAD_VALUE;
935 }
936
937 { // scope for the lock
938 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700939 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700941 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 mHardwareStatus = AUDIO_HW_IDLE;
943 }
944
945 if (NO_ERROR == ret) {
946 Mutex::Autolock _l(mLock);
947 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800948 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700949 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 }
951
952 return ret;
953}
954
955status_t AudioFlinger::setMicMute(bool state)
956{
Eric Laurenta1884f92011-08-23 08:25:03 -0700957 status_t ret = initCheck();
958 if (ret != NO_ERROR) {
959 return ret;
960 }
961
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962 // check calling permissions
963 if (!settingsAllowed()) {
964 return PERMISSION_DENIED;
965 }
966
967 AutoMutex lock(mHardwareLock);
968 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700969 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700970 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
971 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700972 if (result != NO_ERROR) {
973 ret = result;
974 }
975 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 mHardwareStatus = AUDIO_HW_IDLE;
977 return ret;
978}
979
980bool AudioFlinger::getMicMute() const
981{
Eric Laurenta1884f92011-08-23 08:25:03 -0700982 status_t ret = initCheck();
983 if (ret != NO_ERROR) {
984 return false;
985 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800986 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700987 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800988 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800990 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700991 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
992 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800993 if (result == NO_ERROR) {
994 mute = mute && state;
995 }
996 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800998
999 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000}
1001
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001002void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1003{
1004 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1005
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001006 AutoMutex lock(mLock);
1007 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001008 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1009 }
1010 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1011 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001012 }
1013}
1014
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015status_t AudioFlinger::setMasterMute(bool muted)
1016{
John Grossmand8f178d2012-07-20 14:51:35 -07001017 status_t ret = initCheck();
1018 if (ret != NO_ERROR) {
1019 return ret;
1020 }
1021
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 // check calling permissions
1023 if (!settingsAllowed()) {
1024 return PERMISSION_DENIED;
1025 }
1026
John Grossmanee578c02012-07-23 17:05:46 -07001027 Mutex::Autolock _l(mLock);
1028 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001029
John Grossmanee578c02012-07-23 17:05:46 -07001030 // Set master mute in the HALs which support it.
1031 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1032 AutoMutex lock(mHardwareLock);
1033 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001034
John Grossmanee578c02012-07-23 17:05:46 -07001035 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1036 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001037 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001038 }
John Grossmanee578c02012-07-23 17:05:46 -07001039 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001040 }
1041
John Grossmanee578c02012-07-23 17:05:46 -07001042 // Now set the master mute in each playback thread. Playback threads
1043 // assigned to HALs which do not have master mute support will apply master
1044 // mute during the mix operation. Threads with HALs which do support master
1045 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001046 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1047 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1048 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050
1051 return NO_ERROR;
1052}
1053
1054float AudioFlinger::masterVolume() const
1055{
Glenn Kasten98067102011-12-13 11:47:54 -08001056 Mutex::Autolock _l(mLock);
1057 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058}
1059
1060bool AudioFlinger::masterMute() const
1061{
Glenn Kasten98067102011-12-13 11:47:54 -08001062 Mutex::Autolock _l(mLock);
1063 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064}
1065
John Grossman4ff14ba2012-02-08 16:37:41 -08001066float AudioFlinger::masterVolume_l() const
1067{
John Grossman4ff14ba2012-02-08 16:37:41 -08001068 return mMasterVolume;
1069}
1070
John Grossmand8f178d2012-07-20 14:51:35 -07001071bool AudioFlinger::masterMute_l() const
1072{
John Grossmanee578c02012-07-23 17:05:46 -07001073 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001074}
1075
Eric Laurent223fd5c2014-11-11 13:43:36 -08001076status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1077{
1078 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001079 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001080 return BAD_VALUE;
1081 }
1082 pid_t caller = IPCThreadState::self()->getCallingPid();
1083 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001084 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001085 return PERMISSION_DENIED;
1086 }
1087
1088 return NO_ERROR;
1089}
1090
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001091status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1092 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093{
1094 // check calling permissions
1095 if (!settingsAllowed()) {
1096 return PERMISSION_DENIED;
1097 }
1098
Eric Laurent223fd5c2014-11-11 13:43:36 -08001099 status_t status = checkStreamType(stream);
1100 if (status != NO_ERROR) {
1101 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 }
Eric Laurent98e38192018-02-15 18:31:53 -08001103 if (output == AUDIO_IO_HANDLE_NONE) {
1104 return BAD_VALUE;
1105 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001106 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107
1108 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001109 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1110 if (volumeInterface == NULL) {
1111 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 }
Eric Laurent98e38192018-02-15 18:31:53 -08001113 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114
1115 return NO_ERROR;
1116}
1117
Glenn Kastenfff6d712012-01-12 16:38:12 -08001118status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119{
1120 // check calling permissions
1121 if (!settingsAllowed()) {
1122 return PERMISSION_DENIED;
1123 }
1124
Eric Laurent223fd5c2014-11-11 13:43:36 -08001125 status_t status = checkStreamType(stream);
1126 if (status != NO_ERROR) {
1127 return status;
1128 }
1129 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1130
1131 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001132 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 return BAD_VALUE;
1134 }
1135
Eric Laurent93575202011-01-18 18:39:02 -08001136 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001138 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1139 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1140 volumeInterfaces[i]->setStreamMute(stream, muted);
1141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142
1143 return NO_ERROR;
1144}
1145
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001146float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001148 status_t status = checkStreamType(stream);
1149 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 return 0.0f;
1151 }
Eric Laurent98e38192018-02-15 18:31:53 -08001152 if (output == AUDIO_IO_HANDLE_NONE) {
1153 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 }
1155
Eric Laurent98e38192018-02-15 18:31:53 -08001156 AutoMutex lock(mLock);
1157 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1158 if (volumeInterface == NULL) {
1159 return 0.0f;
1160 }
1161
1162 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163}
1164
Glenn Kastenfff6d712012-01-12 16:38:12 -08001165bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001167 status_t status = checkStreamType(stream);
1168 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 return true;
1170 }
1171
Glenn Kasten6637baa2012-01-09 09:40:36 -08001172 AutoMutex lock(mLock);
1173 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174}
1175
Eric Laurent054d9d32015-04-24 08:48:48 -07001176
1177void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1178{
1179 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1180 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1181 }
1182}
1183
Eric Laurentf1047e82018-04-16 19:18:20 -07001184// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1185// Some keys are used for audio routing and audio path configuration and should be reserved for use
1186// by audio policy and audio flinger for functional, privacy and security reasons.
1187void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1188{
1189 static const String8 kReservedParameters[] = {
1190 String8(AudioParameter::keyRouting),
1191 String8(AudioParameter::keySamplingRate),
1192 String8(AudioParameter::keyFormat),
1193 String8(AudioParameter::keyChannels),
1194 String8(AudioParameter::keyFrameCount),
1195 String8(AudioParameter::keyInputSource),
1196 String8(AudioParameter::keyMonoOutput),
1197 String8(AudioParameter::keyStreamConnect),
1198 String8(AudioParameter::keyStreamDisconnect),
1199 String8(AudioParameter::keyStreamSupportedFormats),
1200 String8(AudioParameter::keyStreamSupportedChannels),
1201 String8(AudioParameter::keyStreamSupportedSamplingRates),
1202 };
1203
1204 // multiuser friendly app ID check for requests coming from audioserver
1205 if (multiuser_get_app_id(callingUid) == AID_AUDIOSERVER) {
1206 return;
1207 }
1208
1209 AudioParameter param = AudioParameter(keyValuePairs);
1210 String8 value;
1211 for (auto& key : kReservedParameters) {
1212 if (param.get(key, value) == NO_ERROR) {
1213 ALOGW("%s: filtering key %s value %s from uid %d",
1214 __func__, key.string(), value.string(), callingUid);
1215 param.remove(key);
1216 }
1217 }
1218 keyValuePairs = param.toString();
1219}
1220
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001221status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222{
Eric Laurentf1047e82018-04-16 19:18:20 -07001223 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1224 ioHandle, keyValuePairs.string(),
1225 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001226
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 // check calling permissions
1228 if (!settingsAllowed()) {
1229 return PERMISSION_DENIED;
1230 }
1231
Eric Laurentf1047e82018-04-16 19:18:20 -07001232 String8 filteredKeyValuePairs = keyValuePairs;
1233 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1234
1235 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1236
Glenn Kasten142f5192014-03-25 17:44:59 -07001237 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1238 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001239 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001240 // result will remain NO_INIT if no audio device is present
1241 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001242 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001243 AutoMutex lock(mHardwareLock);
1244 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1245 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001246 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001247 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001248 // return success if at least one audio device accepts the parameters as not all
1249 // HALs are requested to support all parameters. If no audio device supports the
1250 // requested parameters, the last error is reported.
1251 if (final_result != NO_ERROR) {
1252 final_result = result;
1253 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001254 }
1255 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001256 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001257 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001258 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001259 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001260 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1261 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001262 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001263 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001264 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001265 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001266 }
1267 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001268 String8 screenState;
1269 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001270 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001271 if (isOff != (AudioFlinger::mScreenState & 1)) {
1272 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001273 }
1274 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001275 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276 }
1277
1278 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1279 // and the thread is exited once the lock is released
1280 sp<ThreadBase> thread;
1281 {
1282 Mutex::Autolock _l(mLock);
1283 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001284 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001286 if (thread == 0) {
1287 thread = checkMmapThread_l(ioHandle);
1288 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001289 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001290 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001291 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001292 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001293 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1294 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001295 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 }
1298 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001299 if (thread != 0) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001300 return thread->setParameters(filteredKeyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301 }
1302 return BAD_VALUE;
1303}
1304
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001305String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001307 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1308 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309
Eric Laurenta4c5a552012-03-29 10:12:40 -07001310 Mutex::Autolock _l(mLock);
1311
Glenn Kasten142f5192014-03-25 17:44:59 -07001312 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001313 String8 out_s8;
1314
Dima Zavin799a70e2011-04-18 16:57:27 -07001315 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001316 String8 s;
1317 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001318 {
1319 AutoMutex lock(mHardwareLock);
1320 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001321 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1322 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001323 mHardwareStatus = AUDIO_HW_IDLE;
1324 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001325 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001326 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001327 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328 }
1329
Eric Laurent6acd1d42017-01-04 14:23:29 -08001330 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1331 if (thread == NULL) {
1332 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1333 if (thread == NULL) {
1334 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1335 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001336 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001337 }
1338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001340 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001341}
1342
Glenn Kastendd8104c2012-07-02 12:42:44 -07001343size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1344 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001345{
Eric Laurenta1884f92011-08-23 08:25:03 -07001346 status_t ret = initCheck();
1347 if (ret != NO_ERROR) {
1348 return 0;
1349 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001350 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001351 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001352 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001353 return 0;
1354 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001355
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001356 AutoMutex lock(mHardwareLock);
1357 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001358 audio_config_t config, proposed;
1359 memset(&proposed, 0, sizeof(proposed));
1360 proposed.sample_rate = sampleRate;
1361 proposed.channel_mask = channelMask;
1362 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001363
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001364 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001365 size_t frames;
1366 for (;;) {
1367 // Note: config is currently a const parameter for get_input_buffer_size()
1368 // but we use a copy from proposed in case config changes from the call.
1369 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001370 status_t result = dev->getInputBufferSize(&config, &frames);
1371 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001372 break; // hal success, config is the result
1373 }
1374 // change one parameter of the configuration each iteration to a more "common" value
1375 // to see if the device will support it.
1376 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1377 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1378 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1379 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1380 } else {
1381 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1382 "format %#x, channelMask 0x%X",
1383 sampleRate, format, channelMask);
1384 break; // retries failed, break out of loop with frames == 0.
1385 }
1386 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001387 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001388 if (frames > 0 && config.sample_rate != sampleRate) {
1389 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1390 }
1391 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392}
1393
Glenn Kasten5f972c02014-01-13 09:59:31 -08001394uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 Mutex::Autolock _l(mLock);
1397
1398 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1399 if (recordThread != NULL) {
1400 return recordThread->getInputFramesLost();
1401 }
1402 return 0;
1403}
1404
1405status_t AudioFlinger::setVoiceVolume(float value)
1406{
Eric Laurenta1884f92011-08-23 08:25:03 -07001407 status_t ret = initCheck();
1408 if (ret != NO_ERROR) {
1409 return ret;
1410 }
1411
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412 // check calling permissions
1413 if (!settingsAllowed()) {
1414 return PERMISSION_DENIED;
1415 }
1416
1417 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001418 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001419 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001420 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421 mHardwareStatus = AUDIO_HW_IDLE;
1422
1423 return ret;
1424}
1425
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001426status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001427 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001429 Mutex::Autolock _l(mLock);
1430
1431 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1432 if (playbackThread != NULL) {
1433 return playbackThread->getRenderPosition(halFrames, dspFrames);
1434 }
1435
1436 return BAD_VALUE;
1437}
1438
1439void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1440{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001442 if (client == 0) {
1443 return;
1444 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001445 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001446 {
1447 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001448 if (mNotificationClients.indexOfKey(pid) < 0) {
1449 sp<NotificationClient> notificationClient = new NotificationClient(this,
1450 client,
1451 pid);
1452 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453
Eric Laurent021cf962014-05-13 10:18:14 -07001454 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455
Marco Nelissen06b46062014-11-14 07:58:25 -08001456 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001457 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001458 }
1459 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460
Eric Laurent021cf962014-05-13 10:18:14 -07001461 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001462 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001463 // the config change is always sent from playback or record threads to avoid deadlock
1464 // with AudioSystem::gLock
1465 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001466 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001469 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001470 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 }
1472}
1473
1474void AudioFlinger::removeNotificationClient(pid_t pid)
1475{
1476 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001477 {
1478 Mutex::Autolock _cl(mClientLock);
1479 mNotificationClients.removeItem(pid);
1480 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001481
Steve Block3856b092011-10-20 11:56:00 +01001482 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001483 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001484 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001485 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001486 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001487 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001488 if (ref->mPid == pid) {
1489 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001490 mAudioSessionRefs.removeAt(i);
1491 delete ref;
1492 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001493 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001494 } else {
1495 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001496 }
1497 }
1498 if (removed) {
1499 purgeStaleEffects_l();
1500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501}
1502
Eric Laurent73e26b62015-04-27 16:55:58 -07001503void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001504 const sp<AudioIoDescriptor>& ioDesc,
1505 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506{
Eric Laurent021cf962014-05-13 10:18:14 -07001507 Mutex::Autolock _l(mClientLock);
1508 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001510 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1511 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 }
1514}
1515
Eric Laurent021cf962014-05-13 10:18:14 -07001516// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517void AudioFlinger::removeClient_l(pid_t pid)
1518{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001519 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001520 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 mClients.removeItem(pid);
1522}
1523
Eric Laurent717e1282012-06-29 16:36:52 -07001524// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001525sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1526 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001527{
1528 sp<PlaybackThread> thread;
1529
1530 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1531 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1532 ALOG_ASSERT(thread == 0);
1533 thread = mPlaybackThreads.valueAt(i);
1534 }
1535 }
1536
1537 return thread;
1538}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541
1542// ----------------------------------------------------------------------------
1543
1544AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1545 : RefBase(),
1546 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001547 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548{
Andy Hung6f248bb2018-01-23 14:04:37 -08001549 mMemoryDealer = new MemoryDealer(
1550 audioFlinger->getClientSharedHeapSize(),
1551 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552}
1553
Eric Laurent021cf962014-05-13 10:18:14 -07001554// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555AudioFlinger::Client::~Client()
1556{
1557 mAudioFlinger->removeClient_l(mPid);
1558}
1559
Glenn Kasten435dbe62012-01-30 10:15:48 -08001560sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561{
1562 return mMemoryDealer;
1563}
1564
1565// ----------------------------------------------------------------------------
1566
1567AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1568 const sp<IAudioFlingerClient>& client,
1569 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001570 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571{
1572}
1573
1574AudioFlinger::NotificationClient::~NotificationClient()
1575{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576}
1577
Glenn Kasten0f11b512014-01-31 16:18:54 -08001578void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579{
1580 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001581 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582}
1583
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001584// ----------------------------------------------------------------------------
1585AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1586 : mPendingRequests(false) {}
1587
1588
1589void AudioFlinger::MediaLogNotifier::requestMerge() {
1590 AutoMutex _l(mMutex);
1591 mPendingRequests = true;
1592 mCond.signal();
1593}
1594
1595bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001596 // Should already have been checked, but just in case
1597 if (sMediaLogService == 0) {
1598 return false;
1599 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001600 // Wait until there are pending requests
1601 {
1602 AutoMutex _l(mMutex);
1603 mPendingRequests = false; // to ignore past requests
1604 while (!mPendingRequests) {
1605 mCond.wait(mMutex);
1606 // TODO may also need an exitPending check
1607 }
1608 mPendingRequests = false;
1609 }
1610 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001611 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001612 usleep(kPostTriggerSleepPeriod);
1613 return true;
1614}
1615
1616void AudioFlinger::requestLogMerge() {
1617 mMediaLogNotifier->requestMerge();
1618}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619
1620// ----------------------------------------------------------------------------
1621
Eric Laurentf14db3c2017-12-08 14:20:36 -08001622sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1623 CreateRecordOutput& output,
1624 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625{
1626 sp<RecordThread::RecordTrack> recordTrack;
1627 sp<RecordHandle> recordHandle;
1628 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001630 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001631 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632
Eric Laurentf14db3c2017-12-08 14:20:36 -08001633 output.cblk.clear();
1634 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001635 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001636
Eric Laurentf14db3c2017-12-08 14:20:36 -08001637 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001638 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001639 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001640 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001641 ALOGW_IF(clientUid != callingUid,
1642 "%s uid %d tried to pass itself off as %d",
1643 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001644 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001645 updatePid = true;
1646 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001647 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001648 if (updatePid) {
1649 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001650 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001651 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001652 __func__, callingUid, callingPid, clientPid);
1653 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001654 }
1655
Andy Hung6770c6f2015-04-07 13:43:36 -07001656 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001657 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1658 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001659 lStatus = BAD_VALUE;
1660 goto Exit;
1661 }
1662
Glenn Kasten53b5d092014-02-05 10:00:23 -08001663 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001664 if (!audio_is_input_channel(input.config.channel_mask)) {
1665 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001666 lStatus = BAD_VALUE;
1667 goto Exit;
1668 }
1669
Eric Laurentf14db3c2017-12-08 14:20:36 -08001670 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1671 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1672 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1673 lStatus = BAD_VALUE;
1674 goto Exit;
1675 }
1676
1677 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001678 output.selectedDeviceId = input.selectedDeviceId;
1679 output.flags = input.flags;
1680
1681 client = registerPid(clientPid);
1682
1683 // Not a conventional loop, but a retry loop for at most two iterations total.
1684 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1685 // Exits loop via break on no error of got exit on error
1686 // The sp<> references will be dropped when re-entering scope.
1687 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1688 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001689 // release previously opened input if retrying.
1690 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1691 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001692 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001693 output.inputId = AUDIO_IO_HANDLE_NONE;
Eric Laurent77881cd2018-02-09 16:01:31 -08001694 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001695 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001696 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1697 sessionId,
1698 // FIXME compare to AudioTrack
1699 clientPid,
1700 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001701 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001702 &input.config,
1703 output.flags, &output.selectedDeviceId, &portId);
1704
Glenn Kasten05997e22014-03-13 15:08:33 -07001705 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001707 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001709 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 lStatus = BAD_VALUE;
1711 goto Exit;
1712 }
1713
Eric Laurentf14db3c2017-12-08 14:20:36 -08001714 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715
Eric Laurentf14db3c2017-12-08 14:20:36 -08001716 output.sampleRate = input.config.sample_rate;
1717 output.frameCount = input.frameCount;
1718 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001719
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001720 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001721 input.config.format, input.config.channel_mask,
1722 &output.frameCount, sessionId,
1723 &output.notificationFrameCount,
1724 clientUid, &output.flags,
1725 input.clientInfo.clientTid,
1726 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001727 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001728
Eric Laurentf14db3c2017-12-08 14:20:36 -08001729 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1730 // audio policy manager without FAST constraint
1731 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001732 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001733 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001734
1735 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001736 goto Exit;
1737 }
1738
1739 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1740 // session and move it to this thread.
1741 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1742 if (chain != 0) {
1743 Mutex::Autolock _l(thread->mLock);
1744 thread->addEffectChain_l(chain);
1745 }
1746 break;
1747 }
1748 // End of retry loop.
1749 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 }
Glenn Kastene198c362013-08-13 09:13:36 -07001751
Eric Laurentf14db3c2017-12-08 14:20:36 -08001752 output.cblk = recordTrack->getCblk();
1753 output.buffers = recordTrack->getBuffers();
1754
1755 // return handle to client
1756 recordHandle = new RecordHandle(recordTrack);
1757
1758Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001759 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001760 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001761 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001762 // Don't hold mClientLock when releasing the reference on the track as the
1763 // destructor will acquire it.
1764 {
1765 Mutex::Autolock _cl(mClientLock);
1766 client.clear();
1767 }
Eric Laurent896c9672017-12-08 14:08:45 -08001768 recordTrack.clear();
1769 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001770 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 }
1773
Glenn Kasten9156ef32013-08-06 15:39:08 -07001774 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775 return recordHandle;
1776}
1777
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001778
1779
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780// ----------------------------------------------------------------------------
1781
Eric Laurenta4c5a552012-03-29 10:12:40 -07001782audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1783{
Eric Laurent44622db2014-08-01 19:00:33 -07001784 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001785 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001786 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001787 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001788 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001789 }
1790 Mutex::Autolock _l(mLock);
1791 return loadHwModule_l(name);
1792}
1793
1794// loadHwModule_l() must be called with AudioFlinger::mLock held
1795audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1796{
1797 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1798 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1799 ALOGW("loadHwModule() module %s already loaded", name);
1800 return mAudioHwDevs.keyAt(i);
1801 }
1802 }
1803
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001804 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001805
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001806 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001807 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001808 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001809 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001810 }
1811
1812 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001813 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001814 mHardwareStatus = AUDIO_HW_IDLE;
1815 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001816 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001817 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001818 }
1819
John Grossmanee578c02012-07-23 17:05:46 -07001820 // Check and cache this HAL's level of support for master mute and master
1821 // volume. If this is the first HAL opened, and it supports the get
1822 // methods, use the initial values provided by the HAL as the current
1823 // master mute and volume settings.
1824
1825 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1826 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001827 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001828
1829 if (0 == mAudioHwDevs.size()) {
1830 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001831 float mv;
1832 if (OK == dev->getMasterVolume(&mv)) {
1833 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001834 }
1835
1836 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001837 bool mm;
1838 if (OK == dev->getMasterMute(&mm)) {
1839 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001840 }
1841 }
1842
Eric Laurenta4c5a552012-03-29 10:12:40 -07001843 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001844 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001845 flags = static_cast<AudioHwDevice::Flags>(flags |
1846 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1847 }
1848
1849 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001850 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001851 flags = static_cast<AudioHwDevice::Flags>(flags |
1852 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1853 }
1854
Eric Laurenta4c5a552012-03-29 10:12:40 -07001855 mHardwareStatus = AUDIO_HW_IDLE;
1856 }
1857
Glenn Kastena13cde92016-03-28 15:26:02 -07001858 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001859 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001860
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001861 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001862
1863 return handle;
1864
1865}
1866
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001867// ----------------------------------------------------------------------------
1868
Glenn Kasten3b16c762012-11-14 08:44:39 -08001869uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001870{
1871 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001872 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001873 return thread != NULL ? thread->sampleRate() : 0;
1874}
1875
Glenn Kastene33054e2012-11-14 12:54:39 -08001876size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001877{
1878 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001879 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001880 return thread != NULL ? thread->frameCountHAL() : 0;
1881}
1882
1883// ----------------------------------------------------------------------------
1884
Andy Hung6f248bb2018-01-23 14:04:37 -08001885status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001886{
1887 uid_t uid = IPCThreadState::self()->getCallingUid();
1888 if (uid != AID_SYSTEM) {
1889 return PERMISSION_DENIED;
1890 }
1891 Mutex::Autolock _l(mLock);
1892 if (mIsDeviceTypeKnown) {
1893 return INVALID_OPERATION;
1894 }
1895 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001896 mTotalMemory = totalMemory;
1897 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1898 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1899 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1900 // though actual setting is determined through device configuration.
1901 constexpr int64_t GB = 1024 * 1024 * 1024;
1902 mClientSharedHeapSize =
1903 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1904 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1905 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1906 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1907 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001908 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001909
1910 // TODO: Cache the client shared heap size in a persistent property.
1911 // It's possible that a native process or Java service or app accesses audioserver
1912 // after it is registered by system server, but before AudioService updates
1913 // the memory info. This would occur immediately after boot or an audioserver
1914 // crash and restore. Before update from AudioService, the client would get the
1915 // minimum heap size.
1916
1917 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1918 (isLowRamDevice ? "true" : "false"),
1919 (long long)mTotalMemory,
1920 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001921 return NO_ERROR;
1922}
1923
Andy Hung6f248bb2018-01-23 14:04:37 -08001924size_t AudioFlinger::getClientSharedHeapSize() const
1925{
1926 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1927 if (heapSizeInBytes != 0) { // read-only property overrides all.
1928 return heapSizeInBytes;
1929 }
1930 return mClientSharedHeapSize;
1931}
1932
Mikhail Naganovdea53042018-04-26 13:10:21 -07001933status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1934{
1935 ALOGV(__func__);
1936
1937 audio_module_handle_t module;
1938 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1939 module = config->ext.device.hw_module;
1940 } else {
1941 module = config->ext.mix.hw_module;
1942 }
1943
1944 Mutex::Autolock _l(mLock);
1945 ssize_t index = mAudioHwDevs.indexOfKey(module);
1946 if (index < 0) {
1947 ALOGW("%s() bad hw module %d", __func__, module);
1948 return BAD_VALUE;
1949 }
1950
1951 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
1952 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
1953}
1954
Eric Laurent93c3d412014-08-01 14:48:35 -07001955audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1956{
1957 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001958
1959 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1960 if (index >= 0) {
1961 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1962 mHwAvSyncIds.valueAt(index), sessionId);
1963 return mHwAvSyncIds.valueAt(index);
1964 }
1965
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001966 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001967 if (dev == NULL) {
1968 return AUDIO_HW_SYNC_INVALID;
1969 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001970 String8 reply;
1971 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001972 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001973 param = AudioParameter(reply);
1974 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001975
1976 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001977 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001978 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1979 return AUDIO_HW_SYNC_INVALID;
1980 }
1981
1982 // allow only one session for a given HW A/V sync ID.
1983 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1984 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1985 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1986 value, mHwAvSyncIds.keyAt(i));
1987 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001988 break;
1989 }
1990 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001991
1992 mHwAvSyncIds.add(sessionId, value);
1993
1994 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1995 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1996 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001997 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001998 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001999 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07002000 thread->setParameters(param.toString());
2001 break;
2002 }
2003 }
2004
2005 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2006 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002007}
2008
Eric Laurent72e3f392015-05-20 14:43:50 -07002009status_t AudioFlinger::systemReady()
2010{
2011 Mutex::Autolock _l(mLock);
2012 ALOGI("%s", __FUNCTION__);
2013 if (mSystemReady) {
2014 ALOGW("%s called twice", __FUNCTION__);
2015 return NO_ERROR;
2016 }
2017 mSystemReady = true;
2018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2019 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2020 thread->systemReady();
2021 }
2022 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2023 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2024 thread->systemReady();
2025 }
2026 return NO_ERROR;
2027}
2028
jiabin46a76fa2018-01-05 10:18:21 -08002029status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2030{
jiabin9ff780e2018-03-19 18:19:52 -07002031 AutoMutex lock(mHardwareLock);
2032 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2033 status_t status = dev->getMicrophones(microphones);
2034 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002035}
2036
Eric Laurentfa90e842014-10-17 18:12:31 -07002037// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2038void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2039{
2040 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2041 if (index >= 0) {
2042 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2043 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2044 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002045 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002046 thread->setParameters(param.toString());
2047 }
2048}
2049
2050
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002051// ----------------------------------------------------------------------------
2052
Eric Laurent83b88082014-06-20 18:31:16 -07002053
Eric Laurent6acd1d42017-01-04 14:23:29 -08002054sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002055 audio_io_handle_t *output,
2056 audio_config_t *config,
2057 audio_devices_t devices,
2058 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002059 audio_output_flags_t flags)
2060{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002061 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002062 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002063 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002064 }
2065
Eric Laurentcf2c0212014-07-25 16:20:43 -07002066 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002067 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2068 } else {
2069 // Audio Policy does not currently request a specific output handle.
2070 // If this is ever needed, see openInput_l() for example code.
2071 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2072 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002073 }
Eric Laurent83b88082014-06-20 18:31:16 -07002074
2075 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2076
Eric Laurent83b88082014-06-20 18:31:16 -07002077 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002078 // This if statement allows overriding the audio policy settings
2079 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2080 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2081 // Check only for Normal Mixing mode
2082 if (kEnableExtendedPrecision) {
2083 // Specify format (uncomment one below to choose)
2084 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2085 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2086 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2087 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002088 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002089 }
2090 if (kEnableExtendedChannels) {
2091 // Specify channel mask (uncomment one below to choose)
2092 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2093 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2094 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2095 }
Eric Laurent83b88082014-06-20 18:31:16 -07002096 }
2097
Phil Burk062e67a2015-02-11 13:40:50 -08002098 AudioStreamOut *outputStream = NULL;
2099 status_t status = outHwDev->openOutputStream(
2100 &outputStream,
2101 *output,
2102 devices,
2103 flags,
2104 config,
2105 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002106
2107 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002108
Phil Burk062e67a2015-02-11 13:40:50 -08002109 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002110 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2111 sp<MmapPlaybackThread> thread =
2112 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2113 devices, AUDIO_DEVICE_NONE, mSystemReady);
2114 mMmapThreads.add(*output, thread);
2115 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2116 *output, thread.get());
2117 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002118 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002119 sp<PlaybackThread> thread;
2120 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2121 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2122 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2123 *output, thread.get());
2124 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2125 || !isValidPcmSinkFormat(config->format)
2126 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2127 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2128 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2129 *output, thread.get());
2130 } else {
2131 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2132 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2133 *output, thread.get());
2134 }
2135 mPlaybackThreads.add(*output, thread);
2136 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002137 }
Eric Laurent83b88082014-06-20 18:31:16 -07002138 }
2139
2140 return 0;
2141}
2142
Eric Laurentcf2c0212014-07-25 16:20:43 -07002143status_t AudioFlinger::openOutput(audio_module_handle_t module,
2144 audio_io_handle_t *output,
2145 audio_config_t *config,
2146 audio_devices_t *devices,
2147 const String8& address,
2148 uint32_t *latencyMs,
2149 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002151 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2152 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002153 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002154 (devices != NULL) ? *devices : 0,
2155 config->sample_rate,
2156 config->format,
2157 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002158 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002160 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002161 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002162 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002163
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 Mutex::Autolock _l(mLock);
2165
Eric Laurent6acd1d42017-01-04 14:23:29 -08002166 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002167 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002168 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2169 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2170 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171
Eric Laurent6acd1d42017-01-04 14:23:29 -08002172 // notify client processes of the new output creation
2173 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002174
Eric Laurent6acd1d42017-01-04 14:23:29 -08002175 // the first primary output opened designates the primary hw device
2176 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002177 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002178 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002179
Eric Laurent6acd1d42017-01-04 14:23:29 -08002180 AutoMutex lock(mHardwareLock);
2181 mHardwareStatus = AUDIO_HW_SET_MODE;
2182 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2183 mHardwareStatus = AUDIO_HW_IDLE;
2184 }
2185 } else {
2186 MmapThread *mmapThread = (MmapThread *)thread.get();
2187 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002188 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002189 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 }
2191
Eric Laurentcf2c0212014-07-25 16:20:43 -07002192 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193}
2194
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002195audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2196 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197{
2198 Mutex::Autolock _l(mLock);
2199 MixerThread *thread1 = checkMixerThread_l(output1);
2200 MixerThread *thread2 = checkMixerThread_l(output2);
2201
2202 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002203 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2204 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002205 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 }
2207
Glenn Kasteneeecb982016-02-26 10:44:04 -08002208 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002209 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210 thread->addOutputTrack(thread2);
2211 mPlaybackThreads.add(id, thread);
2212 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002213 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002214 return id;
2215}
2216
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002217status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218{
Glenn Kastend96c5722012-04-25 13:44:49 -07002219 return closeOutput_nonvirtual(output);
2220}
2221
2222status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2223{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 // keep strong reference on the playback thread so that
2225 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002226 sp<PlaybackThread> playbackThread;
2227 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 {
2229 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002230 playbackThread = checkPlaybackThread_l(output);
2231 if (playbackThread != NULL) {
2232 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233
Eric Laurent6acd1d42017-01-04 14:23:29 -08002234 if (playbackThread->type() == ThreadBase::MIXER) {
2235 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2236 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2237 DuplicatingThread *dupThread =
2238 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2239 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2240 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241 }
2242 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002243
2244
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245 mPlaybackThreads.removeItem(output);
2246 // save all effects to the default thread
2247 if (mPlaybackThreads.size()) {
2248 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2249 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002250 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002251 Mutex::Autolock _dl(dstThread->mLock);
2252 Mutex::Autolock _sl(playbackThread->mLock);
2253 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2254 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002255 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2256 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 }
2259 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002260 } else {
2261 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2262 if (mmapThread == 0) {
2263 return BAD_VALUE;
2264 }
2265 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002266 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002268 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2269 ioDesc->mIoHandle = output;
2270 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002272 // The thread entity (active unit of execution) is no longer running here,
2273 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274
Eric Laurent6acd1d42017-01-04 14:23:29 -08002275 if (playbackThread != 0) {
2276 playbackThread->exit();
2277 if (!playbackThread->isDuplicating()) {
2278 closeOutputFinish(playbackThread);
2279 }
2280 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002281 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002282 mmapThread->exit();
2283 AudioStreamOut *out = mmapThread->clearOutput();
2284 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2285 // from now on thread->mOutput is NULL
2286 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 }
2288 return NO_ERROR;
2289}
2290
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002291void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002292{
2293 AudioStreamOut *out = thread->clearOutput();
2294 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2295 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002296 delete out;
2297}
2298
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002299void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002300{
2301 mPlaybackThreads.removeItem(thread->mId);
2302 thread->exit();
2303 closeOutputFinish(thread);
2304}
2305
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002306status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307{
2308 Mutex::Autolock _l(mLock);
2309 PlaybackThread *thread = checkPlaybackThread_l(output);
2310
2311 if (thread == NULL) {
2312 return BAD_VALUE;
2313 }
2314
Steve Block3856b092011-10-20 11:56:00 +01002315 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 thread->suspend();
2317
2318 return NO_ERROR;
2319}
2320
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002321status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322{
2323 Mutex::Autolock _l(mLock);
2324 PlaybackThread *thread = checkPlaybackThread_l(output);
2325
2326 if (thread == NULL) {
2327 return BAD_VALUE;
2328 }
2329
Steve Block3856b092011-10-20 11:56:00 +01002330 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331
2332 thread->restore();
2333
2334 return NO_ERROR;
2335}
2336
Eric Laurentcf2c0212014-07-25 16:20:43 -07002337status_t AudioFlinger::openInput(audio_module_handle_t module,
2338 audio_io_handle_t *input,
2339 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002340 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002341 const String8& address,
2342 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002343 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344{
Eric Laurent83b88082014-06-20 18:31:16 -07002345 Mutex::Autolock _l(mLock);
2346
Glenn Kastene7d66712015-03-05 13:46:52 -08002347 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002348 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002349 }
2350
Eric Laurent6acd1d42017-01-04 14:23:29 -08002351 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002352
2353 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002354 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002355 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002356 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002358 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002359}
Dima Zavin799a70e2011-04-18 16:57:27 -07002360
Eric Laurent6acd1d42017-01-04 14:23:29 -08002361sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002362 audio_io_handle_t *input,
2363 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002364 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002365 const String8& address,
2366 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002367 audio_input_flags_t flags)
2368{
Glenn Kastene7d66712015-03-05 13:46:52 -08002369 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002370 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002371 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002372 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002373 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002374
Glenn Kasteneeecb982016-02-26 10:44:04 -08002375 // Audio Policy can request a specific handle for hardware hotword.
2376 // The goal here is not to re-open an already opened input.
2377 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002378 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002379 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2380 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2381 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2382 return 0;
2383 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2384 // This should not happen in a transient state with current design.
2385 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2386 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002387 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002388
Eric Laurentcf2c0212014-07-25 16:20:43 -07002389 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002390 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002391 sp<StreamInHalInterface> inStream;
2392 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002393 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002394 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2395 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002396 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002397 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002398 halconfig.sample_rate,
2399 halconfig.format,
2400 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002401 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002402 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002404 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002405 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002406 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002407 audio_is_linear_pcm(config->format) &&
2408 audio_is_linear_pcm(halconfig.format) &&
2409 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002410 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2411 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002412 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002413 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002414 inStream.clear();
2415 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002416 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002417 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 }
2419
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002420 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002421 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002422 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2423 sp<MmapCaptureThread> thread =
2424 new MmapCaptureThread(this, *input,
2425 inHwDev, inputStream,
2426 primaryOutputDevice_l(), devices, mSystemReady);
2427 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002428 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2429 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002430 return thread;
2431 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002432#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002433 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2434 // or (re-)create if current Pipe is idle and does not match the new format
2435 sp<NBAIO_Sink> teeSink;
2436 enum {
2437 TEE_SINK_NO, // don't copy input
2438 TEE_SINK_NEW, // copy input using a new pipe
2439 TEE_SINK_OLD, // copy input using an existing pipe
2440 } kind;
2441 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2442 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2443 if (!mTeeSinkInputEnabled) {
2444 kind = TEE_SINK_NO;
2445 } else if (!Format_isValid(format)) {
2446 kind = TEE_SINK_NO;
2447 } else if (mRecordTeeSink == 0) {
2448 kind = TEE_SINK_NEW;
2449 } else if (mRecordTeeSink->getStrongCount() != 1) {
2450 kind = TEE_SINK_NO;
2451 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2452 kind = TEE_SINK_OLD;
2453 } else {
2454 kind = TEE_SINK_NEW;
2455 }
2456 switch (kind) {
2457 case TEE_SINK_NEW: {
2458 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2459 size_t numCounterOffers = 0;
2460 const NBAIO_Format offers[1] = {format};
2461 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2462 ALOG_ASSERT(index == 0);
2463 PipeReader *pipeReader = new PipeReader(*pipe);
2464 numCounterOffers = 0;
2465 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2466 ALOG_ASSERT(index == 0);
2467 mRecordTeeSink = pipe;
2468 mRecordTeeSource = pipeReader;
2469 teeSink = pipe;
2470 }
2471 break;
2472 case TEE_SINK_OLD:
2473 teeSink = mRecordTeeSink;
2474 break;
2475 case TEE_SINK_NO:
2476 default:
2477 break;
2478 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002479#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002480
2481 // Start record thread
2482 // RecordThread requires both input and output device indication to forward to audio
2483 // pre processing modules
2484 sp<RecordThread> thread = new RecordThread(this,
2485 inputStream,
2486 *input,
2487 primaryOutputDevice_l(),
2488 devices,
2489 mSystemReady
2490#ifdef TEE_SINK
2491 , teeSink
2492#endif
2493 );
2494 mRecordThreads.add(*input, thread);
2495 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2496 return thread;
2497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 }
2499
Eric Laurentcf2c0212014-07-25 16:20:43 -07002500 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 return 0;
2502}
2503
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002504status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505{
Glenn Kastend96c5722012-04-25 13:44:49 -07002506 return closeInput_nonvirtual(input);
2507}
2508
2509status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2510{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 // keep strong reference on the record thread so that
2512 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002513 sp<RecordThread> recordThread;
2514 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515 {
2516 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002517 recordThread = checkRecordThread_l(input);
2518 if (recordThread != 0) {
2519 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520
Eric Laurent6acd1d42017-01-04 14:23:29 -08002521 // If we still have effect chains, it means that a client still holds a handle
2522 // on at least one effect. We must either move the chain to an existing thread with the
2523 // same session ID or put it aside in case a new record thread is opened for a
2524 // new capture on the same session
2525 sp<EffectChain> chain;
2526 {
2527 Mutex::Autolock _sl(recordThread->mLock);
2528 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2529 // Note: maximum one chain per record thread
2530 if (effectChains.size() != 0) {
2531 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002532 }
2533 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002534 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002535 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002536 // This should only happen in case of overlap between one thread tear down and the
2537 // creation of its replacement
2538 size_t i;
2539 for (i = 0; i < mRecordThreads.size(); i++) {
2540 sp<RecordThread> t = mRecordThreads.valueAt(i);
2541 if (t == recordThread) {
2542 continue;
2543 }
2544 if (t->hasAudioSession(chain->sessionId()) != 0) {
2545 Mutex::Autolock _l(t->mLock);
2546 ALOGV("closeInput() found thread %d for effect session %d",
2547 t->id(), chain->sessionId());
2548 t->addEffectChain_l(chain);
2549 break;
2550 }
2551 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002552 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002553 if (i == mRecordThreads.size()) {
2554 putOrphanEffectChain_l(chain);
2555 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002556 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002557 mRecordThreads.removeItem(input);
2558 } else {
2559 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2560 if (mmapThread == 0) {
2561 return BAD_VALUE;
2562 }
2563 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002564 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002565 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2566 ioDesc->mIoHandle = input;
2567 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 }
Eric Laurent83b88082014-06-20 18:31:16 -07002569 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2570 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002571 if (recordThread != 0) {
2572 closeInputFinish(recordThread);
2573 } else if (mmapThread != 0) {
2574 mmapThread->exit();
2575 AudioStreamIn *in = mmapThread->clearInput();
2576 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2577 // from now on thread->mInput is NULL
2578 delete in;
2579 }
Eric Laurent83b88082014-06-20 18:31:16 -07002580 return NO_ERROR;
2581}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002583void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002584{
2585 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002586 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002587 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002588 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002589 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002590}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002592void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002593{
2594 mRecordThreads.removeItem(thread->mId);
2595 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596}
2597
Glenn Kastend2304db2014-02-03 07:40:31 -08002598status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599{
2600 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002601 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602
2603 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2604 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002605 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002606 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002607 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2608 mMmapThreads[i]->invalidateTracks(stream);
2609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 return NO_ERROR;
2611}
2612
2613
Glenn Kasteneeecb982016-02-26 10:44:04 -08002614audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615{
Glenn Kasten9d003132016-04-06 14:38:09 -07002616 // This is a binder API, so a malicious client could pass in a bad parameter.
2617 // Check for that before calling the internal API nextUniqueId().
2618 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2619 ALOGE("newAudioUniqueId invalid use %d", use);
2620 return AUDIO_UNIQUE_ID_ALLOCATE;
2621 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002622 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623}
2624
Glenn Kastend848eb42016-03-08 13:42:11 -08002625void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002626{
2627 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002628 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002629 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2630 if (pid != -1 && (caller == getpid_cached)) {
2631 caller = pid;
2632 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002633
Eric Laurent021cf962014-05-13 10:18:14 -07002634 {
2635 Mutex::Autolock _cl(mClientLock);
2636 // Ignore requests received from processes not known as notification client. The request
2637 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2638 // called from a different pid leaving a stale session reference. Also we don't know how
2639 // to clear this reference if the client process dies.
2640 if (mNotificationClients.indexOfKey(caller) < 0) {
2641 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2642 return;
2643 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002644 }
2645
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002646 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002647 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002648 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002649 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2650 ref->mCnt++;
2651 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002652 return;
2653 }
2654 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002655 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2656 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002657}
2658
Glenn Kastend848eb42016-03-08 13:42:11 -08002659void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002660{
2661 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002662 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002663 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2664 if (pid != -1 && (caller == getpid_cached)) {
2665 caller = pid;
2666 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002667 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002668 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002669 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002670 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2671 ref->mCnt--;
2672 ALOGV(" decremented refcount to %d", ref->mCnt);
2673 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002674 mAudioSessionRefs.removeAt(i);
2675 delete ref;
2676 purgeStaleEffects_l();
2677 }
2678 return;
2679 }
2680 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002681 // If the caller is mediaserver it is likely that the session being released was acquired
2682 // on behalf of a process not in notification clients and we ignore the warning.
2683 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002684}
2685
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002686bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2687{
2688 size_t num = mAudioSessionRefs.size();
2689 for (size_t i = 0; i < num; i++) {
2690 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2691 if (ref->mSessionid == audioSession) {
2692 return true;
2693 }
2694 }
2695 return false;
2696}
2697
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002698void AudioFlinger::purgeStaleEffects_l() {
2699
Steve Block3856b092011-10-20 11:56:00 +01002700 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002701
2702 Vector< sp<EffectChain> > chains;
2703
2704 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2705 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002706 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002707 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2708 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002709 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2710 chains.push(ec);
2711 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002712 }
2713 }
2714 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2715 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002716 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002717 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2718 sp<EffectChain> ec = t->mEffectChains[j];
2719 chains.push(ec);
2720 }
2721 }
2722
2723 for (size_t i = 0; i < chains.size(); i++) {
2724 sp<EffectChain> ec = chains[i];
2725 int sessionid = ec->sessionId();
2726 sp<ThreadBase> t = ec->mThread.promote();
2727 if (t == 0) {
2728 continue;
2729 }
2730 size_t numsessionrefs = mAudioSessionRefs.size();
2731 bool found = false;
2732 for (size_t k = 0; k < numsessionrefs; k++) {
2733 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002734 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002735 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002736 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002737 found = true;
2738 break;
2739 }
2740 }
2741 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002742 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002743 // remove all effects from the chain
2744 while (ec->mEffects.size()) {
2745 sp<EffectModule> effect = ec->mEffects[0];
2746 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002747 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002748 if (effect->purgeHandles()) {
2749 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002750 }
2751 AudioSystem::unregisterEffect(effect->id());
2752 }
2753 }
2754 }
2755 return;
2756}
2757
Glenn Kasteneeecb982016-02-26 10:44:04 -08002758// checkThread_l() must be called with AudioFlinger::mLock held
2759AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2760{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002761 ThreadBase *thread = checkMmapThread_l(ioHandle);
2762 if (thread == 0) {
2763 switch (audio_unique_id_get_use(ioHandle)) {
2764 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2765 thread = checkPlaybackThread_l(ioHandle);
2766 break;
2767 case AUDIO_UNIQUE_ID_USE_INPUT:
2768 thread = checkRecordThread_l(ioHandle);
2769 break;
2770 default:
2771 break;
2772 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002773 }
2774 return thread;
2775}
2776
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002778AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779{
Glenn Kastena1117922012-01-26 10:53:32 -08002780 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781}
2782
2783// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002784AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785{
2786 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002787 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788}
2789
2790// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002791AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792{
Glenn Kastena1117922012-01-26 10:53:32 -08002793 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794}
2795
Eric Laurent6acd1d42017-01-04 14:23:29 -08002796// checkMmapThread_l() must be called with AudioFlinger::mLock held
2797AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2798{
2799 return mMmapThreads.valueFor(io).get();
2800}
2801
2802
2803// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2804AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2805{
Eric Laurent7459b902017-04-19 18:10:41 -07002806 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002807 if (volumeInterface == nullptr) {
2808 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2809 if (mmapThread != nullptr) {
2810 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002811 MmapPlaybackThread *mmapPlaybackThread =
2812 static_cast<MmapPlaybackThread *>(mmapThread);
2813 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002814 }
2815 }
2816 }
2817 return volumeInterface;
2818}
2819
2820Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2821{
2822 Vector <VolumeInterface *> volumeInterfaces;
2823 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002824 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002825 }
2826 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2827 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002828 MmapPlaybackThread *mmapPlaybackThread =
2829 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2830 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002831 }
2832 }
2833 return volumeInterfaces;
2834}
2835
Glenn Kasteneeecb982016-02-26 10:44:04 -08002836audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837{
Glenn Kasten9d003132016-04-06 14:38:09 -07002838 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002839 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002840 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2841 for (int retry = 0; retry < maxRetries; retry++) {
2842 // The cast allows wraparound from max positive to min negative instead of abort
2843 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2844 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2845 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2846 // allow wrap by skipping 0 and -1 for session ids
2847 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2848 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2849 return (audio_unique_id_t) (base | use);
2850 }
2851 }
2852 // We have no way of recovering from wraparound
2853 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2854 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855}
2856
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002857AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002858{
2859 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2860 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002861 if(thread->isDuplicating()) {
2862 continue;
2863 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002864 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002865 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002866 return thread;
2867 }
2868 }
2869 return NULL;
2870}
2871
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002872audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002873{
2874 PlaybackThread *thread = primaryPlaybackThread_l();
2875
2876 if (thread == NULL) {
2877 return 0;
2878 }
2879
Eric Laurentf1c04f92012-08-28 14:26:53 -07002880 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002881}
2882
Glenn Kastena7335632016-06-09 17:09:53 -07002883AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2884{
2885 size_t minFrameCount = 0;
2886 PlaybackThread *minThread = NULL;
2887 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2888 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2889 if (!thread->isDuplicating()) {
2890 size_t frameCount = thread->frameCountHAL();
2891 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2892 (frameCount == minFrameCount && thread->hasFastMixer() &&
2893 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2894 minFrameCount = frameCount;
2895 minThread = thread;
2896 }
2897 }
2898 }
2899 return minThread;
2900}
2901
Eric Laurenta011e352012-03-29 15:51:43 -07002902sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002903 audio_session_t triggerSession,
2904 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002905 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002906 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002907{
2908 Mutex::Autolock _l(mLock);
2909
2910 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2911 status_t playStatus = NAME_NOT_FOUND;
2912 status_t recStatus = NAME_NOT_FOUND;
2913 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2914 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2915 if (playStatus == NO_ERROR) {
2916 return event;
2917 }
2918 }
2919 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2920 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2921 if (recStatus == NO_ERROR) {
2922 return event;
2923 }
2924 }
2925 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2926 mPendingSyncEvents.add(event);
2927 } else {
2928 ALOGV("createSyncEvent() invalid event %d", event->type());
2929 event.clear();
2930 }
2931 return event;
2932}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002933
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934// ----------------------------------------------------------------------------
2935// Effect management
2936// ----------------------------------------------------------------------------
2937
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002938sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2939 return mEffectsFactoryHal;
2940}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941
Glenn Kastenf587ba52012-01-26 16:25:10 -08002942status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943{
2944 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002945 if (mEffectsFactoryHal.get()) {
2946 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2947 } else {
2948 return -ENODEV;
2949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950}
2951
Glenn Kastenf587ba52012-01-26 16:25:10 -08002952status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953{
2954 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002955 if (mEffectsFactoryHal.get()) {
2956 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2957 } else {
2958 return -ENODEV;
2959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960}
2961
Glenn Kasten5e92a782012-01-30 07:40:52 -08002962status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002963 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964{
2965 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002966 if (mEffectsFactoryHal.get()) {
2967 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2968 } else {
2969 return -ENODEV;
2970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971}
2972
2973
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002974sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 effect_descriptor_t *pDesc,
2976 const sp<IEffectClient>& effectClient,
2977 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002978 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002979 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002980 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002981 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 status_t *status,
2983 int *id,
2984 int *enabled)
2985{
2986 status_t lStatus = NO_ERROR;
2987 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989
Eric Laurentb6436272016-12-07 19:24:50 -08002990 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2991 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2992 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2993 ALOGW_IF(pid != -1 && pid != callingPid,
2994 "%s uid %d pid %d tried to pass itself off as pid %d",
2995 __func__, callingUid, callingPid, pid);
2996 pid = callingPid;
2997 }
2998
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002999 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3000 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001
3002 if (pDesc == NULL) {
3003 lStatus = BAD_VALUE;
3004 goto Exit;
3005 }
3006
Eric Laurent84e9a102010-09-23 16:10:16 -07003007 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003008 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003009 lStatus = PERMISSION_DENIED;
3010 goto Exit;
3011 }
3012
Dima Zavinfce7a472011-04-19 22:30:36 -07003013 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07003014 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08003015 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003016 lStatus = PERMISSION_DENIED;
3017 goto Exit;
3018 }
3019
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003020 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003021 lStatus = NO_INIT;
3022 goto Exit;
3023 }
3024
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003026 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003028 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003029 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003030 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003031 goto Exit;
3032 }
3033 } else {
3034 // if uuid is not specified, look for an available implementation
3035 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003036 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003037 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038 lStatus = BAD_VALUE;
3039 goto Exit;
3040 }
3041 uint32_t numEffects = 0;
3042 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003043 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 bool found = false;
3045
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003046 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003048 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 goto Exit;
3050 }
3051 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003052 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003054 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 continue;
3056 }
3057 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3058 // If matching type found save effect descriptor. If the session is
3059 // 0 and the effect is not auxiliary, continue enumeration in case
3060 // an auxiliary version of this effect type is available
3061 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003062 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003063 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3065 break;
3066 }
3067 }
3068 }
3069 if (!found) {
3070 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003071 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 goto Exit;
3073 }
3074 // For same effect type, chose auxiliary version over insert version if
3075 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003076 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003078 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003079 }
3080 }
3081
3082 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003083 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3085 lStatus = INVALID_OPERATION;
3086 goto Exit;
3087 }
3088
Eric Laurent59255e42011-07-27 19:49:51 -07003089 // check recording permission for visualizer
3090 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003091 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003092 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003093 lStatus = PERMISSION_DENIED;
3094 goto Exit;
3095 }
3096
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003098 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003099 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003100 // if the output returned by getOutputForEffect() is removed before we lock the
3101 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3102 // and we will exit safely
3103 io = AudioSystem::getOutputForEffect(&desc);
3104 ALOGV("createEffect got output %d", io);
3105 }
3106
3107 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108
3109 // If output is not specified try to find a matching audio session ID in one of the
3110 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003111 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3112 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003113 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003114 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003115 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3116 // output must be specified by AudioPolicyManager when using session
3117 // AUDIO_SESSION_OUTPUT_STAGE
3118 lStatus = BAD_VALUE;
3119 goto Exit;
3120 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003121 // look for the thread where the specified audio session is present
3122 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3123 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3124 io = mPlaybackThreads.keyAt(i);
3125 break;
3126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003128 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003129 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3130 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3131 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003132 break;
3133 }
3134 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003135 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003136 if (io == AUDIO_IO_HANDLE_NONE) {
3137 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3138 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3139 io = mMmapThreads.keyAt(i);
3140 break;
3141 }
3142 }
3143 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003144 // If no output thread contains the requested session ID, default to
3145 // first output. The effect chain will be moved to the correct output
3146 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003147 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003148 io = mPlaybackThreads.keyAt(0);
3149 }
Steve Block3856b092011-10-20 11:56:00 +01003150 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003151 }
3152 ThreadBase *thread = checkRecordThread_l(io);
3153 if (thread == NULL) {
3154 thread = checkPlaybackThread_l(io);
3155 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003156 thread = checkMmapThread_l(io);
3157 if (thread == NULL) {
3158 ALOGE("createEffect() unknown output thread");
3159 lStatus = BAD_VALUE;
3160 goto Exit;
3161 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003162 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003163 } else {
3164 // Check if one effect chain was awaiting for an effect to be created on this
3165 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003166 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003167 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003168 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003169 thread->addEffectChain_l(chain);
3170 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003172
Eric Laurent021cf962014-05-13 10:18:14 -07003173 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003175 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003176 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003177 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003178 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003179 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003180 // remove local strong reference to Client with mClientLock held
3181 Mutex::Autolock _cl(mClientLock);
3182 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003183 } else {
3184 // handle must be valid here, but check again to be safe.
3185 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 }
3188
haobo101735295ff7b0d2017-03-17 17:44:03 +08003189 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3190 // handle must be cleared outside lock.
3191 handle.clear();
3192 }
3193
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003195 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196 return handle;
3197}
3198
Glenn Kastend848eb42016-03-08 13:42:11 -08003199status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003200 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003201{
Steve Block3856b092011-10-20 11:56:00 +01003202 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003203 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003204 Mutex::Autolock _l(mLock);
3205 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003206 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003207 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 }
Eric Laurentde070132010-07-13 04:45:46 -07003209 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3210 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003211 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003212 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 }
Eric Laurentde070132010-07-13 04:45:46 -07003214 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3215 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003216 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003217 return BAD_VALUE;
3218 }
3219
3220 Mutex::Autolock _dl(dstThread->mLock);
3221 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003222 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223}
3224
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003225// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003226status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003227 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003228 AudioFlinger::PlaybackThread *dstThread,
3229 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003230{
Steve Block3856b092011-10-20 11:56:00 +01003231 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003232 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003233
Eric Laurent59255e42011-07-27 19:49:51 -07003234 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003235 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003236 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003237 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003238 return INVALID_OPERATION;
3239 }
3240
Eric Laurent4c415062016-06-17 16:14:16 -07003241 // Check whether the destination thread and all effects in the chain are compatible
3242 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003243 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003244 " destination thread %p is not compatible with effects in the chain",
3245 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003246 return INVALID_OPERATION;
3247 }
3248
Eric Laurent39e94f82010-07-28 01:32:47 -07003249 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003250 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003251 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003252 // removed.
3253 srcThread->removeEffectChain_l(chain);
3254
3255 // transfer all effects one by one so that new effect chain is created on new thread with
3256 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003257 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003258 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003259 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003260 Vector< sp<EffectModule> > removed;
3261 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003262 while (effect != 0) {
3263 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003264 removed.add(effect);
3265 status = dstThread->addEffect_l(effect);
3266 if (status != NO_ERROR) {
3267 break;
3268 }
Eric Laurentec35a142011-10-05 17:42:25 -07003269 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3270 if (effect->state() == EffectModule::ACTIVE ||
3271 effect->state() == EffectModule::STOPPING) {
3272 effect->start();
3273 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003274 // if the move request is not received from audio policy manager, the effect must be
3275 // re-registered with the new strategy and output
3276 if (dstChain == 0) {
3277 dstChain = effect->chain().promote();
3278 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003279 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003280 status = NO_INIT;
3281 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003282 }
3283 strategy = dstChain->strategy();
3284 }
3285 if (reRegister) {
3286 AudioSystem::unregisterEffect(effect->id());
3287 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003288 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003289 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003290 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003291 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003292 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003293 }
Eric Laurentde070132010-07-13 04:45:46 -07003294 effect = chain->getEffectFromId_l(0);
3295 }
3296
Eric Laurent5baf2af2013-09-12 17:37:00 -07003297 if (status != NO_ERROR) {
3298 for (size_t i = 0; i < removed.size(); i++) {
3299 srcThread->addEffect_l(removed[i]);
3300 if (dstChain != 0 && reRegister) {
3301 AudioSystem::unregisterEffect(removed[i]->id());
3302 AudioSystem::registerEffect(&removed[i]->desc(),
3303 srcThread->id(),
3304 strategy,
3305 sessionId,
3306 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003307 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003308 }
3309 }
3310 }
3311
3312 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313}
3314
Eric Laurent5baf2af2013-09-12 17:37:00 -07003315bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003316{
3317 if (mGlobalEffectEnableTime != 0 &&
3318 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3319 return true;
3320 }
3321
3322 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3323 sp<EffectChain> ec =
3324 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003325 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003326 return true;
3327 }
3328 }
3329 return false;
3330}
3331
Eric Laurent5baf2af2013-09-12 17:37:00 -07003332void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003333{
3334 Mutex::Autolock _l(mLock);
3335
3336 mGlobalEffectEnableTime = systemTime();
3337
3338 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3339 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3340 if (t->mType == ThreadBase::OFFLOAD) {
3341 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3342 }
3343 }
3344
3345}
3346
Eric Laurentaaa44472014-09-12 17:41:50 -07003347status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3348{
Eric Laurentd8365c52017-07-16 15:27:05 -07003349 // clear possible suspended state before parking the chain so that it starts in default state
3350 // when attached to a new record thread
3351 chain->setEffectSuspended_l(FX_IID_AEC, false);
3352 chain->setEffectSuspended_l(FX_IID_NS, false);
3353
Glenn Kastend848eb42016-03-08 13:42:11 -08003354 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003355 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003356 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003357 if (index >= 0) {
3358 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3359 return ALREADY_EXISTS;
3360 }
3361 mOrphanEffectChains.add(session, chain);
3362 return NO_ERROR;
3363}
3364
3365sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3366{
3367 sp<EffectChain> chain;
3368 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003369 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003370 if (index >= 0) {
3371 chain = mOrphanEffectChains.valueAt(index);
3372 mOrphanEffectChains.removeItemsAt(index);
3373 }
3374 return chain;
3375}
3376
3377bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3378{
3379 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003380 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003381 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003382 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003383 if (index >= 0) {
3384 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003385 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003386 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003387 mOrphanEffectChains.removeItemsAt(index);
3388 }
3389 return true;
3390 }
3391 return false;
3392}
3393
3394
Glenn Kastenda6ef132013-01-10 12:31:01 -08003395struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003396#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3397 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003398};
3399
3400int comparEntry(const void *p1, const void *p2)
3401{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003402 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003403}
3404
Glenn Kasten46909e72013-02-26 09:20:22 -08003405#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003406void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407{
Eric Laurent81784c32012-11-19 14:55:58 -08003408 NBAIO_Source *teeSource = source.get();
3409 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003410 // .wav rotation
3411 // There is a benign race condition if 2 threads call this simultaneously.
3412 // They would both traverse the directory, but the result would simply be
3413 // failures at unlink() which are ignored. It's also unlikely since
3414 // normally dumpsys is only done by bugreport or from the command line.
Andy Hungb1fe6e12018-04-19 19:20:00 -07003415 char teePath[PATH_MAX] = "/data/misc/audioserver";
Glenn Kastenda6ef132013-01-10 12:31:01 -08003416 size_t teePathLen = strlen(teePath);
3417 DIR *dir = opendir(teePath);
3418 teePath[teePathLen++] = '/';
3419 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003420#define TEE_MAX_SORT 20 // number of entries to sort
3421#define TEE_MAX_KEEP 10 // number of entries to keep
3422 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003423 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003424 while (entryCount < TEE_MAX_SORT) {
Andy Hungb1fe6e12018-04-19 19:20:00 -07003425 errno = 0; // clear errno before readdir() to track potential errors.
3426 const struct dirent *result = readdir(dir);
3427 if (result == nullptr) {
3428 ALOGW_IF(errno != 0, "tee readdir() failure %s", strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003429 break;
3430 }
3431 // ignore non .wav file entries
Andy Hungb1fe6e12018-04-19 19:20:00 -07003432 const size_t nameLen = strlen(result->d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003433 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Andy Hungb1fe6e12018-04-19 19:20:00 -07003434 strcmp(&result->d_name[nameLen - 4], ".wav")) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003435 continue;
3436 }
Andy Hungb1fe6e12018-04-19 19:20:00 -07003437 (void)audio_utils_strlcpy(entries[entryCount++].mFileName, result->d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003438 }
3439 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003440 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003441 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003442 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3443 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003444 (void) unlink(teePath);
3445 }
3446 }
3447 } else {
3448 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003449 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003450 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003451 }
3452 }
Eric Laurent81784c32012-11-19 14:55:58 -08003453 char teeTime[16];
3454 struct timeval tv;
3455 gettimeofday(&tv, NULL);
3456 struct tm tm;
3457 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003458 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003459 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3460 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003461 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3462 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003463 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003464 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003465 char wavHeader[44];
3466 memcpy(wavHeader,
3467 "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",
3468 sizeof(wavHeader));
3469 NBAIO_Format format = teeSource->format();
3470 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003471 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003472 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003473 wavHeader[22] = channelCount; // number of channels
3474 wavHeader[24] = sampleRate; // sample rate
3475 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003476 wavHeader[32] = frameSize; // block alignment
3477 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003478 write(teeFd, wavHeader, sizeof(wavHeader));
3479 size_t total = 0;
3480 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003481#define TEE_SINK_READ 1024 // frames per I/O operation
3482 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003483 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003484 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003485 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003486 bool wasFirstRead = firstRead;
3487 firstRead = false;
3488 if (actual <= 0) {
3489 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3490 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003491 }
Eric Laurent81784c32012-11-19 14:55:58 -08003492 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003493 }
Eric Laurent81784c32012-11-19 14:55:58 -08003494 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003495 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003496 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003497 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003498 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003499 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003500 uint32_t temp = 44 + total * frameSize - 8;
3501 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003502 write(teeFd, &temp, sizeof(temp));
3503 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003504 temp = total * frameSize;
3505 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003506 write(teeFd, &temp, sizeof(temp));
3507 close(teeFd);
Glenn Kasten9e756632017-10-03 13:01:09 -07003508 // TODO Should create file with temporary name and then rename to final if non-empty.
3509 if (total > 0) {
3510 if (fd >= 0) {
3511 dprintf(fd, "tee copied to %s\n", teePath);
3512 }
3513 } else {
3514 unlink(teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003515 }
Eric Laurent59255e42011-07-27 19:49:51 -07003516 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003517 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003518 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003519 }
Eric Laurent59255e42011-07-27 19:49:51 -07003520 }
3521 }
3522}
Glenn Kasten46909e72013-02-26 09:20:22 -08003523#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003524
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525// ----------------------------------------------------------------------------
3526
3527status_t AudioFlinger::onTransact(
3528 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3529{
3530 return BnAudioFlinger::onTransact(code, data, reply, flags);
3531}
3532
Glenn Kasten63238ef2015-03-02 15:50:29 -08003533} // namespace android