blob: 2a2f6fc66a11166cb67c8349e59d8ca5ef06aca2 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070042#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
44#include <cutils/properties.h>
45
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Mathias Agopian65ab4712010-07-14 17:59:35 -070048#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080049#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Andy Hung6770c6f2015-04-07 13:43:36 -070051#include <media/AudioResamplerPublic.h>
52
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_visualizer.h>
54#include <system/audio_effects/effect_ns.h>
55#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Eric Laurentfeb0db62011-07-22 09:04:31 -070059#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080060
Glenn Kasten9e58b552013-01-18 15:09:48 -080061#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070062#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080063#include <media/nbaio/Pipe.h>
64#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070065#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080066#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070067#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080068
rago3bd1c872016-09-26 12:58:14 -070069//#define BUFLOG_NDEBUG 0
70#include <BufLog.h>
71
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080072#include "TypedLogger.h"
73
Mathias Agopian65ab4712010-07-14 17:59:35 -070074// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070075
John Grossman1c345192012-03-27 14:00:17 -070076// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
Eric Laurentde070132010-07-13 04:45:46 -070088
Mathias Agopian65ab4712010-07-14 17:59:35 -070089namespace android {
90
Glenn Kastenec1d6b52011-12-12 09:04:45 -080091static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
92static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070093static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070094static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten58912562012-04-03 10:45:00 -070096
John Grossman4ff14ba2012-02-08 16:37:41 -080097nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080098
Eric Laurent81784c32012-11-19 14:55:58 -080099uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700100
Eric Laurentfc235202016-12-20 18:48:17 -0800101
Glenn Kasten46909e72013-02-26 09:20:22 -0800102#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800103bool AudioFlinger::mTeeSinkInputEnabled = false;
104bool AudioFlinger::mTeeSinkOutputEnabled = false;
105bool AudioFlinger::mTeeSinkTrackEnabled = false;
106
107size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
108size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
109size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800110#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800111
Eric Laurent813e2a72013-08-31 12:59:48 -0700112// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
113// we define a minimum time during which a global effect is considered enabled.
114static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
115
Eric Laurentfc235202016-12-20 18:48:17 -0800116Mutex gLock;
117wp<AudioFlinger> gAudioFlinger;
118
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700119// Keep a strong reference to media.log service around forever.
120// The service is within our parent process so it can never die in a way that we could observe.
121// These two variables are const after initialization.
122static sp<IBinder> sMediaLogServiceAsBinder;
123static sp<IMediaLogService> sMediaLogService;
124
125static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
126
127static void sMediaLogInit()
128{
129 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
130 if (sMediaLogServiceAsBinder != 0) {
131 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
132 }
133}
134
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135// ----------------------------------------------------------------------------
136
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700137std::string formatToString(audio_format_t format) {
138 std::string result;
139 FormatConverter::toString(format, result);
140 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800141}
142
Mathias Agopian65ab4712010-07-14 17:59:35 -0700143// ----------------------------------------------------------------------------
144
145AudioFlinger::AudioFlinger()
146 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800147 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800148 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800149 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700150 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800151 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800152 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700153 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700155 mBtNrecIsOff(false),
156 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700157 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700158 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700159 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700160{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700161 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
162 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
163 // zero ID has a special meaning, so unavailable
164 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
165 }
166
Glenn Kasten949a9262013-04-16 12:35:20 -0700167 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800168 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800169 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800170 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
171 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700172 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800173 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700174
Wei Jia3f273d12015-11-24 09:06:49 -0800175 // reset battery stats.
176 // if the audio service has crashed, battery stats could be left
177 // in bad state, reset the state upon service start.
178 BatteryNotifier::getInstance().noteResetAudio();
179
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700180 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700181 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
182
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800183 mMediaLogNotifier->run("MediaLogNotifier");
184
Glenn Kasten46909e72013-02-26 09:20:22 -0800185#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800186 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800187 (void) property_get("ro.debuggable", value, "0");
188 int debuggable = atoi(value);
189 int teeEnabled = 0;
190 if (debuggable) {
191 (void) property_get("af.tee", value, "0");
192 teeEnabled = atoi(value);
193 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800194 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700195 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800196 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700197 }
198 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700200 }
201 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800202 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700203 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800204#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700205}
206
207void AudioFlinger::onFirstRef()
208{
Eric Laurent93575202011-01-18 18:39:02 -0800209 Mutex::Autolock _l(mLock);
210
Dima Zavin799a70e2011-04-18 16:57:27 -0700211 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800212 char val_str[PROPERTY_VALUE_MAX] = { 0 };
213 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
214 uint32_t int_val;
215 if (1 == sscanf(val_str, "%u", &int_val)) {
216 mStandbyTimeInNsecs = milliseconds(int_val);
217 ALOGI("Using %u mSec as standby time.", int_val);
218 } else {
219 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
220 ALOGI("Using default %u mSec as standby time.",
221 (uint32_t)(mStandbyTimeInNsecs / 1000000));
222 }
223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224
Eric Laurent1c333e22014-05-20 10:48:17 -0700225 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700226
Eric Laurenta4c5a552012-03-29 10:12:40 -0700227 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800228
229 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700230}
231
232AudioFlinger::~AudioFlinger()
233{
234 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700235 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700236 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700237 }
238 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700239 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700240 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700242
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800243 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
244 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700245 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700247
248 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700249 if (sMediaLogService != 0) {
250 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
251 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
252 mUnregisteredWriters.pop();
253 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700254 }
255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256}
257
Eric Laurentfc235202016-12-20 18:48:17 -0800258//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800259__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800260status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
261 const audio_attributes_t *attr,
262 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700263 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800264 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800265 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800266 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700267 sp<MmapStreamInterface>& interface,
268 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800269{
270 sp<AudioFlinger> af;
271 {
272 Mutex::Autolock _l(gLock);
273 af = gAudioFlinger.promote();
274 }
275 status_t ret = NO_INIT;
276 if (af != 0) {
277 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800278 direction, attr, config, client, deviceId,
279 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800280 }
281 return ret;
282}
283
Eric Laurent6acd1d42017-01-04 14:23:29 -0800284status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
285 const audio_attributes_t *attr,
286 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700287 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800288 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800289 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800290 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700291 sp<MmapStreamInterface>& interface,
292 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800293{
294 status_t ret = initCheck();
295 if (ret != NO_ERROR) {
296 return ret;
297 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800298 audio_session_t actualSessionId = *sessionId;
299 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
300 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
301 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800302 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700303 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800304 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
305 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
306 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
307 fullConfig.sample_rate = config->sample_rate;
308 fullConfig.channel_mask = config->channel_mask;
309 fullConfig.format = config->format;
310 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800311 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800312 &streamType, client.clientUid,
313 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800314 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
315 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700316 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800317 } else {
318 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800319 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800320 client.clientPid,
321 client.clientUid,
322 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700323 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800324 }
325 if (ret != NO_ERROR) {
326 return ret;
327 }
328
329 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
330 // audio policy manager and we can retrieve it
331 sp<MmapThread> thread = mMmapThreads.valueFor(io);
332 if (thread != 0) {
333 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800334 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700335 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800336 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800337 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700338 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800339 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700340 } else {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800341 AudioSystem::releaseInput(io, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700342 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800343 ret = NO_INIT;
344 }
345
346 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
347
Eric Laurentfc235202016-12-20 18:48:17 -0800348 return ret;
349}
350
Eric Laurenta4c5a552012-03-29 10:12:40 -0700351static const char * const audio_interfaces[] = {
352 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
353 AUDIO_HARDWARE_MODULE_ID_A2DP,
354 AUDIO_HARDWARE_MODULE_ID_USB,
355};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700356
Phil Burk062e67a2015-02-11 13:40:50 -0800357AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700358 audio_module_handle_t module,
359 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700360{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700361 // if module is 0, the request comes from an old policy manager and we should load
362 // well known modules
363 if (module == 0) {
364 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700365 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700366 loadHwModule_l(audio_interfaces[i]);
367 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700368 // then try to find a module supporting the requested device.
369 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
370 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700371 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
372 uint32_t supportedDevices;
373 if (dev->getSupportedDevices(&supportedDevices) == OK &&
374 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700375 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700376 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700377 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700378 } else {
379 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700380 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
381 if (audioHwDevice != NULL) {
382 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700383 }
384 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700385
Dima Zavin799a70e2011-04-18 16:57:27 -0700386 return NULL;
387}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388
Glenn Kasten0f11b512014-01-31 16:18:54 -0800389void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390{
391 const size_t SIZE = 256;
392 char buffer[SIZE];
393 String8 result;
394
395 result.append("Clients:\n");
396 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800397 sp<Client> client = mClients.valueAt(i).promote();
398 if (client != 0) {
399 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
400 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 }
402 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700403
Eric Laurentd1b28d42013-09-18 18:47:13 -0700404 result.append("Notification Clients:\n");
405 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
406 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
407 result.append(buffer);
408 }
409
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700410 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800411 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700412 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
413 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800414 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700415 result.append(buffer);
416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700418}
419
420
Glenn Kasten0f11b512014-01-31 16:18:54 -0800421void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422{
423 const size_t SIZE = 256;
424 char buffer[SIZE];
425 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800426 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427
John Grossman4ff14ba2012-02-08 16:37:41 -0800428 snprintf(buffer, SIZE, "Hardware status: %d\n"
429 "Standby Time mSec: %u\n",
430 hardwareStatus,
431 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432 result.append(buffer);
433 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434}
435
Glenn Kasten0f11b512014-01-31 16:18:54 -0800436void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437{
438 const size_t SIZE = 256;
439 char buffer[SIZE];
440 String8 result;
441 snprintf(buffer, SIZE, "Permission Denial: "
442 "can't dump AudioFlinger from pid=%d, uid=%d\n",
443 IPCThreadState::self()->getCallingPid(),
444 IPCThreadState::self()->getCallingUid());
445 result.append(buffer);
446 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447}
448
Eric Laurent81784c32012-11-19 14:55:58 -0800449bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450{
451 bool locked = false;
452 for (int i = 0; i < kDumpLockRetries; ++i) {
453 if (mutex.tryLock() == NO_ERROR) {
454 locked = true;
455 break;
456 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800457 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458 }
459 return locked;
460}
461
462status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
463{
Glenn Kasten44deb052012-02-05 18:09:08 -0800464 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 dumpPermissionDenial(fd, args);
466 } else {
467 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800468 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 if (!hardwareLocked) {
470 String8 result(kHardwareLockedString);
471 write(fd, result.string(), result.size());
472 } else {
473 mHardwareLock.unlock();
474 }
475
Eric Laurent81784c32012-11-19 14:55:58 -0800476 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477
478 // failed to lock - AudioFlinger is probably deadlocked
479 if (!locked) {
480 String8 result(kDeadlockedString);
481 write(fd, result.string(), result.size());
482 }
483
Eric Laurent021cf962014-05-13 10:18:14 -0700484 bool clientLocked = dumpTryLock(mClientLock);
485 if (!clientLocked) {
486 String8 result(kClientLockedString);
487 write(fd, result.string(), result.size());
488 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700489
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700490 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700491 mEffectsFactoryHal->dumpEffects(fd);
492 } else {
493 String8 result(kNoEffectsFactory);
494 write(fd, result.string(), result.size());
495 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700496
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700498 if (clientLocked) {
499 mClientLock.unlock();
500 }
501
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502 dumpInternals(fd, args);
503
504 // dump playback threads
505 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
506 mPlaybackThreads.valueAt(i)->dump(fd, args);
507 }
508
509 // dump record threads
510 for (size_t i = 0; i < mRecordThreads.size(); i++) {
511 mRecordThreads.valueAt(i)->dump(fd, args);
512 }
513
Eric Laurent6acd1d42017-01-04 14:23:29 -0800514 // dump mmap threads
515 for (size_t i = 0; i < mMmapThreads.size(); i++) {
516 mMmapThreads.valueAt(i)->dump(fd, args);
517 }
518
Eric Laurentaaa44472014-09-12 17:41:50 -0700519 // dump orphan effect chains
520 if (mOrphanEffectChains.size() != 0) {
521 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
522 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
523 mOrphanEffectChains.valueAt(i)->dump(fd, args);
524 }
525 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700526 // dump all hardware devs
527 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700528 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
529 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700531
Glenn Kasten46909e72013-02-26 09:20:22 -0800532#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700533 // dump the serially shared record tee sink
534 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700535 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700536 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800537#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700538
rago3bd1c872016-09-26 12:58:14 -0700539 BUFLOG_RESET;
540
Glenn Kastend65d73c2012-06-22 17:21:07 -0700541 if (locked) {
542 mLock.unlock();
543 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800544
545 // append a copy of media.log here by forwarding fd to it, but don't attempt
546 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700547 if (sMediaLogServiceAsBinder != 0) {
548 dprintf(fd, "\nmedia.log:\n");
549 Vector<String16> args;
550 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800551 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700552
553 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700554 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700555 bool unreachableMemory = false;
556 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700557 if (arg == String16("-m")) {
558 dumpMem = true;
559 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700560 unreachableMemory = true;
561 }
562 }
563
Andy Hung07b745e2016-05-23 16:21:07 -0700564 if (dumpMem) {
565 dprintf(fd, "\nDumping memory:\n");
566 std::string s = dumpMemoryAddresses(100 /* limit */);
567 write(fd, s.c_str(), s.size());
568 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700569 if (unreachableMemory) {
570 dprintf(fd, "\nDumping unreachable memory:\n");
571 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700572 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700573 write(fd, s.c_str(), s.size());
574 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 }
576 return NO_ERROR;
577}
578
Eric Laurent021cf962014-05-13 10:18:14 -0700579sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800580{
Eric Laurent021cf962014-05-13 10:18:14 -0700581 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800582 // If pid is already in the mClients wp<> map, then use that entry
583 // (for which promote() is always != 0), otherwise create a new entry and Client.
584 sp<Client> client = mClients.valueFor(pid).promote();
585 if (client == 0) {
586 client = new Client(this, pid);
587 mClients.add(pid, client);
588 }
589
590 return client;
591}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592
Glenn Kasten9e58b552013-01-18 15:09:48 -0800593sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
594{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700595 // If there is no memory allocated for logs, return a dummy writer that does nothing.
596 // Similarly if we can't contact the media.log service, also return a dummy writer.
597 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800598 return new NBLog::Writer();
599 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700600 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
601 // If allocation fails, consult the vector of previously unregistered writers
602 // and garbage-collect one or more them until an allocation succeeds
603 if (shared == 0) {
604 Mutex::Autolock _l(mUnregisteredWritersLock);
605 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
606 {
607 // Pick the oldest stale writer to garbage-collect
608 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
609 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700610 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700611 // Now the media.log remote reference to IMemory is gone. When our last local
612 // reference to IMemory also drops to zero at end of this block,
613 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
614 }
615 // Re-attempt the allocation
616 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
617 if (shared != 0) {
618 goto success;
619 }
620 }
621 // Even after garbage-collecting all old writers, there is still not enough memory,
622 // so return a dummy writer
623 return new NBLog::Writer();
624 }
625success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800626 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
627 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
628 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700629 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800630 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800631}
632
633void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
634{
Glenn Kasten685ef092013-02-04 08:15:34 -0800635 if (writer == 0) {
636 return;
637 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800638 sp<IMemory> iMemory(writer->getIMemory());
639 if (iMemory == 0) {
640 return;
641 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700642 // Rather than removing the writer immediately, append it to a queue of old writers to
643 // be garbage-collected later. This allows us to continue to view old logs for a while.
644 Mutex::Autolock _l(mUnregisteredWritersLock);
645 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800646}
647
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648// IAudioFlinger interface
649
Eric Laurent21da6472017-11-09 16:29:26 -0800650sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
651 CreateTrackOutput& output,
652 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653{
654 sp<PlaybackThread::Track> track;
655 sp<TrackHandle> trackHandle;
656 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800658 audio_stream_type_t streamType;
659 audio_port_handle_t portId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660
Eric Laurent21da6472017-11-09 16:29:26 -0800661 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700662 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800663 uid_t clientUid = input.clientInfo.clientUid;
664 if (!isTrustedCallingUid(callingUid)) {
665 ALOGW_IF(clientUid != callingUid,
666 "%s uid %d tried to pass itself off as %d",
667 __FUNCTION__, callingUid, clientUid);
668 clientUid = callingUid;
669 updatePid = true;
670 }
671 pid_t clientPid = input.clientInfo.clientPid;
672 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700673 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800674 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700675 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800676 __func__, callingUid, callingPid, clientPid);
677 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700678 }
679
Eric Laurent21da6472017-11-09 16:29:26 -0800680 audio_session_t sessionId = input.sessionId;
681 if (sessionId == AUDIO_SESSION_ALLOCATE) {
682 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800683 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
684 lStatus = BAD_VALUE;
685 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800686 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800687
Eric Laurent21da6472017-11-09 16:29:26 -0800688 output.sessionId = sessionId;
689 output.outputId = AUDIO_IO_HANDLE_NONE;
690 output.selectedDeviceId = input.selectedDeviceId;
691
692 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
693 clientUid, &input.config, input.flags,
694 &output.selectedDeviceId, &portId);
695
696 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
697 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
698 goto Exit;
699 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800700 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
701 // but if someone uses binder directly they could bypass that and cause us to crash
702 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000703 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704 lStatus = BAD_VALUE;
705 goto Exit;
706 }
707
Glenn Kasten53b5d092014-02-05 10:00:23 -0800708 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800709 if (!audio_is_output_channel(input.config.channel_mask)) {
710 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800711 lStatus = BAD_VALUE;
712 goto Exit;
713 }
714
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700715 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800716 if (!audio_is_valid_format(input.config.format)) {
717 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700718 lStatus = BAD_VALUE;
719 goto Exit;
720 }
721
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722 {
723 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800724 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800726 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 lStatus = BAD_VALUE;
728 goto Exit;
729 }
730
Eric Laurent21da6472017-11-09 16:29:26 -0800731 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732
Glenn Kastene848bd92014-03-13 15:00:32 -0700733 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800734 // check if an effect chain with the same session ID is present on another
735 // output thread and move it here.
736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
737 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
738 if (mPlaybackThreads.keyAt(i) != output.outputId) {
739 uint32_t sessions = t->hasAudioSession(sessionId);
740 if (sessions & ThreadBase::EFFECT_SESSION) {
741 effectThread = t.get();
742 break;
Eric Laurentde070132010-07-13 04:45:46 -0700743 }
744 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700745 }
Eric Laurent21da6472017-11-09 16:29:26 -0800746 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747
Eric Laurent21da6472017-11-09 16:29:26 -0800748 output.sampleRate = input.config.sample_rate;
749 output.frameCount = input.frameCount;
750 output.notificationFrameCount = input.notificationFrameCount;
751 output.flags = input.flags;
752
753 track = thread->createTrack_l(client, streamType, &output.sampleRate, input.config.format,
754 input.config.channel_mask,
755 &output.frameCount, &output.notificationFrameCount,
756 input.notificationsPerBuffer, input.speed,
757 input.sharedBuffer, sessionId, &output.flags,
758 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800759 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700760 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700761
Eric Laurent21da6472017-11-09 16:29:26 -0800762 output.afFrameCount = thread->frameCount();
763 output.afSampleRate = thread->sampleRate();
764 output.afLatencyMs = thread->latency();
765
Eric Laurent39e94f82010-07-28 01:32:47 -0700766 // move effect chain to this output thread if an effect on same session was waiting
767 // for a track to be created
768 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700769 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700770 Mutex::Autolock _dl(thread->mLock);
771 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800772 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700773 }
Eric Laurenta011e352012-03-29 15:51:43 -0700774
775 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700776 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800777 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700778 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700779 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700780 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700781 } else {
782 mPendingSyncEvents[i]->cancel();
783 }
Eric Laurenta011e352012-03-29 15:51:43 -0700784 mPendingSyncEvents.removeAt(i);
785 i--;
786 }
787 }
788 }
Glenn Kastene198c362013-08-13 09:13:36 -0700789
Eric Laurent21da6472017-11-09 16:29:26 -0800790 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 }
Glenn Kastene198c362013-08-13 09:13:36 -0700792
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700793 if (lStatus != NO_ERROR) {
794 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700795 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700796 // Don't hold mClientLock when releasing the reference on the track as the
797 // destructor will acquire it.
798 {
799 Mutex::Autolock _cl(mClientLock);
800 client.clear();
801 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700803 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700806 // return handle to client
807 trackHandle = new TrackHandle(track);
808
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800810 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
811 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
812 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700813 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return trackHandle;
815}
816
Glenn Kasten2c073da2016-02-26 09:14:08 -0800817uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818{
819 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800820 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800822 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 return 0;
824 }
825 return thread->sampleRate();
826}
827
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800828audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829{
830 Mutex::Autolock _l(mLock);
831 PlaybackThread *thread = checkPlaybackThread_l(output);
832 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000833 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800834 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 }
836 return thread->format();
837}
838
Glenn Kasten2c073da2016-02-26 09:14:08 -0800839size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
841 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800842 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800844 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0;
846 }
Glenn Kasten58912562012-04-03 10:45:00 -0700847 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
848 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 return thread->frameCount();
850}
851
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700852size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
853{
854 Mutex::Autolock _l(mLock);
855 ThreadBase *thread = checkThread_l(ioHandle);
856 if (thread == NULL) {
857 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
858 return 0;
859 }
860 return thread->frameCountHAL();
861}
862
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800863uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864{
865 Mutex::Autolock _l(mLock);
866 PlaybackThread *thread = checkPlaybackThread_l(output);
867 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800868 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869 return 0;
870 }
871 return thread->latency();
872}
873
874status_t AudioFlinger::setMasterVolume(float value)
875{
Eric Laurenta1884f92011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return ret;
879 }
880
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 // check calling permissions
882 if (!settingsAllowed()) {
883 return PERMISSION_DENIED;
884 }
885
Eric Laurenta4c5a552012-03-29 10:12:40 -0700886 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700887 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700888
John Grossmanee578c02012-07-23 17:05:46 -0700889 // Set master volume in the HALs which support it.
890 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
891 AutoMutex lock(mHardwareLock);
892 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800893
John Grossmanee578c02012-07-23 17:05:46 -0700894 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
895 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700896 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800897 }
John Grossmanee578c02012-07-23 17:05:46 -0700898 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900
John Grossmanee578c02012-07-23 17:05:46 -0700901 // Now set the master volume in each playback thread. Playback threads
902 // assigned to HALs which do not have master volume support will apply
903 // master volume during the mix operation. Threads with HALs which do
904 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700905 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
906 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
907 continue;
908 }
John Grossmanee578c02012-07-23 17:05:46 -0700909 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911
912 return NO_ERROR;
913}
914
Glenn Kastenf78aee72012-01-04 11:00:47 -0800915status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916{
Eric Laurenta1884f92011-08-23 08:25:03 -0700917 status_t ret = initCheck();
918 if (ret != NO_ERROR) {
919 return ret;
920 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921
922 // check calling permissions
923 if (!settingsAllowed()) {
924 return PERMISSION_DENIED;
925 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800926 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000927 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 return BAD_VALUE;
929 }
930
931 { // scope for the lock
932 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700933 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700935 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936 mHardwareStatus = AUDIO_HW_IDLE;
937 }
938
939 if (NO_ERROR == ret) {
940 Mutex::Autolock _l(mLock);
941 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800942 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700943 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 }
945
946 return ret;
947}
948
949status_t AudioFlinger::setMicMute(bool state)
950{
Eric Laurenta1884f92011-08-23 08:25:03 -0700951 status_t ret = initCheck();
952 if (ret != NO_ERROR) {
953 return ret;
954 }
955
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956 // check calling permissions
957 if (!settingsAllowed()) {
958 return PERMISSION_DENIED;
959 }
960
961 AutoMutex lock(mHardwareLock);
962 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700963 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700964 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
965 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700966 if (result != NO_ERROR) {
967 ret = result;
968 }
969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970 mHardwareStatus = AUDIO_HW_IDLE;
971 return ret;
972}
973
974bool AudioFlinger::getMicMute() const
975{
Eric Laurenta1884f92011-08-23 08:25:03 -0700976 status_t ret = initCheck();
977 if (ret != NO_ERROR) {
978 return false;
979 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800980 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700981 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800982 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800984 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700985 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
986 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800987 if (result == NO_ERROR) {
988 mute = mute && state;
989 }
990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800992
993 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994}
995
996status_t AudioFlinger::setMasterMute(bool muted)
997{
John Grossmand8f178d2012-07-20 14:51:35 -0700998 status_t ret = initCheck();
999 if (ret != NO_ERROR) {
1000 return ret;
1001 }
1002
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003 // check calling permissions
1004 if (!settingsAllowed()) {
1005 return PERMISSION_DENIED;
1006 }
1007
John Grossmanee578c02012-07-23 17:05:46 -07001008 Mutex::Autolock _l(mLock);
1009 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001010
John Grossmanee578c02012-07-23 17:05:46 -07001011 // Set master mute in the HALs which support it.
1012 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1013 AutoMutex lock(mHardwareLock);
1014 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001015
John Grossmanee578c02012-07-23 17:05:46 -07001016 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1017 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001018 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001019 }
John Grossmanee578c02012-07-23 17:05:46 -07001020 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001021 }
1022
John Grossmanee578c02012-07-23 17:05:46 -07001023 // Now set the master mute in each playback thread. Playback threads
1024 // assigned to HALs which do not have master mute support will apply master
1025 // mute during the mix operation. Threads with HALs which do support master
1026 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001027 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1028 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1029 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001030 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031
1032 return NO_ERROR;
1033}
1034
1035float AudioFlinger::masterVolume() const
1036{
Glenn Kasten98067102011-12-13 11:47:54 -08001037 Mutex::Autolock _l(mLock);
1038 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039}
1040
1041bool AudioFlinger::masterMute() const
1042{
Glenn Kasten98067102011-12-13 11:47:54 -08001043 Mutex::Autolock _l(mLock);
1044 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045}
1046
John Grossman4ff14ba2012-02-08 16:37:41 -08001047float AudioFlinger::masterVolume_l() const
1048{
John Grossman4ff14ba2012-02-08 16:37:41 -08001049 return mMasterVolume;
1050}
1051
John Grossmand8f178d2012-07-20 14:51:35 -07001052bool AudioFlinger::masterMute_l() const
1053{
John Grossmanee578c02012-07-23 17:05:46 -07001054 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001055}
1056
Eric Laurent223fd5c2014-11-11 13:43:36 -08001057status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1058{
1059 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001060 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001061 return BAD_VALUE;
1062 }
1063 pid_t caller = IPCThreadState::self()->getCallingPid();
1064 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001065 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001066 return PERMISSION_DENIED;
1067 }
1068
1069 return NO_ERROR;
1070}
1071
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001072status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1073 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074{
1075 // check calling permissions
1076 if (!settingsAllowed()) {
1077 return PERMISSION_DENIED;
1078 }
1079
Eric Laurent223fd5c2014-11-11 13:43:36 -08001080 status_t status = checkStreamType(stream);
1081 if (status != NO_ERROR) {
1082 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001084 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085
1086 AutoMutex lock(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001087 Vector<VolumeInterface *> volumeInterfaces;
Glenn Kasten142f5192014-03-25 17:44:59 -07001088 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001089 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1090 if (volumeInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 return BAD_VALUE;
1092 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001093 volumeInterfaces.add(volumeInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 }
1095
1096 mStreamTypes[stream].volume = value;
1097
Eric Laurent6acd1d42017-01-04 14:23:29 -08001098 if (volumeInterfaces.size() == 0) {
1099 volumeInterfaces = getAllVolumeInterfaces_l();
1100 }
1101 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1102 volumeInterfaces[i]->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 }
1104
1105 return NO_ERROR;
1106}
1107
Glenn Kastenfff6d712012-01-12 16:38:12 -08001108status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109{
1110 // check calling permissions
1111 if (!settingsAllowed()) {
1112 return PERMISSION_DENIED;
1113 }
1114
Eric Laurent223fd5c2014-11-11 13:43:36 -08001115 status_t status = checkStreamType(stream);
1116 if (status != NO_ERROR) {
1117 return status;
1118 }
1119 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1120
1121 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001122 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 return BAD_VALUE;
1124 }
1125
Eric Laurent93575202011-01-18 18:39:02 -08001126 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001128 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1129 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1130 volumeInterfaces[i]->setStreamMute(stream, muted);
1131 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132
1133 return NO_ERROR;
1134}
1135
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001136float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001138 status_t status = checkStreamType(stream);
1139 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 return 0.0f;
1141 }
1142
1143 AutoMutex lock(mLock);
1144 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001145 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001146 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1147 if (volumeInterface != NULL) {
1148 volume = volumeInterface->streamVolume(stream);
1149 } else {
1150 volume = 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001153 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 }
1155
1156 return volume;
1157}
1158
Glenn Kastenfff6d712012-01-12 16:38:12 -08001159bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001161 status_t status = checkStreamType(stream);
1162 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 return true;
1164 }
1165
Glenn Kasten6637baa2012-01-09 09:40:36 -08001166 AutoMutex lock(mLock);
1167 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168}
1169
Eric Laurent054d9d32015-04-24 08:48:48 -07001170
1171void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1172{
1173 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1174 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1175 }
1176}
1177
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001178status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001180 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1181 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001182
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183 // check calling permissions
1184 if (!settingsAllowed()) {
1185 return PERMISSION_DENIED;
1186 }
1187
Glenn Kasten142f5192014-03-25 17:44:59 -07001188 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1189 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001190 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001191 // result will remain NO_INIT if no audio device is present
1192 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001193 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001194 AutoMutex lock(mHardwareLock);
1195 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1196 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001197 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1198 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001199 // return success if at least one audio device accepts the parameters as not all
1200 // HALs are requested to support all parameters. If no audio device supports the
1201 // requested parameters, the last error is reported.
1202 if (final_result != NO_ERROR) {
1203 final_result = result;
1204 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001205 }
1206 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001207 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001208 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1209 AudioParameter param = AudioParameter(keyValuePairs);
1210 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001211 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1212 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001213 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001214 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001215 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001216 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001217 }
1218 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001219 String8 screenState;
1220 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001221 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001222 if (isOff != (AudioFlinger::mScreenState & 1)) {
1223 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001224 }
1225 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001226 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 }
1228
1229 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1230 // and the thread is exited once the lock is released
1231 sp<ThreadBase> thread;
1232 {
1233 Mutex::Autolock _l(mLock);
1234 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001235 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001237 if (thread == 0) {
1238 thread = checkMmapThread_l(ioHandle);
1239 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001240 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001241 // indicate output device change to all input threads for pre processing
1242 AudioParameter param = AudioParameter(keyValuePairs);
1243 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001244 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1245 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001246 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 }
1249 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001250 if (thread != 0) {
1251 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 }
1253 return BAD_VALUE;
1254}
1255
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001256String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001258 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1259 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260
Eric Laurenta4c5a552012-03-29 10:12:40 -07001261 Mutex::Autolock _l(mLock);
1262
Glenn Kasten142f5192014-03-25 17:44:59 -07001263 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001264 String8 out_s8;
1265
Dima Zavin799a70e2011-04-18 16:57:27 -07001266 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001267 String8 s;
1268 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001269 {
1270 AutoMutex lock(mHardwareLock);
1271 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001272 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1273 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001274 mHardwareStatus = AUDIO_HW_IDLE;
1275 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001276 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001277 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001278 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279 }
1280
Eric Laurent6acd1d42017-01-04 14:23:29 -08001281 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1282 if (thread == NULL) {
1283 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1284 if (thread == NULL) {
1285 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1286 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001287 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001288 }
1289 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001291 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292}
1293
Glenn Kastendd8104c2012-07-02 12:42:44 -07001294size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1295 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296{
Eric Laurenta1884f92011-08-23 08:25:03 -07001297 status_t ret = initCheck();
1298 if (ret != NO_ERROR) {
1299 return 0;
1300 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001301 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001302 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001303 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001304 return 0;
1305 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001306
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001307 AutoMutex lock(mHardwareLock);
1308 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001309 audio_config_t config, proposed;
1310 memset(&proposed, 0, sizeof(proposed));
1311 proposed.sample_rate = sampleRate;
1312 proposed.channel_mask = channelMask;
1313 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001314
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001315 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001316 size_t frames;
1317 for (;;) {
1318 // Note: config is currently a const parameter for get_input_buffer_size()
1319 // but we use a copy from proposed in case config changes from the call.
1320 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001321 status_t result = dev->getInputBufferSize(&config, &frames);
1322 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001323 break; // hal success, config is the result
1324 }
1325 // change one parameter of the configuration each iteration to a more "common" value
1326 // to see if the device will support it.
1327 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1328 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1329 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1330 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1331 } else {
1332 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1333 "format %#x, channelMask 0x%X",
1334 sampleRate, format, channelMask);
1335 break; // retries failed, break out of loop with frames == 0.
1336 }
1337 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001338 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001339 if (frames > 0 && config.sample_rate != sampleRate) {
1340 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1341 }
1342 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001343}
1344
Glenn Kasten5f972c02014-01-13 09:59:31 -08001345uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001346{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001347 Mutex::Autolock _l(mLock);
1348
1349 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1350 if (recordThread != NULL) {
1351 return recordThread->getInputFramesLost();
1352 }
1353 return 0;
1354}
1355
1356status_t AudioFlinger::setVoiceVolume(float value)
1357{
Eric Laurenta1884f92011-08-23 08:25:03 -07001358 status_t ret = initCheck();
1359 if (ret != NO_ERROR) {
1360 return ret;
1361 }
1362
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363 // check calling permissions
1364 if (!settingsAllowed()) {
1365 return PERMISSION_DENIED;
1366 }
1367
1368 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001369 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001370 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001371 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372 mHardwareStatus = AUDIO_HW_IDLE;
1373
1374 return ret;
1375}
1376
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001377status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001378 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 Mutex::Autolock _l(mLock);
1381
1382 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1383 if (playbackThread != NULL) {
1384 return playbackThread->getRenderPosition(halFrames, dspFrames);
1385 }
1386
1387 return BAD_VALUE;
1388}
1389
1390void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1391{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001393 if (client == 0) {
1394 return;
1395 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001396 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001397 {
1398 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001399 if (mNotificationClients.indexOfKey(pid) < 0) {
1400 sp<NotificationClient> notificationClient = new NotificationClient(this,
1401 client,
1402 pid);
1403 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001404
Eric Laurent021cf962014-05-13 10:18:14 -07001405 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406
Marco Nelissen06b46062014-11-14 07:58:25 -08001407 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001408 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001409 }
1410 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411
Eric Laurent021cf962014-05-13 10:18:14 -07001412 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001413 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001414 // the config change is always sent from playback or record threads to avoid deadlock
1415 // with AudioSystem::gLock
1416 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001417 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001419
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001420 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001421 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422 }
1423}
1424
1425void AudioFlinger::removeNotificationClient(pid_t pid)
1426{
1427 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001428 {
1429 Mutex::Autolock _cl(mClientLock);
1430 mNotificationClients.removeItem(pid);
1431 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001432
Steve Block3856b092011-10-20 11:56:00 +01001433 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001434 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001435 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001436 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001437 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001438 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001439 if (ref->mPid == pid) {
1440 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001441 mAudioSessionRefs.removeAt(i);
1442 delete ref;
1443 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001444 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001445 } else {
1446 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001447 }
1448 }
1449 if (removed) {
1450 purgeStaleEffects_l();
1451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452}
1453
Eric Laurent73e26b62015-04-27 16:55:58 -07001454void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001455 const sp<AudioIoDescriptor>& ioDesc,
1456 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457{
Eric Laurent021cf962014-05-13 10:18:14 -07001458 Mutex::Autolock _l(mClientLock);
1459 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001461 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1462 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464 }
1465}
1466
Eric Laurent021cf962014-05-13 10:18:14 -07001467// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468void AudioFlinger::removeClient_l(pid_t pid)
1469{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001470 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001471 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 mClients.removeItem(pid);
1473}
1474
Eric Laurent717e1282012-06-29 16:36:52 -07001475// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001476sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1477 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001478{
1479 sp<PlaybackThread> thread;
1480
1481 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1482 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1483 ALOG_ASSERT(thread == 0);
1484 thread = mPlaybackThreads.valueAt(i);
1485 }
1486 }
1487
1488 return thread;
1489}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492
1493// ----------------------------------------------------------------------------
1494
1495AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1496 : RefBase(),
1497 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001498 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301500 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1501 heapSize *= 1024;
1502 if (!heapSize) {
1503 heapSize = kClientSharedHeapSizeBytes;
1504 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1505 // invalidated tracks
1506 if (!audioFlinger->isLowRamDevice()) {
1507 heapSize *= kClientSharedHeapSizeMultiplier;
1508 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001509 }
1510 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511}
1512
Eric Laurent021cf962014-05-13 10:18:14 -07001513// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514AudioFlinger::Client::~Client()
1515{
1516 mAudioFlinger->removeClient_l(mPid);
1517}
1518
Glenn Kasten435dbe62012-01-30 10:15:48 -08001519sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520{
1521 return mMemoryDealer;
1522}
1523
1524// ----------------------------------------------------------------------------
1525
1526AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1527 const sp<IAudioFlingerClient>& client,
1528 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001529 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530{
1531}
1532
1533AudioFlinger::NotificationClient::~NotificationClient()
1534{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535}
1536
Glenn Kasten0f11b512014-01-31 16:18:54 -08001537void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538{
1539 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001540 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541}
1542
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001543// ----------------------------------------------------------------------------
1544AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1545 : mPendingRequests(false) {}
1546
1547
1548void AudioFlinger::MediaLogNotifier::requestMerge() {
1549 AutoMutex _l(mMutex);
1550 mPendingRequests = true;
1551 mCond.signal();
1552}
1553
1554bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001555 // Should already have been checked, but just in case
1556 if (sMediaLogService == 0) {
1557 return false;
1558 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001559 // Wait until there are pending requests
1560 {
1561 AutoMutex _l(mMutex);
1562 mPendingRequests = false; // to ignore past requests
1563 while (!mPendingRequests) {
1564 mCond.wait(mMutex);
1565 // TODO may also need an exitPending check
1566 }
1567 mPendingRequests = false;
1568 }
1569 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001570 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001571 usleep(kPostTriggerSleepPeriod);
1572 return true;
1573}
1574
1575void AudioFlinger::requestLogMerge() {
1576 mMediaLogNotifier->requestMerge();
1577}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578
1579// ----------------------------------------------------------------------------
1580
Eric Laurentf14db3c2017-12-08 14:20:36 -08001581sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1582 CreateRecordOutput& output,
1583 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584{
1585 sp<RecordThread::RecordTrack> recordTrack;
1586 sp<RecordHandle> recordHandle;
1587 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001589 audio_session_t sessionId = input.sessionId;
1590 audio_port_handle_t portId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591
Eric Laurentf14db3c2017-12-08 14:20:36 -08001592 output.cblk.clear();
1593 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001594 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001595
Eric Laurentf14db3c2017-12-08 14:20:36 -08001596 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001597 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001598 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001599 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001600 ALOGW_IF(clientUid != callingUid,
1601 "%s uid %d tried to pass itself off as %d",
1602 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001603 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001604 updatePid = true;
1605 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001606 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001607 if (updatePid) {
1608 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001609 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001610 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001611 __func__, callingUid, callingPid, clientPid);
1612 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001613 }
1614
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 // check calling permissions
Eric Laurentf14db3c2017-12-08 14:20:36 -08001616 if (!recordingAllowed(input.opPackageName, input.clientInfo.clientTid, clientUid)) {
1617 ALOGE("createRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 lStatus = PERMISSION_DENIED;
1619 goto Exit;
1620 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001621 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001622 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1623 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001624 lStatus = BAD_VALUE;
1625 goto Exit;
1626 }
1627
Glenn Kasten53b5d092014-02-05 10:00:23 -08001628 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001629 if (!audio_is_input_channel(input.config.channel_mask)) {
1630 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001631 lStatus = BAD_VALUE;
1632 goto Exit;
1633 }
1634
Eric Laurentf14db3c2017-12-08 14:20:36 -08001635 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1636 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1637 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1638 lStatus = BAD_VALUE;
1639 goto Exit;
1640 }
1641
1642 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001643 output.selectedDeviceId = input.selectedDeviceId;
1644 output.flags = input.flags;
1645
1646 client = registerPid(clientPid);
1647
1648 // Not a conventional loop, but a retry loop for at most two iterations total.
1649 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1650 // Exits loop via break on no error of got exit on error
1651 // The sp<> references will be dropped when re-entering scope.
1652 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1653 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001654 // release previously opened input if retrying.
1655 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1656 recordTrack.clear();
1657 AudioSystem::releaseInput(output.inputId, sessionId);
1658 output.inputId = AUDIO_IO_HANDLE_NONE;
1659 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001660 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1661 sessionId,
1662 // FIXME compare to AudioTrack
1663 clientPid,
1664 clientUid,
1665 &input.config,
1666 output.flags, &output.selectedDeviceId, &portId);
1667
Glenn Kasten05997e22014-03-13 15:08:33 -07001668 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001670 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001672 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 lStatus = BAD_VALUE;
1674 goto Exit;
1675 }
1676
Eric Laurentf14db3c2017-12-08 14:20:36 -08001677 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678
Eric Laurentf14db3c2017-12-08 14:20:36 -08001679 output.sampleRate = input.config.sample_rate;
1680 output.frameCount = input.frameCount;
1681 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001682
Eric Laurentf14db3c2017-12-08 14:20:36 -08001683 recordTrack = thread->createRecordTrack_l(client, &output.sampleRate,
1684 input.config.format, input.config.channel_mask,
1685 &output.frameCount, sessionId,
1686 &output.notificationFrameCount,
1687 clientUid, &output.flags,
1688 input.clientInfo.clientTid,
1689 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001690 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001691
Eric Laurentf14db3c2017-12-08 14:20:36 -08001692 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1693 // audio policy manager without FAST constraint
1694 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001695 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001696 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001697
1698 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001699 goto Exit;
1700 }
1701
1702 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1703 // session and move it to this thread.
1704 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1705 if (chain != 0) {
1706 Mutex::Autolock _l(thread->mLock);
1707 thread->addEffectChain_l(chain);
1708 }
1709 break;
1710 }
1711 // End of retry loop.
1712 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 }
Glenn Kastene198c362013-08-13 09:13:36 -07001714
Eric Laurentf14db3c2017-12-08 14:20:36 -08001715 output.cblk = recordTrack->getCblk();
1716 output.buffers = recordTrack->getBuffers();
1717
1718 // return handle to client
1719 recordHandle = new RecordHandle(recordTrack);
1720
1721Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001722 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001723 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001724 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001725 // Don't hold mClientLock when releasing the reference on the track as the
1726 // destructor will acquire it.
1727 {
1728 Mutex::Autolock _cl(mClientLock);
1729 client.clear();
1730 }
Eric Laurent896c9672017-12-08 14:08:45 -08001731 recordTrack.clear();
1732 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1733 AudioSystem::releaseInput(output.inputId, sessionId);
1734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 }
1736
Glenn Kasten9156ef32013-08-06 15:39:08 -07001737 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 return recordHandle;
1739}
1740
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001741
1742
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743// ----------------------------------------------------------------------------
1744
Eric Laurenta4c5a552012-03-29 10:12:40 -07001745audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1746{
Eric Laurent44622db2014-08-01 19:00:33 -07001747 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001748 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001749 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001750 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001751 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001752 }
1753 Mutex::Autolock _l(mLock);
1754 return loadHwModule_l(name);
1755}
1756
1757// loadHwModule_l() must be called with AudioFlinger::mLock held
1758audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1759{
1760 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1761 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1762 ALOGW("loadHwModule() module %s already loaded", name);
1763 return mAudioHwDevs.keyAt(i);
1764 }
1765 }
1766
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001767 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001768
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001769 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001770 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001771 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001772 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001773 }
1774
1775 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001776 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001777 mHardwareStatus = AUDIO_HW_IDLE;
1778 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001779 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001780 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001781 }
1782
John Grossmanee578c02012-07-23 17:05:46 -07001783 // Check and cache this HAL's level of support for master mute and master
1784 // volume. If this is the first HAL opened, and it supports the get
1785 // methods, use the initial values provided by the HAL as the current
1786 // master mute and volume settings.
1787
1788 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1789 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001790 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001791
1792 if (0 == mAudioHwDevs.size()) {
1793 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001794 float mv;
1795 if (OK == dev->getMasterVolume(&mv)) {
1796 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001797 }
1798
1799 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001800 bool mm;
1801 if (OK == dev->getMasterMute(&mm)) {
1802 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001803 }
1804 }
1805
Eric Laurenta4c5a552012-03-29 10:12:40 -07001806 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001807 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001808 flags = static_cast<AudioHwDevice::Flags>(flags |
1809 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1810 }
1811
1812 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001813 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001814 flags = static_cast<AudioHwDevice::Flags>(flags |
1815 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1816 }
1817
Eric Laurenta4c5a552012-03-29 10:12:40 -07001818 mHardwareStatus = AUDIO_HW_IDLE;
1819 }
1820
Glenn Kastena13cde92016-03-28 15:26:02 -07001821 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001822 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001823
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001824 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001825
1826 return handle;
1827
1828}
1829
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001830// ----------------------------------------------------------------------------
1831
Glenn Kasten3b16c762012-11-14 08:44:39 -08001832uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001833{
1834 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001835 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001836 return thread != NULL ? thread->sampleRate() : 0;
1837}
1838
Glenn Kastene33054e2012-11-14 12:54:39 -08001839size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001840{
1841 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001842 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001843 return thread != NULL ? thread->frameCountHAL() : 0;
1844}
1845
1846// ----------------------------------------------------------------------------
1847
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001848status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1849{
1850 uid_t uid = IPCThreadState::self()->getCallingUid();
1851 if (uid != AID_SYSTEM) {
1852 return PERMISSION_DENIED;
1853 }
1854 Mutex::Autolock _l(mLock);
1855 if (mIsDeviceTypeKnown) {
1856 return INVALID_OPERATION;
1857 }
1858 mIsLowRamDevice = isLowRamDevice;
1859 mIsDeviceTypeKnown = true;
1860 return NO_ERROR;
1861}
1862
Eric Laurent93c3d412014-08-01 14:48:35 -07001863audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1864{
1865 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001866
1867 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1868 if (index >= 0) {
1869 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1870 mHwAvSyncIds.valueAt(index), sessionId);
1871 return mHwAvSyncIds.valueAt(index);
1872 }
1873
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001874 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001875 if (dev == NULL) {
1876 return AUDIO_HW_SYNC_INVALID;
1877 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001878 String8 reply;
1879 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001880 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001881 param = AudioParameter(reply);
1882 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001883
1884 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001885 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001886 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1887 return AUDIO_HW_SYNC_INVALID;
1888 }
1889
1890 // allow only one session for a given HW A/V sync ID.
1891 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1892 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1893 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1894 value, mHwAvSyncIds.keyAt(i));
1895 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001896 break;
1897 }
1898 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001899
1900 mHwAvSyncIds.add(sessionId, value);
1901
1902 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1903 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1904 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001905 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001906 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001907 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001908 thread->setParameters(param.toString());
1909 break;
1910 }
1911 }
1912
1913 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1914 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001915}
1916
Eric Laurent72e3f392015-05-20 14:43:50 -07001917status_t AudioFlinger::systemReady()
1918{
1919 Mutex::Autolock _l(mLock);
1920 ALOGI("%s", __FUNCTION__);
1921 if (mSystemReady) {
1922 ALOGW("%s called twice", __FUNCTION__);
1923 return NO_ERROR;
1924 }
1925 mSystemReady = true;
1926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1927 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1928 thread->systemReady();
1929 }
1930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1931 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1932 thread->systemReady();
1933 }
1934 return NO_ERROR;
1935}
1936
Eric Laurentfa90e842014-10-17 18:12:31 -07001937// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1938void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1939{
1940 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1941 if (index >= 0) {
1942 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1943 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1944 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001945 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001946 thread->setParameters(param.toString());
1947 }
1948}
1949
1950
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001951// ----------------------------------------------------------------------------
1952
Eric Laurent83b88082014-06-20 18:31:16 -07001953
Eric Laurent6acd1d42017-01-04 14:23:29 -08001954sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001955 audio_io_handle_t *output,
1956 audio_config_t *config,
1957 audio_devices_t devices,
1958 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001959 audio_output_flags_t flags)
1960{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001961 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001962 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001963 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001964 }
1965
Eric Laurentcf2c0212014-07-25 16:20:43 -07001966 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001967 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1968 } else {
1969 // Audio Policy does not currently request a specific output handle.
1970 // If this is ever needed, see openInput_l() for example code.
1971 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1972 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001973 }
Eric Laurent83b88082014-06-20 18:31:16 -07001974
1975 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1976
Eric Laurent83b88082014-06-20 18:31:16 -07001977 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001978 // This if statement allows overriding the audio policy settings
1979 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1980 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1981 // Check only for Normal Mixing mode
1982 if (kEnableExtendedPrecision) {
1983 // Specify format (uncomment one below to choose)
1984 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1985 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1986 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1987 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001988 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001989 }
1990 if (kEnableExtendedChannels) {
1991 // Specify channel mask (uncomment one below to choose)
1992 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1993 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1994 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1995 }
Eric Laurent83b88082014-06-20 18:31:16 -07001996 }
1997
Phil Burk062e67a2015-02-11 13:40:50 -08001998 AudioStreamOut *outputStream = NULL;
1999 status_t status = outHwDev->openOutputStream(
2000 &outputStream,
2001 *output,
2002 devices,
2003 flags,
2004 config,
2005 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002006
2007 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002008
Phil Burk062e67a2015-02-11 13:40:50 -08002009 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002010 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2011 sp<MmapPlaybackThread> thread =
2012 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2013 devices, AUDIO_DEVICE_NONE, mSystemReady);
2014 mMmapThreads.add(*output, thread);
2015 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2016 *output, thread.get());
2017 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002018 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002019 sp<PlaybackThread> thread;
2020 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2021 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2022 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2023 *output, thread.get());
2024 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2025 || !isValidPcmSinkFormat(config->format)
2026 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2027 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2028 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2029 *output, thread.get());
2030 } else {
2031 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2032 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2033 *output, thread.get());
2034 }
2035 mPlaybackThreads.add(*output, thread);
2036 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002037 }
Eric Laurent83b88082014-06-20 18:31:16 -07002038 }
2039
2040 return 0;
2041}
2042
Eric Laurentcf2c0212014-07-25 16:20:43 -07002043status_t AudioFlinger::openOutput(audio_module_handle_t module,
2044 audio_io_handle_t *output,
2045 audio_config_t *config,
2046 audio_devices_t *devices,
2047 const String8& address,
2048 uint32_t *latencyMs,
2049 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002051 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2052 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002053 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002054 (devices != NULL) ? *devices : 0,
2055 config->sample_rate,
2056 config->format,
2057 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002058 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002060 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002061 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002063
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064 Mutex::Autolock _l(mLock);
2065
Eric Laurent6acd1d42017-01-04 14:23:29 -08002066 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002067 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002068 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2069 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2070 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071
Eric Laurent6acd1d42017-01-04 14:23:29 -08002072 // notify client processes of the new output creation
2073 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002074
Eric Laurent6acd1d42017-01-04 14:23:29 -08002075 // the first primary output opened designates the primary hw device
2076 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002077 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002078 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002079
Eric Laurent6acd1d42017-01-04 14:23:29 -08002080 AutoMutex lock(mHardwareLock);
2081 mHardwareStatus = AUDIO_HW_SET_MODE;
2082 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2083 mHardwareStatus = AUDIO_HW_IDLE;
2084 }
2085 } else {
2086 MmapThread *mmapThread = (MmapThread *)thread.get();
2087 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002088 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002089 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 }
2091
Eric Laurentcf2c0212014-07-25 16:20:43 -07002092 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093}
2094
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002095audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2096 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097{
2098 Mutex::Autolock _l(mLock);
2099 MixerThread *thread1 = checkMixerThread_l(output1);
2100 MixerThread *thread2 = checkMixerThread_l(output2);
2101
2102 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002103 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2104 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002105 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 }
2107
Glenn Kasteneeecb982016-02-26 10:44:04 -08002108 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002109 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 thread->addOutputTrack(thread2);
2111 mPlaybackThreads.add(id, thread);
2112 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002113 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 return id;
2115}
2116
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002117status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118{
Glenn Kastend96c5722012-04-25 13:44:49 -07002119 return closeOutput_nonvirtual(output);
2120}
2121
2122status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2123{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 // keep strong reference on the playback thread so that
2125 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002126 sp<PlaybackThread> playbackThread;
2127 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128 {
2129 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002130 playbackThread = checkPlaybackThread_l(output);
2131 if (playbackThread != NULL) {
2132 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133
Eric Laurent6acd1d42017-01-04 14:23:29 -08002134 if (playbackThread->type() == ThreadBase::MIXER) {
2135 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2136 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2137 DuplicatingThread *dupThread =
2138 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2139 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2140 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141 }
2142 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002143
2144
Eric Laurent6acd1d42017-01-04 14:23:29 -08002145 mPlaybackThreads.removeItem(output);
2146 // save all effects to the default thread
2147 if (mPlaybackThreads.size()) {
2148 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2149 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002150 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002151 Mutex::Autolock _dl(dstThread->mLock);
2152 Mutex::Autolock _sl(playbackThread->mLock);
2153 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2154 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002155 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2156 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 }
2159 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002160 } else {
2161 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2162 if (mmapThread == 0) {
2163 return BAD_VALUE;
2164 }
2165 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002166 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002168 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2169 ioDesc->mIoHandle = output;
2170 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002172 // The thread entity (active unit of execution) is no longer running here,
2173 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174
Eric Laurent6acd1d42017-01-04 14:23:29 -08002175 if (playbackThread != 0) {
2176 playbackThread->exit();
2177 if (!playbackThread->isDuplicating()) {
2178 closeOutputFinish(playbackThread);
2179 }
2180 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002181 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002182 mmapThread->exit();
2183 AudioStreamOut *out = mmapThread->clearOutput();
2184 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2185 // from now on thread->mOutput is NULL
2186 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 }
2188 return NO_ERROR;
2189}
2190
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002191void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002192{
2193 AudioStreamOut *out = thread->clearOutput();
2194 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2195 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002196 delete out;
2197}
2198
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002199void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002200{
2201 mPlaybackThreads.removeItem(thread->mId);
2202 thread->exit();
2203 closeOutputFinish(thread);
2204}
2205
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002206status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207{
2208 Mutex::Autolock _l(mLock);
2209 PlaybackThread *thread = checkPlaybackThread_l(output);
2210
2211 if (thread == NULL) {
2212 return BAD_VALUE;
2213 }
2214
Steve Block3856b092011-10-20 11:56:00 +01002215 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002216 thread->suspend();
2217
2218 return NO_ERROR;
2219}
2220
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002221status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222{
2223 Mutex::Autolock _l(mLock);
2224 PlaybackThread *thread = checkPlaybackThread_l(output);
2225
2226 if (thread == NULL) {
2227 return BAD_VALUE;
2228 }
2229
Steve Block3856b092011-10-20 11:56:00 +01002230 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231
2232 thread->restore();
2233
2234 return NO_ERROR;
2235}
2236
Eric Laurentcf2c0212014-07-25 16:20:43 -07002237status_t AudioFlinger::openInput(audio_module_handle_t module,
2238 audio_io_handle_t *input,
2239 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002240 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002241 const String8& address,
2242 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002243 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244{
Eric Laurent83b88082014-06-20 18:31:16 -07002245 Mutex::Autolock _l(mLock);
2246
Glenn Kastene7d66712015-03-05 13:46:52 -08002247 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002248 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002249 }
2250
Eric Laurent6acd1d42017-01-04 14:23:29 -08002251 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002252
2253 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002254 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002255 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002256 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002258 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002259}
Dima Zavin799a70e2011-04-18 16:57:27 -07002260
Eric Laurent6acd1d42017-01-04 14:23:29 -08002261sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002262 audio_io_handle_t *input,
2263 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002264 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002265 const String8& address,
2266 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002267 audio_input_flags_t flags)
2268{
Glenn Kastene7d66712015-03-05 13:46:52 -08002269 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002270 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002271 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002272 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002273 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002274
Glenn Kasteneeecb982016-02-26 10:44:04 -08002275 // Audio Policy can request a specific handle for hardware hotword.
2276 // The goal here is not to re-open an already opened input.
2277 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002278 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002279 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2280 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2281 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2282 return 0;
2283 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2284 // This should not happen in a transient state with current design.
2285 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2286 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002287 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002288
Eric Laurentcf2c0212014-07-25 16:20:43 -07002289 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002290 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002291 sp<StreamInHalInterface> inStream;
2292 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002293 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002294 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2295 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002296 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002297 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002298 halconfig.sample_rate,
2299 halconfig.format,
2300 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002301 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002302 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002304 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002305 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002306 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002307 audio_is_linear_pcm(config->format) &&
2308 audio_is_linear_pcm(halconfig.format) &&
2309 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002310 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2311 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002312 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002313 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002314 inStream.clear();
2315 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002316 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002317 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 }
2319
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002320 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002321 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002322 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2323 sp<MmapCaptureThread> thread =
2324 new MmapCaptureThread(this, *input,
2325 inHwDev, inputStream,
2326 primaryOutputDevice_l(), devices, mSystemReady);
2327 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002328 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2329 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002330 return thread;
2331 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002332#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002333 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2334 // or (re-)create if current Pipe is idle and does not match the new format
2335 sp<NBAIO_Sink> teeSink;
2336 enum {
2337 TEE_SINK_NO, // don't copy input
2338 TEE_SINK_NEW, // copy input using a new pipe
2339 TEE_SINK_OLD, // copy input using an existing pipe
2340 } kind;
2341 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2342 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2343 if (!mTeeSinkInputEnabled) {
2344 kind = TEE_SINK_NO;
2345 } else if (!Format_isValid(format)) {
2346 kind = TEE_SINK_NO;
2347 } else if (mRecordTeeSink == 0) {
2348 kind = TEE_SINK_NEW;
2349 } else if (mRecordTeeSink->getStrongCount() != 1) {
2350 kind = TEE_SINK_NO;
2351 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2352 kind = TEE_SINK_OLD;
2353 } else {
2354 kind = TEE_SINK_NEW;
2355 }
2356 switch (kind) {
2357 case TEE_SINK_NEW: {
2358 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2359 size_t numCounterOffers = 0;
2360 const NBAIO_Format offers[1] = {format};
2361 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2362 ALOG_ASSERT(index == 0);
2363 PipeReader *pipeReader = new PipeReader(*pipe);
2364 numCounterOffers = 0;
2365 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2366 ALOG_ASSERT(index == 0);
2367 mRecordTeeSink = pipe;
2368 mRecordTeeSource = pipeReader;
2369 teeSink = pipe;
2370 }
2371 break;
2372 case TEE_SINK_OLD:
2373 teeSink = mRecordTeeSink;
2374 break;
2375 case TEE_SINK_NO:
2376 default:
2377 break;
2378 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002379#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002380
2381 // Start record thread
2382 // RecordThread requires both input and output device indication to forward to audio
2383 // pre processing modules
2384 sp<RecordThread> thread = new RecordThread(this,
2385 inputStream,
2386 *input,
2387 primaryOutputDevice_l(),
2388 devices,
2389 mSystemReady
2390#ifdef TEE_SINK
2391 , teeSink
2392#endif
2393 );
2394 mRecordThreads.add(*input, thread);
2395 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2396 return thread;
2397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 }
2399
Eric Laurentcf2c0212014-07-25 16:20:43 -07002400 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 return 0;
2402}
2403
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002404status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405{
Glenn Kastend96c5722012-04-25 13:44:49 -07002406 return closeInput_nonvirtual(input);
2407}
2408
2409status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2410{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411 // keep strong reference on the record thread so that
2412 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002413 sp<RecordThread> recordThread;
2414 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 {
2416 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002417 recordThread = checkRecordThread_l(input);
2418 if (recordThread != 0) {
2419 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420
Eric Laurent6acd1d42017-01-04 14:23:29 -08002421 // If we still have effect chains, it means that a client still holds a handle
2422 // on at least one effect. We must either move the chain to an existing thread with the
2423 // same session ID or put it aside in case a new record thread is opened for a
2424 // new capture on the same session
2425 sp<EffectChain> chain;
2426 {
2427 Mutex::Autolock _sl(recordThread->mLock);
2428 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2429 // Note: maximum one chain per record thread
2430 if (effectChains.size() != 0) {
2431 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002432 }
2433 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002434 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002435 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002436 // This should only happen in case of overlap between one thread tear down and the
2437 // creation of its replacement
2438 size_t i;
2439 for (i = 0; i < mRecordThreads.size(); i++) {
2440 sp<RecordThread> t = mRecordThreads.valueAt(i);
2441 if (t == recordThread) {
2442 continue;
2443 }
2444 if (t->hasAudioSession(chain->sessionId()) != 0) {
2445 Mutex::Autolock _l(t->mLock);
2446 ALOGV("closeInput() found thread %d for effect session %d",
2447 t->id(), chain->sessionId());
2448 t->addEffectChain_l(chain);
2449 break;
2450 }
2451 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002452 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002453 if (i == mRecordThreads.size()) {
2454 putOrphanEffectChain_l(chain);
2455 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002456 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002457 mRecordThreads.removeItem(input);
2458 } else {
2459 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2460 if (mmapThread == 0) {
2461 return BAD_VALUE;
2462 }
2463 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002464 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002465 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2466 ioDesc->mIoHandle = input;
2467 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 }
Eric Laurent83b88082014-06-20 18:31:16 -07002469 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2470 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002471 if (recordThread != 0) {
2472 closeInputFinish(recordThread);
2473 } else if (mmapThread != 0) {
2474 mmapThread->exit();
2475 AudioStreamIn *in = mmapThread->clearInput();
2476 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2477 // from now on thread->mInput is NULL
2478 delete in;
2479 }
Eric Laurent83b88082014-06-20 18:31:16 -07002480 return NO_ERROR;
2481}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002483void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002484{
2485 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002486 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002487 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002488 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002489 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002490}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002492void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002493{
2494 mRecordThreads.removeItem(thread->mId);
2495 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496}
2497
Glenn Kastend2304db2014-02-03 07:40:31 -08002498status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499{
2500 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002501 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502
2503 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2504 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002505 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002506 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002507 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2508 mMmapThreads[i]->invalidateTracks(stream);
2509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 return NO_ERROR;
2511}
2512
2513
Glenn Kasteneeecb982016-02-26 10:44:04 -08002514audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515{
Glenn Kasten9d003132016-04-06 14:38:09 -07002516 // This is a binder API, so a malicious client could pass in a bad parameter.
2517 // Check for that before calling the internal API nextUniqueId().
2518 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2519 ALOGE("newAudioUniqueId invalid use %d", use);
2520 return AUDIO_UNIQUE_ID_ALLOCATE;
2521 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002522 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523}
2524
Glenn Kastend848eb42016-03-08 13:42:11 -08002525void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002526{
2527 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002528 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002529 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2530 if (pid != -1 && (caller == getpid_cached)) {
2531 caller = pid;
2532 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002533
Eric Laurent021cf962014-05-13 10:18:14 -07002534 {
2535 Mutex::Autolock _cl(mClientLock);
2536 // Ignore requests received from processes not known as notification client. The request
2537 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2538 // called from a different pid leaving a stale session reference. Also we don't know how
2539 // to clear this reference if the client process dies.
2540 if (mNotificationClients.indexOfKey(caller) < 0) {
2541 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2542 return;
2543 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002544 }
2545
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002546 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002547 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002548 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002549 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2550 ref->mCnt++;
2551 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002552 return;
2553 }
2554 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002555 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2556 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002557}
2558
Glenn Kastend848eb42016-03-08 13:42:11 -08002559void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002560{
2561 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002562 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002563 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2564 if (pid != -1 && (caller == getpid_cached)) {
2565 caller = pid;
2566 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002567 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002568 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002569 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002570 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2571 ref->mCnt--;
2572 ALOGV(" decremented refcount to %d", ref->mCnt);
2573 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002574 mAudioSessionRefs.removeAt(i);
2575 delete ref;
2576 purgeStaleEffects_l();
2577 }
2578 return;
2579 }
2580 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002581 // If the caller is mediaserver it is likely that the session being released was acquired
2582 // on behalf of a process not in notification clients and we ignore the warning.
2583 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002584}
2585
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002586bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2587{
2588 size_t num = mAudioSessionRefs.size();
2589 for (size_t i = 0; i < num; i++) {
2590 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2591 if (ref->mSessionid == audioSession) {
2592 return true;
2593 }
2594 }
2595 return false;
2596}
2597
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002598void AudioFlinger::purgeStaleEffects_l() {
2599
Steve Block3856b092011-10-20 11:56:00 +01002600 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002601
2602 Vector< sp<EffectChain> > chains;
2603
2604 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2605 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002606 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002607 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2608 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002609 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2610 chains.push(ec);
2611 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002612 }
2613 }
2614 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2615 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002616 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002617 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2618 sp<EffectChain> ec = t->mEffectChains[j];
2619 chains.push(ec);
2620 }
2621 }
2622
2623 for (size_t i = 0; i < chains.size(); i++) {
2624 sp<EffectChain> ec = chains[i];
2625 int sessionid = ec->sessionId();
2626 sp<ThreadBase> t = ec->mThread.promote();
2627 if (t == 0) {
2628 continue;
2629 }
2630 size_t numsessionrefs = mAudioSessionRefs.size();
2631 bool found = false;
2632 for (size_t k = 0; k < numsessionrefs; k++) {
2633 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002634 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002635 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002636 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002637 found = true;
2638 break;
2639 }
2640 }
2641 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002642 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002643 // remove all effects from the chain
2644 while (ec->mEffects.size()) {
2645 sp<EffectModule> effect = ec->mEffects[0];
2646 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002647 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002648 if (effect->purgeHandles()) {
2649 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002650 }
2651 AudioSystem::unregisterEffect(effect->id());
2652 }
2653 }
2654 }
2655 return;
2656}
2657
Glenn Kasteneeecb982016-02-26 10:44:04 -08002658// checkThread_l() must be called with AudioFlinger::mLock held
2659AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2660{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002661 ThreadBase *thread = checkMmapThread_l(ioHandle);
2662 if (thread == 0) {
2663 switch (audio_unique_id_get_use(ioHandle)) {
2664 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2665 thread = checkPlaybackThread_l(ioHandle);
2666 break;
2667 case AUDIO_UNIQUE_ID_USE_INPUT:
2668 thread = checkRecordThread_l(ioHandle);
2669 break;
2670 default:
2671 break;
2672 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002673 }
2674 return thread;
2675}
2676
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002678AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679{
Glenn Kastena1117922012-01-26 10:53:32 -08002680 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681}
2682
2683// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002684AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685{
2686 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002687 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688}
2689
2690// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002691AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692{
Glenn Kastena1117922012-01-26 10:53:32 -08002693 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002694}
2695
Eric Laurent6acd1d42017-01-04 14:23:29 -08002696// checkMmapThread_l() must be called with AudioFlinger::mLock held
2697AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2698{
2699 return mMmapThreads.valueFor(io).get();
2700}
2701
2702
2703// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2704AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2705{
Eric Laurent7459b902017-04-19 18:10:41 -07002706 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002707 if (volumeInterface == nullptr) {
2708 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2709 if (mmapThread != nullptr) {
2710 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002711 MmapPlaybackThread *mmapPlaybackThread =
2712 static_cast<MmapPlaybackThread *>(mmapThread);
2713 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002714 }
2715 }
2716 }
2717 return volumeInterface;
2718}
2719
2720Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2721{
2722 Vector <VolumeInterface *> volumeInterfaces;
2723 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002724 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002725 }
2726 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2727 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002728 MmapPlaybackThread *mmapPlaybackThread =
2729 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2730 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002731 }
2732 }
2733 return volumeInterfaces;
2734}
2735
Glenn Kasteneeecb982016-02-26 10:44:04 -08002736audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737{
Glenn Kasten9d003132016-04-06 14:38:09 -07002738 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002739 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002740 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2741 for (int retry = 0; retry < maxRetries; retry++) {
2742 // The cast allows wraparound from max positive to min negative instead of abort
2743 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2744 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2745 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2746 // allow wrap by skipping 0 and -1 for session ids
2747 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2748 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2749 return (audio_unique_id_t) (base | use);
2750 }
2751 }
2752 // We have no way of recovering from wraparound
2753 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2754 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755}
2756
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002757AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002758{
2759 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2760 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002761 if(thread->isDuplicating()) {
2762 continue;
2763 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002764 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002765 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002766 return thread;
2767 }
2768 }
2769 return NULL;
2770}
2771
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002772audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002773{
2774 PlaybackThread *thread = primaryPlaybackThread_l();
2775
2776 if (thread == NULL) {
2777 return 0;
2778 }
2779
Eric Laurentf1c04f92012-08-28 14:26:53 -07002780 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002781}
2782
Glenn Kastena7335632016-06-09 17:09:53 -07002783AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2784{
2785 size_t minFrameCount = 0;
2786 PlaybackThread *minThread = NULL;
2787 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2788 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2789 if (!thread->isDuplicating()) {
2790 size_t frameCount = thread->frameCountHAL();
2791 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2792 (frameCount == minFrameCount && thread->hasFastMixer() &&
2793 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2794 minFrameCount = frameCount;
2795 minThread = thread;
2796 }
2797 }
2798 }
2799 return minThread;
2800}
2801
Eric Laurenta011e352012-03-29 15:51:43 -07002802sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002803 audio_session_t triggerSession,
2804 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002805 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002806 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002807{
2808 Mutex::Autolock _l(mLock);
2809
2810 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2811 status_t playStatus = NAME_NOT_FOUND;
2812 status_t recStatus = NAME_NOT_FOUND;
2813 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2814 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2815 if (playStatus == NO_ERROR) {
2816 return event;
2817 }
2818 }
2819 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2820 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2821 if (recStatus == NO_ERROR) {
2822 return event;
2823 }
2824 }
2825 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2826 mPendingSyncEvents.add(event);
2827 } else {
2828 ALOGV("createSyncEvent() invalid event %d", event->type());
2829 event.clear();
2830 }
2831 return event;
2832}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002833
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834// ----------------------------------------------------------------------------
2835// Effect management
2836// ----------------------------------------------------------------------------
2837
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002838sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2839 return mEffectsFactoryHal;
2840}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841
Glenn Kastenf587ba52012-01-26 16:25:10 -08002842status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843{
2844 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002845 if (mEffectsFactoryHal.get()) {
2846 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2847 } else {
2848 return -ENODEV;
2849 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850}
2851
Glenn Kastenf587ba52012-01-26 16:25:10 -08002852status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853{
2854 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002855 if (mEffectsFactoryHal.get()) {
2856 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2857 } else {
2858 return -ENODEV;
2859 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860}
2861
Glenn Kasten5e92a782012-01-30 07:40:52 -08002862status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002863 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864{
2865 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002866 if (mEffectsFactoryHal.get()) {
2867 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2868 } else {
2869 return -ENODEV;
2870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871}
2872
2873
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002874sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 effect_descriptor_t *pDesc,
2876 const sp<IEffectClient>& effectClient,
2877 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002878 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002879 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002880 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002881 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002882 status_t *status,
2883 int *id,
2884 int *enabled)
2885{
2886 status_t lStatus = NO_ERROR;
2887 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889
Eric Laurentb6436272016-12-07 19:24:50 -08002890 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2891 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2892 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2893 ALOGW_IF(pid != -1 && pid != callingPid,
2894 "%s uid %d pid %d tried to pass itself off as pid %d",
2895 __func__, callingUid, callingPid, pid);
2896 pid = callingPid;
2897 }
2898
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002899 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2900 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901
2902 if (pDesc == NULL) {
2903 lStatus = BAD_VALUE;
2904 goto Exit;
2905 }
2906
Eric Laurent84e9a102010-09-23 16:10:16 -07002907 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002908 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002909 lStatus = PERMISSION_DENIED;
2910 goto Exit;
2911 }
2912
Dima Zavinfce7a472011-04-19 22:30:36 -07002913 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002914 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002915 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002916 lStatus = PERMISSION_DENIED;
2917 goto Exit;
2918 }
2919
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002920 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002921 lStatus = NO_INIT;
2922 goto Exit;
2923 }
2924
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002926 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002928 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002930 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 goto Exit;
2932 }
2933 } else {
2934 // if uuid is not specified, look for an available implementation
2935 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002936 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002937 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938 lStatus = BAD_VALUE;
2939 goto Exit;
2940 }
2941 uint32_t numEffects = 0;
2942 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002943 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 bool found = false;
2945
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002946 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002948 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 goto Exit;
2950 }
2951 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002952 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002954 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955 continue;
2956 }
2957 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2958 // If matching type found save effect descriptor. If the session is
2959 // 0 and the effect is not auxiliary, continue enumeration in case
2960 // an auxiliary version of this effect type is available
2961 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002962 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002963 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2965 break;
2966 }
2967 }
2968 }
2969 if (!found) {
2970 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002971 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 goto Exit;
2973 }
2974 // For same effect type, chose auxiliary version over insert version if
2975 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002976 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002978 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 }
2980 }
2981
2982 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002983 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2985 lStatus = INVALID_OPERATION;
2986 goto Exit;
2987 }
2988
Eric Laurent59255e42011-07-27 19:49:51 -07002989 // check recording permission for visualizer
2990 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002991 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002992 lStatus = PERMISSION_DENIED;
2993 goto Exit;
2994 }
2995
Mathias Agopian65ab4712010-07-14 17:59:35 -07002996 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002997 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002998 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002999 // if the output returned by getOutputForEffect() is removed before we lock the
3000 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3001 // and we will exit safely
3002 io = AudioSystem::getOutputForEffect(&desc);
3003 ALOGV("createEffect got output %d", io);
3004 }
3005
3006 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007
3008 // If output is not specified try to find a matching audio session ID in one of the
3009 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003010 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3011 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003012 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003013 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003014 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3015 // output must be specified by AudioPolicyManager when using session
3016 // AUDIO_SESSION_OUTPUT_STAGE
3017 lStatus = BAD_VALUE;
3018 goto Exit;
3019 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003020 // look for the thread where the specified audio session is present
3021 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3022 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3023 io = mPlaybackThreads.keyAt(i);
3024 break;
3025 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003027 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003028 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3029 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3030 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003031 break;
3032 }
3033 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003034 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003035 if (io == AUDIO_IO_HANDLE_NONE) {
3036 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3037 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3038 io = mMmapThreads.keyAt(i);
3039 break;
3040 }
3041 }
3042 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003043 // If no output thread contains the requested session ID, default to
3044 // first output. The effect chain will be moved to the correct output
3045 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003046 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003047 io = mPlaybackThreads.keyAt(0);
3048 }
Steve Block3856b092011-10-20 11:56:00 +01003049 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003050 }
3051 ThreadBase *thread = checkRecordThread_l(io);
3052 if (thread == NULL) {
3053 thread = checkPlaybackThread_l(io);
3054 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003055 thread = checkMmapThread_l(io);
3056 if (thread == NULL) {
3057 ALOGE("createEffect() unknown output thread");
3058 lStatus = BAD_VALUE;
3059 goto Exit;
3060 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003061 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003062 } else {
3063 // Check if one effect chain was awaiting for an effect to be created on this
3064 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003065 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003066 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003067 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003068 thread->addEffectChain_l(chain);
3069 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003071
Eric Laurent021cf962014-05-13 10:18:14 -07003072 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003074 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003075 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003076 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003077 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 if (handle != 0 && id != NULL) {
3079 *id = handle->id();
3080 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003081 if (handle == 0) {
3082 // remove local strong reference to Client with mClientLock held
3083 Mutex::Autolock _cl(mClientLock);
3084 client.clear();
3085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 }
3087
3088Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003089 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 return handle;
3091}
3092
Glenn Kastend848eb42016-03-08 13:42:11 -08003093status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003094 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003095{
Steve Block3856b092011-10-20 11:56:00 +01003096 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003097 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003098 Mutex::Autolock _l(mLock);
3099 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003100 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003101 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 }
Eric Laurentde070132010-07-13 04:45:46 -07003103 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3104 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003105 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003106 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 }
Eric Laurentde070132010-07-13 04:45:46 -07003108 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3109 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003110 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003111 return BAD_VALUE;
3112 }
3113
3114 Mutex::Autolock _dl(dstThread->mLock);
3115 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003116 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117}
3118
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003119// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003120status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003121 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003122 AudioFlinger::PlaybackThread *dstThread,
3123 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003124{
Steve Block3856b092011-10-20 11:56:00 +01003125 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003126 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003127
Eric Laurent59255e42011-07-27 19:49:51 -07003128 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003129 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003130 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003131 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003132 return INVALID_OPERATION;
3133 }
3134
Eric Laurent4c415062016-06-17 16:14:16 -07003135 // Check whether the destination thread and all effects in the chain are compatible
3136 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003137 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003138 " destination thread %p is not compatible with effects in the chain",
3139 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003140 return INVALID_OPERATION;
3141 }
3142
Eric Laurent39e94f82010-07-28 01:32:47 -07003143 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003144 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003145 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003146 // removed.
3147 srcThread->removeEffectChain_l(chain);
3148
3149 // transfer all effects one by one so that new effect chain is created on new thread with
3150 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003151 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003152 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003153 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003154 Vector< sp<EffectModule> > removed;
3155 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003156 while (effect != 0) {
3157 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003158 removed.add(effect);
3159 status = dstThread->addEffect_l(effect);
3160 if (status != NO_ERROR) {
3161 break;
3162 }
Eric Laurentec35a142011-10-05 17:42:25 -07003163 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3164 if (effect->state() == EffectModule::ACTIVE ||
3165 effect->state() == EffectModule::STOPPING) {
3166 effect->start();
3167 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003168 // if the move request is not received from audio policy manager, the effect must be
3169 // re-registered with the new strategy and output
3170 if (dstChain == 0) {
3171 dstChain = effect->chain().promote();
3172 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003173 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003174 status = NO_INIT;
3175 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003176 }
3177 strategy = dstChain->strategy();
3178 }
3179 if (reRegister) {
3180 AudioSystem::unregisterEffect(effect->id());
3181 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003182 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003183 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003184 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003185 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003186 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003187 }
Eric Laurentde070132010-07-13 04:45:46 -07003188 effect = chain->getEffectFromId_l(0);
3189 }
3190
Eric Laurent5baf2af2013-09-12 17:37:00 -07003191 if (status != NO_ERROR) {
3192 for (size_t i = 0; i < removed.size(); i++) {
3193 srcThread->addEffect_l(removed[i]);
3194 if (dstChain != 0 && reRegister) {
3195 AudioSystem::unregisterEffect(removed[i]->id());
3196 AudioSystem::registerEffect(&removed[i]->desc(),
3197 srcThread->id(),
3198 strategy,
3199 sessionId,
3200 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003201 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003202 }
3203 }
3204 }
3205
3206 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207}
3208
Eric Laurent5baf2af2013-09-12 17:37:00 -07003209bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003210{
3211 if (mGlobalEffectEnableTime != 0 &&
3212 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3213 return true;
3214 }
3215
3216 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3217 sp<EffectChain> ec =
3218 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003219 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003220 return true;
3221 }
3222 }
3223 return false;
3224}
3225
Eric Laurent5baf2af2013-09-12 17:37:00 -07003226void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003227{
3228 Mutex::Autolock _l(mLock);
3229
3230 mGlobalEffectEnableTime = systemTime();
3231
3232 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3233 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3234 if (t->mType == ThreadBase::OFFLOAD) {
3235 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3236 }
3237 }
3238
3239}
3240
Eric Laurentaaa44472014-09-12 17:41:50 -07003241status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3242{
Eric Laurentd8365c52017-07-16 15:27:05 -07003243 // clear possible suspended state before parking the chain so that it starts in default state
3244 // when attached to a new record thread
3245 chain->setEffectSuspended_l(FX_IID_AEC, false);
3246 chain->setEffectSuspended_l(FX_IID_NS, false);
3247
Glenn Kastend848eb42016-03-08 13:42:11 -08003248 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003249 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003250 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003251 if (index >= 0) {
3252 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3253 return ALREADY_EXISTS;
3254 }
3255 mOrphanEffectChains.add(session, chain);
3256 return NO_ERROR;
3257}
3258
3259sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3260{
3261 sp<EffectChain> chain;
3262 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003263 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003264 if (index >= 0) {
3265 chain = mOrphanEffectChains.valueAt(index);
3266 mOrphanEffectChains.removeItemsAt(index);
3267 }
3268 return chain;
3269}
3270
3271bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3272{
3273 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003274 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003275 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003276 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003277 if (index >= 0) {
3278 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003279 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003280 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003281 mOrphanEffectChains.removeItemsAt(index);
3282 }
3283 return true;
3284 }
3285 return false;
3286}
3287
3288
Glenn Kastenda6ef132013-01-10 12:31:01 -08003289struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003290#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3291 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003292};
3293
3294int comparEntry(const void *p1, const void *p2)
3295{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003296 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003297}
3298
Glenn Kasten46909e72013-02-26 09:20:22 -08003299#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003300void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301{
Eric Laurent81784c32012-11-19 14:55:58 -08003302 NBAIO_Source *teeSource = source.get();
3303 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003304 // .wav rotation
3305 // There is a benign race condition if 2 threads call this simultaneously.
3306 // They would both traverse the directory, but the result would simply be
3307 // failures at unlink() which are ignored. It's also unlikely since
3308 // normally dumpsys is only done by bugreport or from the command line.
3309 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003310 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003311 size_t teePathLen = strlen(teePath);
3312 DIR *dir = opendir(teePath);
3313 teePath[teePathLen++] = '/';
3314 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003315#define TEE_MAX_SORT 20 // number of entries to sort
3316#define TEE_MAX_KEEP 10 // number of entries to keep
3317 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003318 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003319 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003320 struct dirent de;
3321 struct dirent *result = NULL;
3322 int rc = readdir_r(dir, &de, &result);
3323 if (rc != 0) {
3324 ALOGW("readdir_r failed %d", rc);
3325 break;
3326 }
3327 if (result == NULL) {
3328 break;
3329 }
3330 if (result != &de) {
3331 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3332 break;
3333 }
3334 // ignore non .wav file entries
3335 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003336 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003337 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3338 continue;
3339 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003340 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003341 }
3342 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003343 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003344 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003345 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3346 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003347 (void) unlink(teePath);
3348 }
3349 }
3350 } else {
3351 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003352 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003353 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003354 }
3355 }
Eric Laurent81784c32012-11-19 14:55:58 -08003356 char teeTime[16];
3357 struct timeval tv;
3358 gettimeofday(&tv, NULL);
3359 struct tm tm;
3360 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003361 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003362 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3363 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003364 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3365 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003366 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003367 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003368 char wavHeader[44];
3369 memcpy(wavHeader,
3370 "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",
3371 sizeof(wavHeader));
3372 NBAIO_Format format = teeSource->format();
3373 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003374 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003375 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003376 wavHeader[22] = channelCount; // number of channels
3377 wavHeader[24] = sampleRate; // sample rate
3378 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003379 wavHeader[32] = frameSize; // block alignment
3380 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003381 write(teeFd, wavHeader, sizeof(wavHeader));
3382 size_t total = 0;
3383 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003384#define TEE_SINK_READ 1024 // frames per I/O operation
3385 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003386 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003387 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003388 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003389 bool wasFirstRead = firstRead;
3390 firstRead = false;
3391 if (actual <= 0) {
3392 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3393 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003394 }
Eric Laurent81784c32012-11-19 14:55:58 -08003395 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003396 }
Eric Laurent81784c32012-11-19 14:55:58 -08003397 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003398 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003399 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003400 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003401 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003402 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003403 uint32_t temp = 44 + total * frameSize - 8;
3404 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003405 write(teeFd, &temp, sizeof(temp));
3406 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003407 temp = total * frameSize;
3408 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003409 write(teeFd, &temp, sizeof(temp));
3410 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003411 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003412 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003413 }
Eric Laurent59255e42011-07-27 19:49:51 -07003414 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003415 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003416 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003417 }
Eric Laurent59255e42011-07-27 19:49:51 -07003418 }
3419 }
3420}
Glenn Kasten46909e72013-02-26 09:20:22 -08003421#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003422
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423// ----------------------------------------------------------------------------
3424
3425status_t AudioFlinger::onTransact(
3426 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3427{
3428 return BnAudioFlinger::onTransact(code, data, reply, flags);
3429}
3430
Glenn Kasten63238ef2015-03-02 15:50:29 -08003431} // namespace android