blob: 9fef60fec3d15db08f423336fcba6beab4b6e5c7 [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,
265 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700266 sp<MmapStreamInterface>& interface,
267 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800268{
269 sp<AudioFlinger> af;
270 {
271 Mutex::Autolock _l(gLock);
272 af = gAudioFlinger.promote();
273 }
274 status_t ret = NO_INIT;
275 if (af != 0) {
276 ret = af->openMmapStream(
Eric Laurentcb4dae22017-07-01 19:39:32 -0700277 direction, attr, config, client, deviceId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800278 }
279 return ret;
280}
281
Eric Laurent6acd1d42017-01-04 14:23:29 -0800282status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
283 const audio_attributes_t *attr,
284 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700285 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800286 audio_port_handle_t *deviceId,
287 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700288 sp<MmapStreamInterface>& interface,
289 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800290{
291 status_t ret = initCheck();
292 if (ret != NO_ERROR) {
293 return ret;
294 }
295
Eric Laurent6acd1d42017-01-04 14:23:29 -0800296 audio_session_t sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
297 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700298 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800299 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
300 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
301 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
302 fullConfig.sample_rate = config->sample_rate;
303 fullConfig.channel_mask = config->channel_mask;
304 fullConfig.format = config->format;
305 ret = AudioSystem::getOutputForAttr(attr, &io,
306 sessionId,
307 &streamType, client.clientUid,
308 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800309 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
310 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700311 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800312 } else {
313 ret = AudioSystem::getInputForAttr(attr, &io,
314 sessionId,
315 client.clientPid,
316 client.clientUid,
317 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700318 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800319 }
320 if (ret != NO_ERROR) {
321 return ret;
322 }
323
324 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
325 // audio policy manager and we can retrieve it
326 sp<MmapThread> thread = mMmapThreads.valueFor(io);
327 if (thread != 0) {
328 interface = new MmapThreadHandle(thread);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -0700329 thread->configure(attr, streamType, sessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700330 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800331 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700332 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
333 AudioSystem::releaseOutput(io, streamType, sessionId);
334 } else {
335 AudioSystem::releaseInput(io, sessionId);
336 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800337 ret = NO_INIT;
338 }
339
340 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
341
Eric Laurentfc235202016-12-20 18:48:17 -0800342 return ret;
343}
344
Eric Laurenta4c5a552012-03-29 10:12:40 -0700345static const char * const audio_interfaces[] = {
346 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
347 AUDIO_HARDWARE_MODULE_ID_A2DP,
348 AUDIO_HARDWARE_MODULE_ID_USB,
349};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700350
Phil Burk062e67a2015-02-11 13:40:50 -0800351AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700352 audio_module_handle_t module,
353 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700354{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355 // if module is 0, the request comes from an old policy manager and we should load
356 // well known modules
357 if (module == 0) {
358 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700359 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700360 loadHwModule_l(audio_interfaces[i]);
361 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700362 // then try to find a module supporting the requested device.
363 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
364 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700365 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
366 uint32_t supportedDevices;
367 if (dev->getSupportedDevices(&supportedDevices) == OK &&
368 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700369 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700370 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700371 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700372 } else {
373 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700374 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
375 if (audioHwDevice != NULL) {
376 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700377 }
378 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700379
Dima Zavin799a70e2011-04-18 16:57:27 -0700380 return NULL;
381}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382
Glenn Kasten0f11b512014-01-31 16:18:54 -0800383void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384{
385 const size_t SIZE = 256;
386 char buffer[SIZE];
387 String8 result;
388
389 result.append("Clients:\n");
390 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800391 sp<Client> client = mClients.valueAt(i).promote();
392 if (client != 0) {
393 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
394 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395 }
396 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700397
Eric Laurentd1b28d42013-09-18 18:47:13 -0700398 result.append("Notification Clients:\n");
399 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
400 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
401 result.append(buffer);
402 }
403
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700404 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800405 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700406 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
407 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800408 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700409 result.append(buffer);
410 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412}
413
414
Glenn Kasten0f11b512014-01-31 16:18:54 -0800415void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416{
417 const size_t SIZE = 256;
418 char buffer[SIZE];
419 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800420 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421
John Grossman4ff14ba2012-02-08 16:37:41 -0800422 snprintf(buffer, SIZE, "Hardware status: %d\n"
423 "Standby Time mSec: %u\n",
424 hardwareStatus,
425 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 result.append(buffer);
427 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428}
429
Glenn Kasten0f11b512014-01-31 16:18:54 -0800430void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431{
432 const size_t SIZE = 256;
433 char buffer[SIZE];
434 String8 result;
435 snprintf(buffer, SIZE, "Permission Denial: "
436 "can't dump AudioFlinger from pid=%d, uid=%d\n",
437 IPCThreadState::self()->getCallingPid(),
438 IPCThreadState::self()->getCallingUid());
439 result.append(buffer);
440 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441}
442
Eric Laurent81784c32012-11-19 14:55:58 -0800443bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444{
445 bool locked = false;
446 for (int i = 0; i < kDumpLockRetries; ++i) {
447 if (mutex.tryLock() == NO_ERROR) {
448 locked = true;
449 break;
450 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800451 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 }
453 return locked;
454}
455
456status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
457{
Glenn Kasten44deb052012-02-05 18:09:08 -0800458 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459 dumpPermissionDenial(fd, args);
460 } else {
461 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800462 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 if (!hardwareLocked) {
464 String8 result(kHardwareLockedString);
465 write(fd, result.string(), result.size());
466 } else {
467 mHardwareLock.unlock();
468 }
469
Eric Laurent81784c32012-11-19 14:55:58 -0800470 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471
472 // failed to lock - AudioFlinger is probably deadlocked
473 if (!locked) {
474 String8 result(kDeadlockedString);
475 write(fd, result.string(), result.size());
476 }
477
Eric Laurent021cf962014-05-13 10:18:14 -0700478 bool clientLocked = dumpTryLock(mClientLock);
479 if (!clientLocked) {
480 String8 result(kClientLockedString);
481 write(fd, result.string(), result.size());
482 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700483
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700484 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700485 mEffectsFactoryHal->dumpEffects(fd);
486 } else {
487 String8 result(kNoEffectsFactory);
488 write(fd, result.string(), result.size());
489 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700490
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700492 if (clientLocked) {
493 mClientLock.unlock();
494 }
495
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 dumpInternals(fd, args);
497
498 // dump playback threads
499 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
500 mPlaybackThreads.valueAt(i)->dump(fd, args);
501 }
502
503 // dump record threads
504 for (size_t i = 0; i < mRecordThreads.size(); i++) {
505 mRecordThreads.valueAt(i)->dump(fd, args);
506 }
507
Eric Laurent6acd1d42017-01-04 14:23:29 -0800508 // dump mmap threads
509 for (size_t i = 0; i < mMmapThreads.size(); i++) {
510 mMmapThreads.valueAt(i)->dump(fd, args);
511 }
512
Eric Laurentaaa44472014-09-12 17:41:50 -0700513 // dump orphan effect chains
514 if (mOrphanEffectChains.size() != 0) {
515 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
516 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
517 mOrphanEffectChains.valueAt(i)->dump(fd, args);
518 }
519 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700520 // dump all hardware devs
521 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700522 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
523 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700525
Glenn Kasten46909e72013-02-26 09:20:22 -0800526#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700527 // dump the serially shared record tee sink
528 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700529 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700530 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800531#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700532
rago3bd1c872016-09-26 12:58:14 -0700533 BUFLOG_RESET;
534
Glenn Kastend65d73c2012-06-22 17:21:07 -0700535 if (locked) {
536 mLock.unlock();
537 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800538
539 // append a copy of media.log here by forwarding fd to it, but don't attempt
540 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700541 if (sMediaLogServiceAsBinder != 0) {
542 dprintf(fd, "\nmedia.log:\n");
543 Vector<String16> args;
544 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800545 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700546
547 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700548 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700549 bool unreachableMemory = false;
550 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700551 if (arg == String16("-m")) {
552 dumpMem = true;
553 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700554 unreachableMemory = true;
555 }
556 }
557
Andy Hung07b745e2016-05-23 16:21:07 -0700558 if (dumpMem) {
559 dprintf(fd, "\nDumping memory:\n");
560 std::string s = dumpMemoryAddresses(100 /* limit */);
561 write(fd, s.c_str(), s.size());
562 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700563 if (unreachableMemory) {
564 dprintf(fd, "\nDumping unreachable memory:\n");
565 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700566 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700567 write(fd, s.c_str(), s.size());
568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569 }
570 return NO_ERROR;
571}
572
Eric Laurent021cf962014-05-13 10:18:14 -0700573sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800574{
Eric Laurent021cf962014-05-13 10:18:14 -0700575 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800576 // If pid is already in the mClients wp<> map, then use that entry
577 // (for which promote() is always != 0), otherwise create a new entry and Client.
578 sp<Client> client = mClients.valueFor(pid).promote();
579 if (client == 0) {
580 client = new Client(this, pid);
581 mClients.add(pid, client);
582 }
583
584 return client;
585}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586
Glenn Kasten9e58b552013-01-18 15:09:48 -0800587sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
588{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700589 // If there is no memory allocated for logs, return a dummy writer that does nothing.
590 // Similarly if we can't contact the media.log service, also return a dummy writer.
591 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800592 return new NBLog::Writer();
593 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700594 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
595 // If allocation fails, consult the vector of previously unregistered writers
596 // and garbage-collect one or more them until an allocation succeeds
597 if (shared == 0) {
598 Mutex::Autolock _l(mUnregisteredWritersLock);
599 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
600 {
601 // Pick the oldest stale writer to garbage-collect
602 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
603 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700604 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700605 // Now the media.log remote reference to IMemory is gone. When our last local
606 // reference to IMemory also drops to zero at end of this block,
607 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
608 }
609 // Re-attempt the allocation
610 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
611 if (shared != 0) {
612 goto success;
613 }
614 }
615 // Even after garbage-collecting all old writers, there is still not enough memory,
616 // so return a dummy writer
617 return new NBLog::Writer();
618 }
619success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800620 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
621 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
622 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700623 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800624 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800625}
626
627void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
628{
Glenn Kasten685ef092013-02-04 08:15:34 -0800629 if (writer == 0) {
630 return;
631 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800632 sp<IMemory> iMemory(writer->getIMemory());
633 if (iMemory == 0) {
634 return;
635 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700636 // Rather than removing the writer immediately, append it to a queue of old writers to
637 // be garbage-collected later. This allows us to continue to view old logs for a while.
638 Mutex::Autolock _l(mUnregisteredWritersLock);
639 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800640}
641
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642// IAudioFlinger interface
643
Eric Laurent21da6472017-11-09 16:29:26 -0800644sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
645 CreateTrackOutput& output,
646 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647{
648 sp<PlaybackThread::Track> track;
649 sp<TrackHandle> trackHandle;
650 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800652 audio_stream_type_t streamType;
653 audio_port_handle_t portId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654
Eric Laurent21da6472017-11-09 16:29:26 -0800655 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700656 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800657 uid_t clientUid = input.clientInfo.clientUid;
658 if (!isTrustedCallingUid(callingUid)) {
659 ALOGW_IF(clientUid != callingUid,
660 "%s uid %d tried to pass itself off as %d",
661 __FUNCTION__, callingUid, clientUid);
662 clientUid = callingUid;
663 updatePid = true;
664 }
665 pid_t clientPid = input.clientInfo.clientPid;
666 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700667 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800668 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700669 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800670 __func__, callingUid, callingPid, clientPid);
671 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700672 }
673
Eric Laurent21da6472017-11-09 16:29:26 -0800674 audio_session_t sessionId = input.sessionId;
675 if (sessionId == AUDIO_SESSION_ALLOCATE) {
676 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800677 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
678 lStatus = BAD_VALUE;
679 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800680 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800681
Eric Laurent21da6472017-11-09 16:29:26 -0800682 output.sessionId = sessionId;
683 output.outputId = AUDIO_IO_HANDLE_NONE;
684 output.selectedDeviceId = input.selectedDeviceId;
685
686 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
687 clientUid, &input.config, input.flags,
688 &output.selectedDeviceId, &portId);
689
690 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
691 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
692 goto Exit;
693 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800694 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
695 // but if someone uses binder directly they could bypass that and cause us to crash
696 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000697 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 lStatus = BAD_VALUE;
699 goto Exit;
700 }
701
Glenn Kasten53b5d092014-02-05 10:00:23 -0800702 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800703 if (!audio_is_output_channel(input.config.channel_mask)) {
704 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800705 lStatus = BAD_VALUE;
706 goto Exit;
707 }
708
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700709 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800710 if (!audio_is_valid_format(input.config.format)) {
711 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700712 lStatus = BAD_VALUE;
713 goto Exit;
714 }
715
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 {
717 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800718 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800720 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 lStatus = BAD_VALUE;
722 goto Exit;
723 }
724
Eric Laurent21da6472017-11-09 16:29:26 -0800725 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726
Glenn Kastene848bd92014-03-13 15:00:32 -0700727 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800728 // check if an effect chain with the same session ID is present on another
729 // output thread and move it here.
730 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
731 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
732 if (mPlaybackThreads.keyAt(i) != output.outputId) {
733 uint32_t sessions = t->hasAudioSession(sessionId);
734 if (sessions & ThreadBase::EFFECT_SESSION) {
735 effectThread = t.get();
736 break;
Eric Laurentde070132010-07-13 04:45:46 -0700737 }
738 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739 }
Eric Laurent21da6472017-11-09 16:29:26 -0800740 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700741
Eric Laurent21da6472017-11-09 16:29:26 -0800742 output.sampleRate = input.config.sample_rate;
743 output.frameCount = input.frameCount;
744 output.notificationFrameCount = input.notificationFrameCount;
745 output.flags = input.flags;
746
747 track = thread->createTrack_l(client, streamType, &output.sampleRate, input.config.format,
748 input.config.channel_mask,
749 &output.frameCount, &output.notificationFrameCount,
750 input.notificationsPerBuffer, input.speed,
751 input.sharedBuffer, sessionId, &output.flags,
752 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800753 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700754 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700755
Eric Laurent21da6472017-11-09 16:29:26 -0800756 output.afFrameCount = thread->frameCount();
757 output.afSampleRate = thread->sampleRate();
758 output.afLatencyMs = thread->latency();
759
Eric Laurent39e94f82010-07-28 01:32:47 -0700760 // move effect chain to this output thread if an effect on same session was waiting
761 // for a track to be created
762 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700763 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700764 Mutex::Autolock _dl(thread->mLock);
765 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800766 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700767 }
Eric Laurenta011e352012-03-29 15:51:43 -0700768
769 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700770 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800771 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700772 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700773 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700774 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700775 } else {
776 mPendingSyncEvents[i]->cancel();
777 }
Eric Laurenta011e352012-03-29 15:51:43 -0700778 mPendingSyncEvents.removeAt(i);
779 i--;
780 }
781 }
782 }
Glenn Kastene198c362013-08-13 09:13:36 -0700783
Eric Laurent21da6472017-11-09 16:29:26 -0800784 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 }
Glenn Kastene198c362013-08-13 09:13:36 -0700786
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700787 if (lStatus != NO_ERROR) {
788 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700789 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700790 // Don't hold mClientLock when releasing the reference on the track as the
791 // destructor will acquire it.
792 {
793 Mutex::Autolock _cl(mClientLock);
794 client.clear();
795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700797 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 }
799
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700800 // return handle to client
801 trackHandle = new TrackHandle(track);
802
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800804 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
805 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
806 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700807 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 return trackHandle;
809}
810
Glenn Kasten2c073da2016-02-26 09:14:08 -0800811uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812{
813 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800814 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800816 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return 0;
818 }
819 return thread->sampleRate();
820}
821
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800822audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823{
824 Mutex::Autolock _l(mLock);
825 PlaybackThread *thread = checkPlaybackThread_l(output);
826 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000827 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800828 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 }
830 return thread->format();
831}
832
Glenn Kasten2c073da2016-02-26 09:14:08 -0800833size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834{
835 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800836 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800838 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839 return 0;
840 }
Glenn Kasten58912562012-04-03 10:45:00 -0700841 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
842 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 return thread->frameCount();
844}
845
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700846size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
847{
848 Mutex::Autolock _l(mLock);
849 ThreadBase *thread = checkThread_l(ioHandle);
850 if (thread == NULL) {
851 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
852 return 0;
853 }
854 return thread->frameCountHAL();
855}
856
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800857uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858{
859 Mutex::Autolock _l(mLock);
860 PlaybackThread *thread = checkPlaybackThread_l(output);
861 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800862 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700863 return 0;
864 }
865 return thread->latency();
866}
867
868status_t AudioFlinger::setMasterVolume(float value)
869{
Eric Laurenta1884f92011-08-23 08:25:03 -0700870 status_t ret = initCheck();
871 if (ret != NO_ERROR) {
872 return ret;
873 }
874
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 // check calling permissions
876 if (!settingsAllowed()) {
877 return PERMISSION_DENIED;
878 }
879
Eric Laurenta4c5a552012-03-29 10:12:40 -0700880 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700881 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700882
John Grossmanee578c02012-07-23 17:05:46 -0700883 // Set master volume in the HALs which support it.
884 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
885 AutoMutex lock(mHardwareLock);
886 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800887
John Grossmanee578c02012-07-23 17:05:46 -0700888 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
889 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700890 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800891 }
John Grossmanee578c02012-07-23 17:05:46 -0700892 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894
John Grossmanee578c02012-07-23 17:05:46 -0700895 // Now set the master volume in each playback thread. Playback threads
896 // assigned to HALs which do not have master volume support will apply
897 // master volume during the mix operation. Threads with HALs which do
898 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700899 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
900 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
901 continue;
902 }
John Grossmanee578c02012-07-23 17:05:46 -0700903 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700904 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905
906 return NO_ERROR;
907}
908
Glenn Kastenf78aee72012-01-04 11:00:47 -0800909status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700910{
Eric Laurenta1884f92011-08-23 08:25:03 -0700911 status_t ret = initCheck();
912 if (ret != NO_ERROR) {
913 return ret;
914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915
916 // check calling permissions
917 if (!settingsAllowed()) {
918 return PERMISSION_DENIED;
919 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800920 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000921 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 return BAD_VALUE;
923 }
924
925 { // scope for the lock
926 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700927 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700929 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 mHardwareStatus = AUDIO_HW_IDLE;
931 }
932
933 if (NO_ERROR == ret) {
934 Mutex::Autolock _l(mLock);
935 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800936 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700937 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 }
939
940 return ret;
941}
942
943status_t AudioFlinger::setMicMute(bool state)
944{
Eric Laurenta1884f92011-08-23 08:25:03 -0700945 status_t ret = initCheck();
946 if (ret != NO_ERROR) {
947 return ret;
948 }
949
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 // check calling permissions
951 if (!settingsAllowed()) {
952 return PERMISSION_DENIED;
953 }
954
955 AutoMutex lock(mHardwareLock);
956 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700957 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700958 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
959 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700960 if (result != NO_ERROR) {
961 ret = result;
962 }
963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 mHardwareStatus = AUDIO_HW_IDLE;
965 return ret;
966}
967
968bool AudioFlinger::getMicMute() const
969{
Eric Laurenta1884f92011-08-23 08:25:03 -0700970 status_t ret = initCheck();
971 if (ret != NO_ERROR) {
972 return false;
973 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800974 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700975 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800976 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800978 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700979 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
980 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800981 if (result == NO_ERROR) {
982 mute = mute && state;
983 }
984 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800986
987 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988}
989
990status_t AudioFlinger::setMasterMute(bool muted)
991{
John Grossmand8f178d2012-07-20 14:51:35 -0700992 status_t ret = initCheck();
993 if (ret != NO_ERROR) {
994 return ret;
995 }
996
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 // check calling permissions
998 if (!settingsAllowed()) {
999 return PERMISSION_DENIED;
1000 }
1001
John Grossmanee578c02012-07-23 17:05:46 -07001002 Mutex::Autolock _l(mLock);
1003 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001004
John Grossmanee578c02012-07-23 17:05:46 -07001005 // Set master mute in the HALs which support it.
1006 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1007 AutoMutex lock(mHardwareLock);
1008 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001009
John Grossmanee578c02012-07-23 17:05:46 -07001010 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1011 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001012 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001013 }
John Grossmanee578c02012-07-23 17:05:46 -07001014 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001015 }
1016
John Grossmanee578c02012-07-23 17:05:46 -07001017 // Now set the master mute in each playback thread. Playback threads
1018 // assigned to HALs which do not have master mute support will apply master
1019 // mute during the mix operation. Threads with HALs which do support master
1020 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001021 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1022 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1023 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001024 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025
1026 return NO_ERROR;
1027}
1028
1029float AudioFlinger::masterVolume() const
1030{
Glenn Kasten98067102011-12-13 11:47:54 -08001031 Mutex::Autolock _l(mLock);
1032 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033}
1034
1035bool AudioFlinger::masterMute() const
1036{
Glenn Kasten98067102011-12-13 11:47:54 -08001037 Mutex::Autolock _l(mLock);
1038 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039}
1040
John Grossman4ff14ba2012-02-08 16:37:41 -08001041float AudioFlinger::masterVolume_l() const
1042{
John Grossman4ff14ba2012-02-08 16:37:41 -08001043 return mMasterVolume;
1044}
1045
John Grossmand8f178d2012-07-20 14:51:35 -07001046bool AudioFlinger::masterMute_l() const
1047{
John Grossmanee578c02012-07-23 17:05:46 -07001048 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001049}
1050
Eric Laurent223fd5c2014-11-11 13:43:36 -08001051status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1052{
1053 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001054 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001055 return BAD_VALUE;
1056 }
1057 pid_t caller = IPCThreadState::self()->getCallingPid();
1058 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001059 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001060 return PERMISSION_DENIED;
1061 }
1062
1063 return NO_ERROR;
1064}
1065
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001066status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1067 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068{
1069 // check calling permissions
1070 if (!settingsAllowed()) {
1071 return PERMISSION_DENIED;
1072 }
1073
Eric Laurent223fd5c2014-11-11 13:43:36 -08001074 status_t status = checkStreamType(stream);
1075 if (status != NO_ERROR) {
1076 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001078 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079
1080 AutoMutex lock(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001081 Vector<VolumeInterface *> volumeInterfaces;
Glenn Kasten142f5192014-03-25 17:44:59 -07001082 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001083 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1084 if (volumeInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 return BAD_VALUE;
1086 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001087 volumeInterfaces.add(volumeInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 }
1089
1090 mStreamTypes[stream].volume = value;
1091
Eric Laurent6acd1d42017-01-04 14:23:29 -08001092 if (volumeInterfaces.size() == 0) {
1093 volumeInterfaces = getAllVolumeInterfaces_l();
1094 }
1095 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1096 volumeInterfaces[i]->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097 }
1098
1099 return NO_ERROR;
1100}
1101
Glenn Kastenfff6d712012-01-12 16:38:12 -08001102status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103{
1104 // check calling permissions
1105 if (!settingsAllowed()) {
1106 return PERMISSION_DENIED;
1107 }
1108
Eric Laurent223fd5c2014-11-11 13:43:36 -08001109 status_t status = checkStreamType(stream);
1110 if (status != NO_ERROR) {
1111 return status;
1112 }
1113 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1114
1115 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001116 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 return BAD_VALUE;
1118 }
1119
Eric Laurent93575202011-01-18 18:39:02 -08001120 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001122 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1123 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1124 volumeInterfaces[i]->setStreamMute(stream, muted);
1125 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126
1127 return NO_ERROR;
1128}
1129
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001130float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001132 status_t status = checkStreamType(stream);
1133 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134 return 0.0f;
1135 }
1136
1137 AutoMutex lock(mLock);
1138 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001139 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001140 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1141 if (volumeInterface != NULL) {
1142 volume = volumeInterface->streamVolume(stream);
1143 } else {
1144 volume = 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001147 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 }
1149
1150 return volume;
1151}
1152
Glenn Kastenfff6d712012-01-12 16:38:12 -08001153bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001155 status_t status = checkStreamType(stream);
1156 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 return true;
1158 }
1159
Glenn Kasten6637baa2012-01-09 09:40:36 -08001160 AutoMutex lock(mLock);
1161 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162}
1163
Eric Laurent054d9d32015-04-24 08:48:48 -07001164
1165void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1166{
1167 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1168 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1169 }
1170}
1171
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001172status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001174 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1175 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001176
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 // check calling permissions
1178 if (!settingsAllowed()) {
1179 return PERMISSION_DENIED;
1180 }
1181
Glenn Kasten142f5192014-03-25 17:44:59 -07001182 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1183 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001184 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001185 // result will remain NO_INIT if no audio device is present
1186 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001187 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001188 AutoMutex lock(mHardwareLock);
1189 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1190 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001191 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1192 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001193 // return success if at least one audio device accepts the parameters as not all
1194 // HALs are requested to support all parameters. If no audio device supports the
1195 // requested parameters, the last error is reported.
1196 if (final_result != NO_ERROR) {
1197 final_result = result;
1198 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001199 }
1200 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001201 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001202 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1203 AudioParameter param = AudioParameter(keyValuePairs);
1204 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001205 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1206 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001207 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001208 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001209 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001210 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001211 }
1212 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001213 String8 screenState;
1214 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001215 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001216 if (isOff != (AudioFlinger::mScreenState & 1)) {
1217 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001218 }
1219 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001220 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 }
1222
1223 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1224 // and the thread is exited once the lock is released
1225 sp<ThreadBase> thread;
1226 {
1227 Mutex::Autolock _l(mLock);
1228 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001229 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001231 if (thread == 0) {
1232 thread = checkMmapThread_l(ioHandle);
1233 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001234 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001235 // indicate output device change to all input threads for pre processing
1236 AudioParameter param = AudioParameter(keyValuePairs);
1237 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001238 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1239 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001240 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 }
1243 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001244 if (thread != 0) {
1245 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 }
1247 return BAD_VALUE;
1248}
1249
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001250String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001252 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1253 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254
Eric Laurenta4c5a552012-03-29 10:12:40 -07001255 Mutex::Autolock _l(mLock);
1256
Glenn Kasten142f5192014-03-25 17:44:59 -07001257 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001258 String8 out_s8;
1259
Dima Zavin799a70e2011-04-18 16:57:27 -07001260 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001261 String8 s;
1262 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001263 {
1264 AutoMutex lock(mHardwareLock);
1265 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001266 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1267 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001268 mHardwareStatus = AUDIO_HW_IDLE;
1269 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001270 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001271 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001272 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273 }
1274
Eric Laurent6acd1d42017-01-04 14:23:29 -08001275 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1276 if (thread == NULL) {
1277 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1278 if (thread == NULL) {
1279 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1280 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001281 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001282 }
1283 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001284 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001285 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286}
1287
Glenn Kastendd8104c2012-07-02 12:42:44 -07001288size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1289 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290{
Eric Laurenta1884f92011-08-23 08:25:03 -07001291 status_t ret = initCheck();
1292 if (ret != NO_ERROR) {
1293 return 0;
1294 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001295 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001296 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001297 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001298 return 0;
1299 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001300
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001301 AutoMutex lock(mHardwareLock);
1302 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001303 audio_config_t config, proposed;
1304 memset(&proposed, 0, sizeof(proposed));
1305 proposed.sample_rate = sampleRate;
1306 proposed.channel_mask = channelMask;
1307 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001308
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001309 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001310 size_t frames;
1311 for (;;) {
1312 // Note: config is currently a const parameter for get_input_buffer_size()
1313 // but we use a copy from proposed in case config changes from the call.
1314 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001315 status_t result = dev->getInputBufferSize(&config, &frames);
1316 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001317 break; // hal success, config is the result
1318 }
1319 // change one parameter of the configuration each iteration to a more "common" value
1320 // to see if the device will support it.
1321 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1322 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1323 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1324 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1325 } else {
1326 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1327 "format %#x, channelMask 0x%X",
1328 sampleRate, format, channelMask);
1329 break; // retries failed, break out of loop with frames == 0.
1330 }
1331 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001332 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001333 if (frames > 0 && config.sample_rate != sampleRate) {
1334 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1335 }
1336 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337}
1338
Glenn Kasten5f972c02014-01-13 09:59:31 -08001339uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001340{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001341 Mutex::Autolock _l(mLock);
1342
1343 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1344 if (recordThread != NULL) {
1345 return recordThread->getInputFramesLost();
1346 }
1347 return 0;
1348}
1349
1350status_t AudioFlinger::setVoiceVolume(float value)
1351{
Eric Laurenta1884f92011-08-23 08:25:03 -07001352 status_t ret = initCheck();
1353 if (ret != NO_ERROR) {
1354 return ret;
1355 }
1356
Mathias Agopian65ab4712010-07-14 17:59:35 -07001357 // check calling permissions
1358 if (!settingsAllowed()) {
1359 return PERMISSION_DENIED;
1360 }
1361
1362 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001363 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001364 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001365 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366 mHardwareStatus = AUDIO_HW_IDLE;
1367
1368 return ret;
1369}
1370
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001371status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001372 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001373{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374 Mutex::Autolock _l(mLock);
1375
1376 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1377 if (playbackThread != NULL) {
1378 return playbackThread->getRenderPosition(halFrames, dspFrames);
1379 }
1380
1381 return BAD_VALUE;
1382}
1383
1384void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1385{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001387 if (client == 0) {
1388 return;
1389 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001390 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001391 {
1392 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001393 if (mNotificationClients.indexOfKey(pid) < 0) {
1394 sp<NotificationClient> notificationClient = new NotificationClient(this,
1395 client,
1396 pid);
1397 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001398
Eric Laurent021cf962014-05-13 10:18:14 -07001399 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400
Marco Nelissen06b46062014-11-14 07:58:25 -08001401 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001402 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001403 }
1404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405
Eric Laurent021cf962014-05-13 10:18:14 -07001406 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001407 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001408 // the config change is always sent from playback or record threads to avoid deadlock
1409 // with AudioSystem::gLock
1410 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001411 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001412 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001414 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001415 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416 }
1417}
1418
1419void AudioFlinger::removeNotificationClient(pid_t pid)
1420{
1421 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001422 {
1423 Mutex::Autolock _cl(mClientLock);
1424 mNotificationClients.removeItem(pid);
1425 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001426
Steve Block3856b092011-10-20 11:56:00 +01001427 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001428 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001429 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001430 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001431 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001432 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001433 if (ref->mPid == pid) {
1434 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001435 mAudioSessionRefs.removeAt(i);
1436 delete ref;
1437 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001438 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001439 } else {
1440 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001441 }
1442 }
1443 if (removed) {
1444 purgeStaleEffects_l();
1445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446}
1447
Eric Laurent73e26b62015-04-27 16:55:58 -07001448void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001449 const sp<AudioIoDescriptor>& ioDesc,
1450 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451{
Eric Laurent021cf962014-05-13 10:18:14 -07001452 Mutex::Autolock _l(mClientLock);
1453 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001455 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1456 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1457 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458 }
1459}
1460
Eric Laurent021cf962014-05-13 10:18:14 -07001461// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001462void AudioFlinger::removeClient_l(pid_t pid)
1463{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001464 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001465 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 mClients.removeItem(pid);
1467}
1468
Eric Laurent717e1282012-06-29 16:36:52 -07001469// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001470sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1471 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001472{
1473 sp<PlaybackThread> thread;
1474
1475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1476 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1477 ALOG_ASSERT(thread == 0);
1478 thread = mPlaybackThreads.valueAt(i);
1479 }
1480 }
1481
1482 return thread;
1483}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486
1487// ----------------------------------------------------------------------------
1488
1489AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1490 : RefBase(),
1491 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001492 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301494 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1495 heapSize *= 1024;
1496 if (!heapSize) {
1497 heapSize = kClientSharedHeapSizeBytes;
1498 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1499 // invalidated tracks
1500 if (!audioFlinger->isLowRamDevice()) {
1501 heapSize *= kClientSharedHeapSizeMultiplier;
1502 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001503 }
1504 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505}
1506
Eric Laurent021cf962014-05-13 10:18:14 -07001507// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508AudioFlinger::Client::~Client()
1509{
1510 mAudioFlinger->removeClient_l(mPid);
1511}
1512
Glenn Kasten435dbe62012-01-30 10:15:48 -08001513sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514{
1515 return mMemoryDealer;
1516}
1517
1518// ----------------------------------------------------------------------------
1519
1520AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1521 const sp<IAudioFlingerClient>& client,
1522 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001523 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524{
1525}
1526
1527AudioFlinger::NotificationClient::~NotificationClient()
1528{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529}
1530
Glenn Kasten0f11b512014-01-31 16:18:54 -08001531void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532{
1533 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001534 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535}
1536
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001537// ----------------------------------------------------------------------------
1538AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1539 : mPendingRequests(false) {}
1540
1541
1542void AudioFlinger::MediaLogNotifier::requestMerge() {
1543 AutoMutex _l(mMutex);
1544 mPendingRequests = true;
1545 mCond.signal();
1546}
1547
1548bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001549 // Should already have been checked, but just in case
1550 if (sMediaLogService == 0) {
1551 return false;
1552 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001553 // Wait until there are pending requests
1554 {
1555 AutoMutex _l(mMutex);
1556 mPendingRequests = false; // to ignore past requests
1557 while (!mPendingRequests) {
1558 mCond.wait(mMutex);
1559 // TODO may also need an exitPending check
1560 }
1561 mPendingRequests = false;
1562 }
1563 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001564 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001565 usleep(kPostTriggerSleepPeriod);
1566 return true;
1567}
1568
1569void AudioFlinger::requestLogMerge() {
1570 mMediaLogNotifier->requestMerge();
1571}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572
1573// ----------------------------------------------------------------------------
1574
Eric Laurentf14db3c2017-12-08 14:20:36 -08001575sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1576 CreateRecordOutput& output,
1577 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578{
1579 sp<RecordThread::RecordTrack> recordTrack;
1580 sp<RecordHandle> recordHandle;
1581 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001583 audio_session_t sessionId = input.sessionId;
1584 audio_port_handle_t portId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585
Eric Laurentf14db3c2017-12-08 14:20:36 -08001586 output.cblk.clear();
1587 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001588 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001589
Eric Laurentf14db3c2017-12-08 14:20:36 -08001590 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001591 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001592 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001593 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001594 ALOGW_IF(clientUid != callingUid,
1595 "%s uid %d tried to pass itself off as %d",
1596 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001597 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001598 updatePid = true;
1599 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001600 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001601 if (updatePid) {
1602 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001603 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001604 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001605 __func__, callingUid, callingPid, clientPid);
1606 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001607 }
1608
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 // check calling permissions
Eric Laurentf14db3c2017-12-08 14:20:36 -08001610 if (!recordingAllowed(input.opPackageName, input.clientInfo.clientTid, clientUid)) {
1611 ALOGE("createRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 lStatus = PERMISSION_DENIED;
1613 goto Exit;
1614 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001615 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001616 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1617 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001618 lStatus = BAD_VALUE;
1619 goto Exit;
1620 }
1621
Glenn Kasten53b5d092014-02-05 10:00:23 -08001622 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001623 if (!audio_is_input_channel(input.config.channel_mask)) {
1624 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001625 lStatus = BAD_VALUE;
1626 goto Exit;
1627 }
1628
Eric Laurentf14db3c2017-12-08 14:20:36 -08001629 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1630 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1631 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1632 lStatus = BAD_VALUE;
1633 goto Exit;
1634 }
1635
1636 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001637 output.selectedDeviceId = input.selectedDeviceId;
1638 output.flags = input.flags;
1639
1640 client = registerPid(clientPid);
1641
1642 // Not a conventional loop, but a retry loop for at most two iterations total.
1643 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1644 // Exits loop via break on no error of got exit on error
1645 // The sp<> references will be dropped when re-entering scope.
1646 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1647 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001648 // release previously opened input if retrying.
1649 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1650 recordTrack.clear();
1651 AudioSystem::releaseInput(output.inputId, sessionId);
1652 output.inputId = AUDIO_IO_HANDLE_NONE;
1653 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001654 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1655 sessionId,
1656 // FIXME compare to AudioTrack
1657 clientPid,
1658 clientUid,
1659 &input.config,
1660 output.flags, &output.selectedDeviceId, &portId);
1661
Glenn Kasten05997e22014-03-13 15:08:33 -07001662 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001664 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001666 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667 lStatus = BAD_VALUE;
1668 goto Exit;
1669 }
1670
Eric Laurentf14db3c2017-12-08 14:20:36 -08001671 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672
Eric Laurentf14db3c2017-12-08 14:20:36 -08001673 output.sampleRate = input.config.sample_rate;
1674 output.frameCount = input.frameCount;
1675 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001676
Eric Laurentf14db3c2017-12-08 14:20:36 -08001677 recordTrack = thread->createRecordTrack_l(client, &output.sampleRate,
1678 input.config.format, input.config.channel_mask,
1679 &output.frameCount, sessionId,
1680 &output.notificationFrameCount,
1681 clientUid, &output.flags,
1682 input.clientInfo.clientTid,
1683 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001684 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001685
Eric Laurentf14db3c2017-12-08 14:20:36 -08001686 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1687 // audio policy manager without FAST constraint
1688 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001689 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001690 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001691
1692 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001693 goto Exit;
1694 }
1695
1696 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1697 // session and move it to this thread.
1698 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1699 if (chain != 0) {
1700 Mutex::Autolock _l(thread->mLock);
1701 thread->addEffectChain_l(chain);
1702 }
1703 break;
1704 }
1705 // End of retry loop.
1706 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707 }
Glenn Kastene198c362013-08-13 09:13:36 -07001708
Eric Laurentf14db3c2017-12-08 14:20:36 -08001709 output.cblk = recordTrack->getCblk();
1710 output.buffers = recordTrack->getBuffers();
1711
1712 // return handle to client
1713 recordHandle = new RecordHandle(recordTrack);
1714
1715Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001716 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001717 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001718 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001719 // Don't hold mClientLock when releasing the reference on the track as the
1720 // destructor will acquire it.
1721 {
1722 Mutex::Autolock _cl(mClientLock);
1723 client.clear();
1724 }
Eric Laurent896c9672017-12-08 14:08:45 -08001725 recordTrack.clear();
1726 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1727 AudioSystem::releaseInput(output.inputId, sessionId);
1728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 }
1730
Glenn Kasten9156ef32013-08-06 15:39:08 -07001731 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 return recordHandle;
1733}
1734
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001735
1736
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737// ----------------------------------------------------------------------------
1738
Eric Laurenta4c5a552012-03-29 10:12:40 -07001739audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1740{
Eric Laurent44622db2014-08-01 19:00:33 -07001741 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001742 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001743 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001744 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001745 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001746 }
1747 Mutex::Autolock _l(mLock);
1748 return loadHwModule_l(name);
1749}
1750
1751// loadHwModule_l() must be called with AudioFlinger::mLock held
1752audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1753{
1754 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1755 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1756 ALOGW("loadHwModule() module %s already loaded", name);
1757 return mAudioHwDevs.keyAt(i);
1758 }
1759 }
1760
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001761 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001762
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001763 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001764 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001765 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001766 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001767 }
1768
1769 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001770 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001771 mHardwareStatus = AUDIO_HW_IDLE;
1772 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001773 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001774 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001775 }
1776
John Grossmanee578c02012-07-23 17:05:46 -07001777 // Check and cache this HAL's level of support for master mute and master
1778 // volume. If this is the first HAL opened, and it supports the get
1779 // methods, use the initial values provided by the HAL as the current
1780 // master mute and volume settings.
1781
1782 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1783 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001784 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001785
1786 if (0 == mAudioHwDevs.size()) {
1787 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001788 float mv;
1789 if (OK == dev->getMasterVolume(&mv)) {
1790 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001791 }
1792
1793 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001794 bool mm;
1795 if (OK == dev->getMasterMute(&mm)) {
1796 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001797 }
1798 }
1799
Eric Laurenta4c5a552012-03-29 10:12:40 -07001800 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001801 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001802 flags = static_cast<AudioHwDevice::Flags>(flags |
1803 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1804 }
1805
1806 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001807 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001808 flags = static_cast<AudioHwDevice::Flags>(flags |
1809 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1810 }
1811
Eric Laurenta4c5a552012-03-29 10:12:40 -07001812 mHardwareStatus = AUDIO_HW_IDLE;
1813 }
1814
Glenn Kastena13cde92016-03-28 15:26:02 -07001815 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001816 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001817
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001818 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001819
1820 return handle;
1821
1822}
1823
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001824// ----------------------------------------------------------------------------
1825
Glenn Kasten3b16c762012-11-14 08:44:39 -08001826uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001827{
1828 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001829 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001830 return thread != NULL ? thread->sampleRate() : 0;
1831}
1832
Glenn Kastene33054e2012-11-14 12:54:39 -08001833size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001834{
1835 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001836 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001837 return thread != NULL ? thread->frameCountHAL() : 0;
1838}
1839
1840// ----------------------------------------------------------------------------
1841
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001842status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1843{
1844 uid_t uid = IPCThreadState::self()->getCallingUid();
1845 if (uid != AID_SYSTEM) {
1846 return PERMISSION_DENIED;
1847 }
1848 Mutex::Autolock _l(mLock);
1849 if (mIsDeviceTypeKnown) {
1850 return INVALID_OPERATION;
1851 }
1852 mIsLowRamDevice = isLowRamDevice;
1853 mIsDeviceTypeKnown = true;
1854 return NO_ERROR;
1855}
1856
Eric Laurent93c3d412014-08-01 14:48:35 -07001857audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1858{
1859 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001860
1861 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1862 if (index >= 0) {
1863 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1864 mHwAvSyncIds.valueAt(index), sessionId);
1865 return mHwAvSyncIds.valueAt(index);
1866 }
1867
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001868 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001869 if (dev == NULL) {
1870 return AUDIO_HW_SYNC_INVALID;
1871 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001872 String8 reply;
1873 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001874 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001875 param = AudioParameter(reply);
1876 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001877
1878 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001879 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001880 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1881 return AUDIO_HW_SYNC_INVALID;
1882 }
1883
1884 // allow only one session for a given HW A/V sync ID.
1885 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1886 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1887 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1888 value, mHwAvSyncIds.keyAt(i));
1889 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001890 break;
1891 }
1892 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001893
1894 mHwAvSyncIds.add(sessionId, value);
1895
1896 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1897 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1898 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001899 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001900 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001901 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001902 thread->setParameters(param.toString());
1903 break;
1904 }
1905 }
1906
1907 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1908 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001909}
1910
Eric Laurent72e3f392015-05-20 14:43:50 -07001911status_t AudioFlinger::systemReady()
1912{
1913 Mutex::Autolock _l(mLock);
1914 ALOGI("%s", __FUNCTION__);
1915 if (mSystemReady) {
1916 ALOGW("%s called twice", __FUNCTION__);
1917 return NO_ERROR;
1918 }
1919 mSystemReady = true;
1920 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1921 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1922 thread->systemReady();
1923 }
1924 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1925 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1926 thread->systemReady();
1927 }
1928 return NO_ERROR;
1929}
1930
Eric Laurentfa90e842014-10-17 18:12:31 -07001931// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1932void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1933{
1934 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1935 if (index >= 0) {
1936 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1937 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1938 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001939 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001940 thread->setParameters(param.toString());
1941 }
1942}
1943
1944
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001945// ----------------------------------------------------------------------------
1946
Eric Laurent83b88082014-06-20 18:31:16 -07001947
Eric Laurent6acd1d42017-01-04 14:23:29 -08001948sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001949 audio_io_handle_t *output,
1950 audio_config_t *config,
1951 audio_devices_t devices,
1952 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001953 audio_output_flags_t flags)
1954{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001955 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001956 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001957 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001958 }
1959
Eric Laurentcf2c0212014-07-25 16:20:43 -07001960 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001961 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1962 } else {
1963 // Audio Policy does not currently request a specific output handle.
1964 // If this is ever needed, see openInput_l() for example code.
1965 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1966 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001967 }
Eric Laurent83b88082014-06-20 18:31:16 -07001968
1969 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1970
Eric Laurent83b88082014-06-20 18:31:16 -07001971 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001972 // This if statement allows overriding the audio policy settings
1973 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1974 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1975 // Check only for Normal Mixing mode
1976 if (kEnableExtendedPrecision) {
1977 // Specify format (uncomment one below to choose)
1978 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1979 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1980 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1981 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001982 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001983 }
1984 if (kEnableExtendedChannels) {
1985 // Specify channel mask (uncomment one below to choose)
1986 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1987 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1988 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1989 }
Eric Laurent83b88082014-06-20 18:31:16 -07001990 }
1991
Phil Burk062e67a2015-02-11 13:40:50 -08001992 AudioStreamOut *outputStream = NULL;
1993 status_t status = outHwDev->openOutputStream(
1994 &outputStream,
1995 *output,
1996 devices,
1997 flags,
1998 config,
1999 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002000
2001 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002002
Phil Burk062e67a2015-02-11 13:40:50 -08002003 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002004 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2005 sp<MmapPlaybackThread> thread =
2006 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2007 devices, AUDIO_DEVICE_NONE, mSystemReady);
2008 mMmapThreads.add(*output, thread);
2009 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2010 *output, thread.get());
2011 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002012 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002013 sp<PlaybackThread> thread;
2014 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2015 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2016 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2017 *output, thread.get());
2018 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2019 || !isValidPcmSinkFormat(config->format)
2020 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2021 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2022 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2023 *output, thread.get());
2024 } else {
2025 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2026 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2027 *output, thread.get());
2028 }
2029 mPlaybackThreads.add(*output, thread);
2030 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002031 }
Eric Laurent83b88082014-06-20 18:31:16 -07002032 }
2033
2034 return 0;
2035}
2036
Eric Laurentcf2c0212014-07-25 16:20:43 -07002037status_t AudioFlinger::openOutput(audio_module_handle_t module,
2038 audio_io_handle_t *output,
2039 audio_config_t *config,
2040 audio_devices_t *devices,
2041 const String8& address,
2042 uint32_t *latencyMs,
2043 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044{
Glenn Kastend3bb6452016-12-05 18:14:37 -08002045 ALOGI("openOutput() this %p, module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, "
2046 "flags %x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002047 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002048 (devices != NULL) ? *devices : 0,
2049 config->sample_rate,
2050 config->format,
2051 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002052 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002054 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002055 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002057
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 Mutex::Autolock _l(mLock);
2059
Eric Laurent6acd1d42017-01-04 14:23:29 -08002060 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002061 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002062 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2063 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2064 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065
Eric Laurent6acd1d42017-01-04 14:23:29 -08002066 // notify client processes of the new output creation
2067 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002068
Eric Laurent6acd1d42017-01-04 14:23:29 -08002069 // the first primary output opened designates the primary hw device
2070 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002071 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002072 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002073
Eric Laurent6acd1d42017-01-04 14:23:29 -08002074 AutoMutex lock(mHardwareLock);
2075 mHardwareStatus = AUDIO_HW_SET_MODE;
2076 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2077 mHardwareStatus = AUDIO_HW_IDLE;
2078 }
2079 } else {
2080 MmapThread *mmapThread = (MmapThread *)thread.get();
2081 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002082 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002083 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 }
2085
Eric Laurentcf2c0212014-07-25 16:20:43 -07002086 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087}
2088
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002089audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2090 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091{
2092 Mutex::Autolock _l(mLock);
2093 MixerThread *thread1 = checkMixerThread_l(output1);
2094 MixerThread *thread2 = checkMixerThread_l(output2);
2095
2096 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002097 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2098 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002099 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100 }
2101
Glenn Kasteneeecb982016-02-26 10:44:04 -08002102 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002103 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104 thread->addOutputTrack(thread2);
2105 mPlaybackThreads.add(id, thread);
2106 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002107 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108 return id;
2109}
2110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002111status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112{
Glenn Kastend96c5722012-04-25 13:44:49 -07002113 return closeOutput_nonvirtual(output);
2114}
2115
2116status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2117{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118 // keep strong reference on the playback thread so that
2119 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002120 sp<PlaybackThread> playbackThread;
2121 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122 {
2123 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002124 playbackThread = checkPlaybackThread_l(output);
2125 if (playbackThread != NULL) {
2126 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127
Eric Laurent6acd1d42017-01-04 14:23:29 -08002128 if (playbackThread->type() == ThreadBase::MIXER) {
2129 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2130 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2131 DuplicatingThread *dupThread =
2132 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2133 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2134 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 }
2136 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002137
2138
Eric Laurent6acd1d42017-01-04 14:23:29 -08002139 mPlaybackThreads.removeItem(output);
2140 // save all effects to the default thread
2141 if (mPlaybackThreads.size()) {
2142 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2143 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002144 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002145 Mutex::Autolock _dl(dstThread->mLock);
2146 Mutex::Autolock _sl(playbackThread->mLock);
2147 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2148 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002149 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2150 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002151 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 }
2153 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002154 } else {
2155 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2156 if (mmapThread == 0) {
2157 return BAD_VALUE;
2158 }
2159 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002160 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002162 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2163 ioDesc->mIoHandle = output;
2164 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002166 // The thread entity (active unit of execution) is no longer running here,
2167 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168
Eric Laurent6acd1d42017-01-04 14:23:29 -08002169 if (playbackThread != 0) {
2170 playbackThread->exit();
2171 if (!playbackThread->isDuplicating()) {
2172 closeOutputFinish(playbackThread);
2173 }
2174 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002175 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002176 mmapThread->exit();
2177 AudioStreamOut *out = mmapThread->clearOutput();
2178 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2179 // from now on thread->mOutput is NULL
2180 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181 }
2182 return NO_ERROR;
2183}
2184
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002185void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002186{
2187 AudioStreamOut *out = thread->clearOutput();
2188 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2189 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002190 delete out;
2191}
2192
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002193void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002194{
2195 mPlaybackThreads.removeItem(thread->mId);
2196 thread->exit();
2197 closeOutputFinish(thread);
2198}
2199
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002200status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201{
2202 Mutex::Autolock _l(mLock);
2203 PlaybackThread *thread = checkPlaybackThread_l(output);
2204
2205 if (thread == NULL) {
2206 return BAD_VALUE;
2207 }
2208
Steve Block3856b092011-10-20 11:56:00 +01002209 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210 thread->suspend();
2211
2212 return NO_ERROR;
2213}
2214
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002215status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002216{
2217 Mutex::Autolock _l(mLock);
2218 PlaybackThread *thread = checkPlaybackThread_l(output);
2219
2220 if (thread == NULL) {
2221 return BAD_VALUE;
2222 }
2223
Steve Block3856b092011-10-20 11:56:00 +01002224 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225
2226 thread->restore();
2227
2228 return NO_ERROR;
2229}
2230
Eric Laurentcf2c0212014-07-25 16:20:43 -07002231status_t AudioFlinger::openInput(audio_module_handle_t module,
2232 audio_io_handle_t *input,
2233 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002234 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002235 const String8& address,
2236 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002237 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238{
Eric Laurent83b88082014-06-20 18:31:16 -07002239 Mutex::Autolock _l(mLock);
2240
Glenn Kastene7d66712015-03-05 13:46:52 -08002241 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002242 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002243 }
2244
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002246
2247 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002248 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002249 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002250 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002252 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002253}
Dima Zavin799a70e2011-04-18 16:57:27 -07002254
Eric Laurent6acd1d42017-01-04 14:23:29 -08002255sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002256 audio_io_handle_t *input,
2257 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002258 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002259 const String8& address,
2260 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002261 audio_input_flags_t flags)
2262{
Glenn Kastene7d66712015-03-05 13:46:52 -08002263 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002264 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002265 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002266 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002267 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002268
Glenn Kasteneeecb982016-02-26 10:44:04 -08002269 // Audio Policy can request a specific handle for hardware hotword.
2270 // The goal here is not to re-open an already opened input.
2271 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002272 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002273 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2274 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2275 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2276 return 0;
2277 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2278 // This should not happen in a transient state with current design.
2279 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2280 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002281 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002282
Eric Laurentcf2c0212014-07-25 16:20:43 -07002283 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002284 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002285 sp<StreamInHalInterface> inStream;
2286 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002287 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Mikhail Naganovf558e022016-11-14 17:45:17 -08002288 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002289 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002290 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002291 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002292 halconfig.sample_rate,
2293 halconfig.format,
2294 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002295 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002296 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002298 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002299 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002300 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002301 audio_is_linear_pcm(config->format) &&
2302 audio_is_linear_pcm(halconfig.format) &&
2303 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002304 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2305 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002306 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002307 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002308 inStream.clear();
2309 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002310 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002311 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 }
2313
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002314 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002315 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002316 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2317 sp<MmapCaptureThread> thread =
2318 new MmapCaptureThread(this, *input,
2319 inHwDev, inputStream,
2320 primaryOutputDevice_l(), devices, mSystemReady);
2321 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002322 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2323 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002324 return thread;
2325 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002326#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002327 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2328 // or (re-)create if current Pipe is idle and does not match the new format
2329 sp<NBAIO_Sink> teeSink;
2330 enum {
2331 TEE_SINK_NO, // don't copy input
2332 TEE_SINK_NEW, // copy input using a new pipe
2333 TEE_SINK_OLD, // copy input using an existing pipe
2334 } kind;
2335 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2336 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2337 if (!mTeeSinkInputEnabled) {
2338 kind = TEE_SINK_NO;
2339 } else if (!Format_isValid(format)) {
2340 kind = TEE_SINK_NO;
2341 } else if (mRecordTeeSink == 0) {
2342 kind = TEE_SINK_NEW;
2343 } else if (mRecordTeeSink->getStrongCount() != 1) {
2344 kind = TEE_SINK_NO;
2345 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2346 kind = TEE_SINK_OLD;
2347 } else {
2348 kind = TEE_SINK_NEW;
2349 }
2350 switch (kind) {
2351 case TEE_SINK_NEW: {
2352 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2353 size_t numCounterOffers = 0;
2354 const NBAIO_Format offers[1] = {format};
2355 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2356 ALOG_ASSERT(index == 0);
2357 PipeReader *pipeReader = new PipeReader(*pipe);
2358 numCounterOffers = 0;
2359 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2360 ALOG_ASSERT(index == 0);
2361 mRecordTeeSink = pipe;
2362 mRecordTeeSource = pipeReader;
2363 teeSink = pipe;
2364 }
2365 break;
2366 case TEE_SINK_OLD:
2367 teeSink = mRecordTeeSink;
2368 break;
2369 case TEE_SINK_NO:
2370 default:
2371 break;
2372 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002373#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002374
2375 // Start record thread
2376 // RecordThread requires both input and output device indication to forward to audio
2377 // pre processing modules
2378 sp<RecordThread> thread = new RecordThread(this,
2379 inputStream,
2380 *input,
2381 primaryOutputDevice_l(),
2382 devices,
2383 mSystemReady
2384#ifdef TEE_SINK
2385 , teeSink
2386#endif
2387 );
2388 mRecordThreads.add(*input, thread);
2389 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2390 return thread;
2391 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392 }
2393
Eric Laurentcf2c0212014-07-25 16:20:43 -07002394 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 return 0;
2396}
2397
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002398status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399{
Glenn Kastend96c5722012-04-25 13:44:49 -07002400 return closeInput_nonvirtual(input);
2401}
2402
2403status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2404{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 // keep strong reference on the record thread so that
2406 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002407 sp<RecordThread> recordThread;
2408 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 {
2410 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002411 recordThread = checkRecordThread_l(input);
2412 if (recordThread != 0) {
2413 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414
Eric Laurent6acd1d42017-01-04 14:23:29 -08002415 // If we still have effect chains, it means that a client still holds a handle
2416 // on at least one effect. We must either move the chain to an existing thread with the
2417 // same session ID or put it aside in case a new record thread is opened for a
2418 // new capture on the same session
2419 sp<EffectChain> chain;
2420 {
2421 Mutex::Autolock _sl(recordThread->mLock);
2422 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2423 // Note: maximum one chain per record thread
2424 if (effectChains.size() != 0) {
2425 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002426 }
2427 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002428 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002429 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002430 // This should only happen in case of overlap between one thread tear down and the
2431 // creation of its replacement
2432 size_t i;
2433 for (i = 0; i < mRecordThreads.size(); i++) {
2434 sp<RecordThread> t = mRecordThreads.valueAt(i);
2435 if (t == recordThread) {
2436 continue;
2437 }
2438 if (t->hasAudioSession(chain->sessionId()) != 0) {
2439 Mutex::Autolock _l(t->mLock);
2440 ALOGV("closeInput() found thread %d for effect session %d",
2441 t->id(), chain->sessionId());
2442 t->addEffectChain_l(chain);
2443 break;
2444 }
2445 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002446 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002447 if (i == mRecordThreads.size()) {
2448 putOrphanEffectChain_l(chain);
2449 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002450 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002451 mRecordThreads.removeItem(input);
2452 } else {
2453 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2454 if (mmapThread == 0) {
2455 return BAD_VALUE;
2456 }
2457 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002458 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002459 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2460 ioDesc->mIoHandle = input;
2461 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 }
Eric Laurent83b88082014-06-20 18:31:16 -07002463 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2464 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002465 if (recordThread != 0) {
2466 closeInputFinish(recordThread);
2467 } else if (mmapThread != 0) {
2468 mmapThread->exit();
2469 AudioStreamIn *in = mmapThread->clearInput();
2470 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2471 // from now on thread->mInput is NULL
2472 delete in;
2473 }
Eric Laurent83b88082014-06-20 18:31:16 -07002474 return NO_ERROR;
2475}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002477void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002478{
2479 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002480 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002481 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002482 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002483 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002484}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002486void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002487{
2488 mRecordThreads.removeItem(thread->mId);
2489 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490}
2491
Glenn Kastend2304db2014-02-03 07:40:31 -08002492status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493{
2494 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002495 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496
2497 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2498 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002499 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002500 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002501 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2502 mMmapThreads[i]->invalidateTracks(stream);
2503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 return NO_ERROR;
2505}
2506
2507
Glenn Kasteneeecb982016-02-26 10:44:04 -08002508audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509{
Glenn Kasten9d003132016-04-06 14:38:09 -07002510 // This is a binder API, so a malicious client could pass in a bad parameter.
2511 // Check for that before calling the internal API nextUniqueId().
2512 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2513 ALOGE("newAudioUniqueId invalid use %d", use);
2514 return AUDIO_UNIQUE_ID_ALLOCATE;
2515 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002516 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517}
2518
Glenn Kastend848eb42016-03-08 13:42:11 -08002519void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002520{
2521 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002522 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002523 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2524 if (pid != -1 && (caller == getpid_cached)) {
2525 caller = pid;
2526 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002527
Eric Laurent021cf962014-05-13 10:18:14 -07002528 {
2529 Mutex::Autolock _cl(mClientLock);
2530 // Ignore requests received from processes not known as notification client. The request
2531 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2532 // called from a different pid leaving a stale session reference. Also we don't know how
2533 // to clear this reference if the client process dies.
2534 if (mNotificationClients.indexOfKey(caller) < 0) {
2535 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2536 return;
2537 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002538 }
2539
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002540 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002541 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002542 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002543 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2544 ref->mCnt++;
2545 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002546 return;
2547 }
2548 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002549 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2550 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002551}
2552
Glenn Kastend848eb42016-03-08 13:42:11 -08002553void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002554{
2555 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002556 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002557 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2558 if (pid != -1 && (caller == getpid_cached)) {
2559 caller = pid;
2560 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002561 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002562 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002563 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002564 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2565 ref->mCnt--;
2566 ALOGV(" decremented refcount to %d", ref->mCnt);
2567 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002568 mAudioSessionRefs.removeAt(i);
2569 delete ref;
2570 purgeStaleEffects_l();
2571 }
2572 return;
2573 }
2574 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002575 // If the caller is mediaserver it is likely that the session being released was acquired
2576 // on behalf of a process not in notification clients and we ignore the warning.
2577 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002578}
2579
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002580bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2581{
2582 size_t num = mAudioSessionRefs.size();
2583 for (size_t i = 0; i < num; i++) {
2584 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2585 if (ref->mSessionid == audioSession) {
2586 return true;
2587 }
2588 }
2589 return false;
2590}
2591
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002592void AudioFlinger::purgeStaleEffects_l() {
2593
Steve Block3856b092011-10-20 11:56:00 +01002594 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002595
2596 Vector< sp<EffectChain> > chains;
2597
2598 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2599 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2600 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2601 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002602 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2603 chains.push(ec);
2604 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002605 }
2606 }
2607 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2608 sp<RecordThread> t = mRecordThreads.valueAt(i);
2609 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2610 sp<EffectChain> ec = t->mEffectChains[j];
2611 chains.push(ec);
2612 }
2613 }
2614
2615 for (size_t i = 0; i < chains.size(); i++) {
2616 sp<EffectChain> ec = chains[i];
2617 int sessionid = ec->sessionId();
2618 sp<ThreadBase> t = ec->mThread.promote();
2619 if (t == 0) {
2620 continue;
2621 }
2622 size_t numsessionrefs = mAudioSessionRefs.size();
2623 bool found = false;
2624 for (size_t k = 0; k < numsessionrefs; k++) {
2625 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002626 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002627 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002628 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002629 found = true;
2630 break;
2631 }
2632 }
2633 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002634 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002635 // remove all effects from the chain
2636 while (ec->mEffects.size()) {
2637 sp<EffectModule> effect = ec->mEffects[0];
2638 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002639 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002640 if (effect->purgeHandles()) {
2641 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002642 }
2643 AudioSystem::unregisterEffect(effect->id());
2644 }
2645 }
2646 }
2647 return;
2648}
2649
Glenn Kasteneeecb982016-02-26 10:44:04 -08002650// checkThread_l() must be called with AudioFlinger::mLock held
2651AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2652{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002653 ThreadBase *thread = checkMmapThread_l(ioHandle);
2654 if (thread == 0) {
2655 switch (audio_unique_id_get_use(ioHandle)) {
2656 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2657 thread = checkPlaybackThread_l(ioHandle);
2658 break;
2659 case AUDIO_UNIQUE_ID_USE_INPUT:
2660 thread = checkRecordThread_l(ioHandle);
2661 break;
2662 default:
2663 break;
2664 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002665 }
2666 return thread;
2667}
2668
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002670AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671{
Glenn Kastena1117922012-01-26 10:53:32 -08002672 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002673}
2674
2675// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002676AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677{
2678 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002679 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680}
2681
2682// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002683AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684{
Glenn Kastena1117922012-01-26 10:53:32 -08002685 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686}
2687
Eric Laurent6acd1d42017-01-04 14:23:29 -08002688// checkMmapThread_l() must be called with AudioFlinger::mLock held
2689AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2690{
2691 return mMmapThreads.valueFor(io).get();
2692}
2693
2694
2695// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2696AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2697{
Eric Laurent7459b902017-04-19 18:10:41 -07002698 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002699 if (volumeInterface == nullptr) {
2700 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2701 if (mmapThread != nullptr) {
2702 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002703 MmapPlaybackThread *mmapPlaybackThread =
2704 static_cast<MmapPlaybackThread *>(mmapThread);
2705 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002706 }
2707 }
2708 }
2709 return volumeInterface;
2710}
2711
2712Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2713{
2714 Vector <VolumeInterface *> volumeInterfaces;
2715 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002716 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002717 }
2718 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2719 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002720 MmapPlaybackThread *mmapPlaybackThread =
2721 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2722 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002723 }
2724 }
2725 return volumeInterfaces;
2726}
2727
Glenn Kasteneeecb982016-02-26 10:44:04 -08002728audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729{
Glenn Kasten9d003132016-04-06 14:38:09 -07002730 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002731 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002732 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2733 for (int retry = 0; retry < maxRetries; retry++) {
2734 // The cast allows wraparound from max positive to min negative instead of abort
2735 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2736 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2737 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2738 // allow wrap by skipping 0 and -1 for session ids
2739 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2740 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2741 return (audio_unique_id_t) (base | use);
2742 }
2743 }
2744 // We have no way of recovering from wraparound
2745 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2746 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747}
2748
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002749AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002750{
2751 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2752 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002753 if(thread->isDuplicating()) {
2754 continue;
2755 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002756 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002757 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002758 return thread;
2759 }
2760 }
2761 return NULL;
2762}
2763
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002764audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002765{
2766 PlaybackThread *thread = primaryPlaybackThread_l();
2767
2768 if (thread == NULL) {
2769 return 0;
2770 }
2771
Eric Laurentf1c04f92012-08-28 14:26:53 -07002772 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002773}
2774
Glenn Kastena7335632016-06-09 17:09:53 -07002775AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2776{
2777 size_t minFrameCount = 0;
2778 PlaybackThread *minThread = NULL;
2779 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2780 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2781 if (!thread->isDuplicating()) {
2782 size_t frameCount = thread->frameCountHAL();
2783 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2784 (frameCount == minFrameCount && thread->hasFastMixer() &&
2785 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2786 minFrameCount = frameCount;
2787 minThread = thread;
2788 }
2789 }
2790 }
2791 return minThread;
2792}
2793
Eric Laurenta011e352012-03-29 15:51:43 -07002794sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002795 audio_session_t triggerSession,
2796 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002797 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002798 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002799{
2800 Mutex::Autolock _l(mLock);
2801
2802 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2803 status_t playStatus = NAME_NOT_FOUND;
2804 status_t recStatus = NAME_NOT_FOUND;
2805 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2806 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2807 if (playStatus == NO_ERROR) {
2808 return event;
2809 }
2810 }
2811 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2812 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2813 if (recStatus == NO_ERROR) {
2814 return event;
2815 }
2816 }
2817 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2818 mPendingSyncEvents.add(event);
2819 } else {
2820 ALOGV("createSyncEvent() invalid event %d", event->type());
2821 event.clear();
2822 }
2823 return event;
2824}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002825
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826// ----------------------------------------------------------------------------
2827// Effect management
2828// ----------------------------------------------------------------------------
2829
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002830sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2831 return mEffectsFactoryHal;
2832}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833
Glenn Kastenf587ba52012-01-26 16:25:10 -08002834status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835{
2836 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002837 if (mEffectsFactoryHal.get()) {
2838 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2839 } else {
2840 return -ENODEV;
2841 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842}
2843
Glenn Kastenf587ba52012-01-26 16:25:10 -08002844status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845{
2846 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002847 if (mEffectsFactoryHal.get()) {
2848 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2849 } else {
2850 return -ENODEV;
2851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852}
2853
Glenn Kasten5e92a782012-01-30 07:40:52 -08002854status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002855 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856{
2857 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002858 if (mEffectsFactoryHal.get()) {
2859 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2860 } else {
2861 return -ENODEV;
2862 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863}
2864
2865
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002866sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 effect_descriptor_t *pDesc,
2868 const sp<IEffectClient>& effectClient,
2869 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002870 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002871 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002872 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002873 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 status_t *status,
2875 int *id,
2876 int *enabled)
2877{
2878 status_t lStatus = NO_ERROR;
2879 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881
Eric Laurentb6436272016-12-07 19:24:50 -08002882 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2883 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2884 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2885 ALOGW_IF(pid != -1 && pid != callingPid,
2886 "%s uid %d pid %d tried to pass itself off as pid %d",
2887 __func__, callingUid, callingPid, pid);
2888 pid = callingPid;
2889 }
2890
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002891 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2892 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893
2894 if (pDesc == NULL) {
2895 lStatus = BAD_VALUE;
2896 goto Exit;
2897 }
2898
Eric Laurent84e9a102010-09-23 16:10:16 -07002899 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002900 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002901 lStatus = PERMISSION_DENIED;
2902 goto Exit;
2903 }
2904
Dima Zavinfce7a472011-04-19 22:30:36 -07002905 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002906 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002907 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002908 lStatus = PERMISSION_DENIED;
2909 goto Exit;
2910 }
2911
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002912 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002913 lStatus = NO_INIT;
2914 goto Exit;
2915 }
2916
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002918 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002920 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002922 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 goto Exit;
2924 }
2925 } else {
2926 // if uuid is not specified, look for an available implementation
2927 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002928 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002929 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930 lStatus = BAD_VALUE;
2931 goto Exit;
2932 }
2933 uint32_t numEffects = 0;
2934 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002935 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 bool found = false;
2937
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002938 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002940 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 goto Exit;
2942 }
2943 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002944 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002946 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 continue;
2948 }
2949 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2950 // If matching type found save effect descriptor. If the session is
2951 // 0 and the effect is not auxiliary, continue enumeration in case
2952 // an auxiliary version of this effect type is available
2953 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002954 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002955 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2957 break;
2958 }
2959 }
2960 }
2961 if (!found) {
2962 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002963 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 goto Exit;
2965 }
2966 // For same effect type, chose auxiliary version over insert version if
2967 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002968 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002970 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 }
2972 }
2973
2974 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002975 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2977 lStatus = INVALID_OPERATION;
2978 goto Exit;
2979 }
2980
Eric Laurent59255e42011-07-27 19:49:51 -07002981 // check recording permission for visualizer
2982 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002983 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002984 lStatus = PERMISSION_DENIED;
2985 goto Exit;
2986 }
2987
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002989 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002990 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002991 // if the output returned by getOutputForEffect() is removed before we lock the
2992 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2993 // and we will exit safely
2994 io = AudioSystem::getOutputForEffect(&desc);
2995 ALOGV("createEffect got output %d", io);
2996 }
2997
2998 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999
3000 // If output is not specified try to find a matching audio session ID in one of the
3001 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003002 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3003 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003004 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003005 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003006 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3007 // output must be specified by AudioPolicyManager when using session
3008 // AUDIO_SESSION_OUTPUT_STAGE
3009 lStatus = BAD_VALUE;
3010 goto Exit;
3011 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003012 // look for the thread where the specified audio session is present
3013 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3014 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3015 io = mPlaybackThreads.keyAt(i);
3016 break;
3017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003019 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003020 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3021 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3022 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003023 break;
3024 }
3025 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003026 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003027 if (io == AUDIO_IO_HANDLE_NONE) {
3028 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3029 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3030 io = mMmapThreads.keyAt(i);
3031 break;
3032 }
3033 }
3034 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003035 // If no output thread contains the requested session ID, default to
3036 // first output. The effect chain will be moved to the correct output
3037 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003038 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003039 io = mPlaybackThreads.keyAt(0);
3040 }
Steve Block3856b092011-10-20 11:56:00 +01003041 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003042 }
3043 ThreadBase *thread = checkRecordThread_l(io);
3044 if (thread == NULL) {
3045 thread = checkPlaybackThread_l(io);
3046 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003047 thread = checkMmapThread_l(io);
3048 if (thread == NULL) {
3049 ALOGE("createEffect() unknown output thread");
3050 lStatus = BAD_VALUE;
3051 goto Exit;
3052 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003053 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003054 } else {
3055 // Check if one effect chain was awaiting for an effect to be created on this
3056 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003057 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003058 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003059 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003060 thread->addEffectChain_l(chain);
3061 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003063
Eric Laurent021cf962014-05-13 10:18:14 -07003064 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003065
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003066 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003067 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003068 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003069 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 if (handle != 0 && id != NULL) {
3071 *id = handle->id();
3072 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003073 if (handle == 0) {
3074 // remove local strong reference to Client with mClientLock held
3075 Mutex::Autolock _cl(mClientLock);
3076 client.clear();
3077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 }
3079
3080Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003081 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 return handle;
3083}
3084
Glenn Kastend848eb42016-03-08 13:42:11 -08003085status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003086 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003087{
Steve Block3856b092011-10-20 11:56:00 +01003088 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003089 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003090 Mutex::Autolock _l(mLock);
3091 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003092 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003093 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 }
Eric Laurentde070132010-07-13 04:45:46 -07003095 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3096 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003097 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003098 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 }
Eric Laurentde070132010-07-13 04:45:46 -07003100 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3101 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003102 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003103 return BAD_VALUE;
3104 }
3105
3106 Mutex::Autolock _dl(dstThread->mLock);
3107 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003108 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109}
3110
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003111// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003112status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003113 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003114 AudioFlinger::PlaybackThread *dstThread,
3115 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003116{
Steve Block3856b092011-10-20 11:56:00 +01003117 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003118 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003119
Eric Laurent59255e42011-07-27 19:49:51 -07003120 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003121 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003122 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003123 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003124 return INVALID_OPERATION;
3125 }
3126
Eric Laurent4c415062016-06-17 16:14:16 -07003127 // Check whether the destination thread and all effects in the chain are compatible
3128 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003129 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003130 " destination thread %p is not compatible with effects in the chain",
3131 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003132 return INVALID_OPERATION;
3133 }
3134
Eric Laurent39e94f82010-07-28 01:32:47 -07003135 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003136 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003137 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003138 // removed.
3139 srcThread->removeEffectChain_l(chain);
3140
3141 // transfer all effects one by one so that new effect chain is created on new thread with
3142 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003143 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003144 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003145 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003146 Vector< sp<EffectModule> > removed;
3147 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003148 while (effect != 0) {
3149 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003150 removed.add(effect);
3151 status = dstThread->addEffect_l(effect);
3152 if (status != NO_ERROR) {
3153 break;
3154 }
Eric Laurentec35a142011-10-05 17:42:25 -07003155 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3156 if (effect->state() == EffectModule::ACTIVE ||
3157 effect->state() == EffectModule::STOPPING) {
3158 effect->start();
3159 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003160 // if the move request is not received from audio policy manager, the effect must be
3161 // re-registered with the new strategy and output
3162 if (dstChain == 0) {
3163 dstChain = effect->chain().promote();
3164 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003165 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003166 status = NO_INIT;
3167 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003168 }
3169 strategy = dstChain->strategy();
3170 }
3171 if (reRegister) {
3172 AudioSystem::unregisterEffect(effect->id());
3173 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003174 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003175 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003176 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003177 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003178 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003179 }
Eric Laurentde070132010-07-13 04:45:46 -07003180 effect = chain->getEffectFromId_l(0);
3181 }
3182
Eric Laurent5baf2af2013-09-12 17:37:00 -07003183 if (status != NO_ERROR) {
3184 for (size_t i = 0; i < removed.size(); i++) {
3185 srcThread->addEffect_l(removed[i]);
3186 if (dstChain != 0 && reRegister) {
3187 AudioSystem::unregisterEffect(removed[i]->id());
3188 AudioSystem::registerEffect(&removed[i]->desc(),
3189 srcThread->id(),
3190 strategy,
3191 sessionId,
3192 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003193 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003194 }
3195 }
3196 }
3197
3198 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199}
3200
Eric Laurent5baf2af2013-09-12 17:37:00 -07003201bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003202{
3203 if (mGlobalEffectEnableTime != 0 &&
3204 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3205 return true;
3206 }
3207
3208 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3209 sp<EffectChain> ec =
3210 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003211 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003212 return true;
3213 }
3214 }
3215 return false;
3216}
3217
Eric Laurent5baf2af2013-09-12 17:37:00 -07003218void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003219{
3220 Mutex::Autolock _l(mLock);
3221
3222 mGlobalEffectEnableTime = systemTime();
3223
3224 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3225 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3226 if (t->mType == ThreadBase::OFFLOAD) {
3227 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3228 }
3229 }
3230
3231}
3232
Eric Laurentaaa44472014-09-12 17:41:50 -07003233status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3234{
Eric Laurentd8365c52017-07-16 15:27:05 -07003235 // clear possible suspended state before parking the chain so that it starts in default state
3236 // when attached to a new record thread
3237 chain->setEffectSuspended_l(FX_IID_AEC, false);
3238 chain->setEffectSuspended_l(FX_IID_NS, false);
3239
Glenn Kastend848eb42016-03-08 13:42:11 -08003240 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003241 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003242 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003243 if (index >= 0) {
3244 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3245 return ALREADY_EXISTS;
3246 }
3247 mOrphanEffectChains.add(session, chain);
3248 return NO_ERROR;
3249}
3250
3251sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3252{
3253 sp<EffectChain> chain;
3254 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003255 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003256 if (index >= 0) {
3257 chain = mOrphanEffectChains.valueAt(index);
3258 mOrphanEffectChains.removeItemsAt(index);
3259 }
3260 return chain;
3261}
3262
3263bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3264{
3265 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003266 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003267 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003268 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003269 if (index >= 0) {
3270 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003271 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003272 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003273 mOrphanEffectChains.removeItemsAt(index);
3274 }
3275 return true;
3276 }
3277 return false;
3278}
3279
3280
Glenn Kastenda6ef132013-01-10 12:31:01 -08003281struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003282#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3283 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003284};
3285
3286int comparEntry(const void *p1, const void *p2)
3287{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003288 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003289}
3290
Glenn Kasten46909e72013-02-26 09:20:22 -08003291#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003292void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293{
Eric Laurent81784c32012-11-19 14:55:58 -08003294 NBAIO_Source *teeSource = source.get();
3295 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003296 // .wav rotation
3297 // There is a benign race condition if 2 threads call this simultaneously.
3298 // They would both traverse the directory, but the result would simply be
3299 // failures at unlink() which are ignored. It's also unlikely since
3300 // normally dumpsys is only done by bugreport or from the command line.
3301 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003302 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003303 size_t teePathLen = strlen(teePath);
3304 DIR *dir = opendir(teePath);
3305 teePath[teePathLen++] = '/';
3306 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003307#define TEE_MAX_SORT 20 // number of entries to sort
3308#define TEE_MAX_KEEP 10 // number of entries to keep
3309 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003310 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003311 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003312 struct dirent de;
3313 struct dirent *result = NULL;
3314 int rc = readdir_r(dir, &de, &result);
3315 if (rc != 0) {
3316 ALOGW("readdir_r failed %d", rc);
3317 break;
3318 }
3319 if (result == NULL) {
3320 break;
3321 }
3322 if (result != &de) {
3323 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3324 break;
3325 }
3326 // ignore non .wav file entries
3327 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003328 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003329 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3330 continue;
3331 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003332 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003333 }
3334 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003335 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003336 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003337 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3338 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003339 (void) unlink(teePath);
3340 }
3341 }
3342 } else {
3343 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003344 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003345 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003346 }
3347 }
Eric Laurent81784c32012-11-19 14:55:58 -08003348 char teeTime[16];
3349 struct timeval tv;
3350 gettimeofday(&tv, NULL);
3351 struct tm tm;
3352 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003353 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003354 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3355 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003356 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3357 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003358 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003359 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003360 char wavHeader[44];
3361 memcpy(wavHeader,
3362 "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",
3363 sizeof(wavHeader));
3364 NBAIO_Format format = teeSource->format();
3365 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003366 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003367 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003368 wavHeader[22] = channelCount; // number of channels
3369 wavHeader[24] = sampleRate; // sample rate
3370 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003371 wavHeader[32] = frameSize; // block alignment
3372 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003373 write(teeFd, wavHeader, sizeof(wavHeader));
3374 size_t total = 0;
3375 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003376#define TEE_SINK_READ 1024 // frames per I/O operation
3377 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003378 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003379 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003380 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003381 bool wasFirstRead = firstRead;
3382 firstRead = false;
3383 if (actual <= 0) {
3384 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3385 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003386 }
Eric Laurent81784c32012-11-19 14:55:58 -08003387 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003388 }
Eric Laurent81784c32012-11-19 14:55:58 -08003389 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003390 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003391 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003392 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003393 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003394 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003395 uint32_t temp = 44 + total * frameSize - 8;
3396 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003397 write(teeFd, &temp, sizeof(temp));
3398 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003399 temp = total * frameSize;
3400 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003401 write(teeFd, &temp, sizeof(temp));
3402 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003403 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003404 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003405 }
Eric Laurent59255e42011-07-27 19:49:51 -07003406 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003407 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003408 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003409 }
Eric Laurent59255e42011-07-27 19:49:51 -07003410 }
3411 }
3412}
Glenn Kasten46909e72013-02-26 09:20:22 -08003413#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003414
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415// ----------------------------------------------------------------------------
3416
3417status_t AudioFlinger::onTransact(
3418 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3419{
3420 return BnAudioFlinger::onTransact(code, data, reply, flags);
3421}
3422
Glenn Kasten63238ef2015-03-02 15:50:29 -08003423} // namespace android