blob: b01e48514192eca684dc6dce3cecfe751aeb0f33 [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
jiabina392a552019-09-23 10:34:20 -070022// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23#define AUDIO_ARRAYS_STATIC_CHECK 1
24
Glenn Kasten153b9fe2013-07-15 11:23:36 -070025#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080026#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <math.h>
28#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/time.h>
31#include <sys/resource.h>
32
jiabin57303cc2018-12-18 15:45:57 -080033#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080034#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/IServiceManager.h>
36#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070037#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070039#include <media/audiohal/DeviceHalInterface.h>
40#include <media/audiohal/DevicesFactoryHalInterface.h>
41#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070042#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070043#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070044#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/String16.h>
46#include <utils/threads.h>
47
Steven Morelandf0c02ce2018-02-23 14:53:55 -080048#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <cutils/properties.h>
50
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070052#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070055#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Andy Hung6770c6f2015-04-07 13:43:36 -070057#include <media/AudioResamplerPublic.h>
58
Mikhail Naganov9fe94012016-10-14 14:57:40 -070059#include <system/audio_effects/effect_visualizer.h>
60#include <system/audio_effects/effect_ns.h>
61#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten9e58b552013-01-18 15:09:48 -080067#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070068#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069#include <media/nbaio/Pipe.h>
70#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080071#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070072#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070073#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080074
rago3bd1c872016-09-26 12:58:14 -070075//#define BUFLOG_NDEBUG 0
76#include <BufLog.h>
77
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080078#include "TypedLogger.h"
79
Mathias Agopian65ab4712010-07-14 17:59:35 -070080// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
John Grossman1c345192012-03-27 14:00:17 -070082// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
Eric Laurentde070132010-07-13 04:45:46 -070094
Mathias Agopian65ab4712010-07-14 17:59:35 -070095namespace android {
96
Glenn Kastenec1d6b52011-12-12 09:04:45 -080097static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
98static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070099static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700100static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101
Glenn Kasten58912562012-04-03 10:45:00 -0700102
John Grossman4ff14ba2012-02-08 16:37:41 -0800103nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800104
Eric Laurent81784c32012-11-19 14:55:58 -0800105uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700106
Eric Laurent813e2a72013-08-31 12:59:48 -0700107// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
108// we define a minimum time during which a global effect is considered enabled.
109static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
110
Eric Laurentfc235202016-12-20 18:48:17 -0800111Mutex gLock;
112wp<AudioFlinger> gAudioFlinger;
113
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700114// Keep a strong reference to media.log service around forever.
115// The service is within our parent process so it can never die in a way that we could observe.
116// These two variables are const after initialization.
117static sp<IBinder> sMediaLogServiceAsBinder;
118static sp<IMediaLogService> sMediaLogService;
119
120static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
121
122static void sMediaLogInit()
123{
124 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
125 if (sMediaLogServiceAsBinder != 0) {
126 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
127 }
128}
129
jiabin57303cc2018-12-18 15:45:57 -0800130// Keep a strong reference to external vibrator service
131static sp<os::IExternalVibratorService> sExternalVibratorService;
132
133static sp<os::IExternalVibratorService> getExternalVibratorService() {
134 if (sExternalVibratorService == 0) {
135 sp <IBinder> binder = defaultServiceManager()->getService(
136 String16("external_vibrator_service"));
137 if (binder != 0) {
138 sExternalVibratorService =
139 interface_cast<os::IExternalVibratorService>(binder);
140 }
141 }
142 return sExternalVibratorService;
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700147std::string formatToString(audio_format_t format) {
148 std::string result;
149 FormatConverter::toString(format, result);
150 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800151}
152
Mathias Agopian65ab4712010-07-14 17:59:35 -0700153// ----------------------------------------------------------------------------
154
155AudioFlinger::AudioFlinger()
156 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800157 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800159 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700160 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800161 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800162 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700163 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800164 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700165 mBtNrecIsOff(false),
166 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700167 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800168 mTotalMemory(0),
169 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700170 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700171 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700172 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700173{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700174 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
175 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
176 // zero ID has a special meaning, so unavailable
177 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
178 }
179
Glenn Kastenae0cff12016-02-24 13:57:49 -0800180 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800181 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800182 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
183 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700184 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800185 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700186
Wei Jia3f273d12015-11-24 09:06:49 -0800187 // reset battery stats.
188 // if the audio service has crashed, battery stats could be left
189 // in bad state, reset the state upon service start.
190 BatteryNotifier::getInstance().noteResetAudio();
191
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700192 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700193 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
194
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800195 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700196}
197
198void AudioFlinger::onFirstRef()
199{
Eric Laurent93575202011-01-18 18:39:02 -0800200 Mutex::Autolock _l(mLock);
201
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800203 char val_str[PROPERTY_VALUE_MAX] = { 0 };
204 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
205 uint32_t int_val;
206 if (1 == sscanf(val_str, "%u", &int_val)) {
207 mStandbyTimeInNsecs = milliseconds(int_val);
208 ALOGI("Using %u mSec as standby time.", int_val);
209 } else {
210 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
211 ALOGI("Using default %u mSec as standby time.",
212 (uint32_t)(mStandbyTimeInNsecs / 1000000));
213 }
214 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215
Eric Laurenta4c5a552012-03-29 10:12:40 -0700216 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800217
218 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219}
220
221AudioFlinger::~AudioFlinger()
222{
223 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700224 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700225 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226 }
227 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700228 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700229 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700230 }
Andy Hungb4946b62019-03-14 11:19:28 -0700231 while (!mMmapThreads.isEmpty()) {
232 const audio_io_handle_t io = mMmapThreads.keyAt(0);
233 if (mMmapThreads.valueAt(0)->isOutput()) {
234 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
235 } else {
236 closeInput_nonvirtual(io); // removes entry from mMmapThreads
237 }
238 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700239
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700242 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700244
245 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700246 if (sMediaLogService != 0) {
247 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
248 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
249 mUnregisteredWriters.pop();
250 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700251 }
252 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253}
254
Eric Laurentfc235202016-12-20 18:48:17 -0800255//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800256__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800257status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
258 const audio_attributes_t *attr,
259 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700260 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800261 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800262 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800263 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700264 sp<MmapStreamInterface>& interface,
265 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800266{
267 sp<AudioFlinger> af;
268 {
269 Mutex::Autolock _l(gLock);
270 af = gAudioFlinger.promote();
271 }
272 status_t ret = NO_INIT;
273 if (af != 0) {
274 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800275 direction, attr, config, client, deviceId,
276 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800277 }
278 return ret;
279}
280
Eric Laurent6acd1d42017-01-04 14:23:29 -0800281status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
282 const audio_attributes_t *attr,
283 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700284 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800285 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800286 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800287 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 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800295 audio_session_t actualSessionId = *sessionId;
296 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
297 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
298 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800299 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700300 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800301 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700302 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800303 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
304 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
305 fullConfig.sample_rate = config->sample_rate;
306 fullConfig.channel_mask = config->channel_mask;
307 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800308 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700309
310 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800311 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200312 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800313 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800314 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
315 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800316 deviceId, &portId, &secondaryOutputs);
317 ALOGW_IF(!secondaryOutputs.empty(),
318 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800319 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700320 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700321 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800322 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800323 client.clientPid,
324 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800325 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800326 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700327 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800328 }
329 if (ret != NO_ERROR) {
330 return ret;
331 }
332
333 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
334 // audio policy manager and we can retrieve it
335 sp<MmapThread> thread = mMmapThreads.valueFor(io);
336 if (thread != 0) {
337 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700338 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700339 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800340 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800341 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700342 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700343 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700344 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800345 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700346 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800347 ret = NO_INIT;
348 }
349
350 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
351
Eric Laurentfc235202016-12-20 18:48:17 -0800352 return ret;
353}
354
jiabin57303cc2018-12-18 15:45:57 -0800355/* static */
356int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
357 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
358 if (evs != 0) {
359 int32_t ret;
360 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
361 if (status.isOk()) {
362 return ret;
363 }
364 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800365 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800366}
367
368/* static */
369void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
370 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
371 if (evs != 0) {
372 evs->onExternalVibrationStop(*externalVibration);
373 }
374}
375
Eric Laurenta4c5a552012-03-29 10:12:40 -0700376static const char * const audio_interfaces[] = {
377 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
378 AUDIO_HARDWARE_MODULE_ID_A2DP,
379 AUDIO_HARDWARE_MODULE_ID_USB,
380};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700381
Phil Burk062e67a2015-02-11 13:40:50 -0800382AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700383 audio_module_handle_t module,
384 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700385{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700386 // if module is 0, the request comes from an old policy manager and we should load
387 // well known modules
388 if (module == 0) {
389 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700390 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700391 loadHwModule_l(audio_interfaces[i]);
392 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700393 // then try to find a module supporting the requested device.
394 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
395 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700396 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
397 uint32_t supportedDevices;
398 if (dev->getSupportedDevices(&supportedDevices) == OK &&
399 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700400 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700401 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700402 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700403 } else {
404 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700405 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
406 if (audioHwDevice != NULL) {
407 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700408 }
409 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700410
Dima Zavin799a70e2011-04-18 16:57:27 -0700411 return NULL;
412}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700413
Glenn Kasten0f11b512014-01-31 16:18:54 -0800414void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415{
416 const size_t SIZE = 256;
417 char buffer[SIZE];
418 String8 result;
419
420 result.append("Clients:\n");
421 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800422 sp<Client> client = mClients.valueAt(i).promote();
423 if (client != 0) {
424 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
425 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 }
427 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700428
Eric Laurentd1b28d42013-09-18 18:47:13 -0700429 result.append("Notification Clients:\n");
430 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
431 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
432 result.append(buffer);
433 }
434
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700435 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800436 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700437 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
438 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800439 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700440 result.append(buffer);
441 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443}
444
445
Glenn Kasten0f11b512014-01-31 16:18:54 -0800446void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447{
448 const size_t SIZE = 256;
449 char buffer[SIZE];
450 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800451 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452
John Grossman4ff14ba2012-02-08 16:37:41 -0800453 snprintf(buffer, SIZE, "Hardware status: %d\n"
454 "Standby Time mSec: %u\n",
455 hardwareStatus,
456 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 result.append(buffer);
458 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459}
460
Glenn Kasten0f11b512014-01-31 16:18:54 -0800461void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462{
463 const size_t SIZE = 256;
464 char buffer[SIZE];
465 String8 result;
466 snprintf(buffer, SIZE, "Permission Denial: "
467 "can't dump AudioFlinger from pid=%d, uid=%d\n",
468 IPCThreadState::self()->getCallingPid(),
469 IPCThreadState::self()->getCallingUid());
470 result.append(buffer);
471 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472}
473
Eric Laurent81784c32012-11-19 14:55:58 -0800474bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700476 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
477 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478}
479
480status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
481{
Glenn Kasten44deb052012-02-05 18:09:08 -0800482 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 dumpPermissionDenial(fd, args);
484 } else {
485 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800486 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 if (!hardwareLocked) {
488 String8 result(kHardwareLockedString);
489 write(fd, result.string(), result.size());
490 } else {
491 mHardwareLock.unlock();
492 }
493
Eric Tan7b651152018-07-13 10:17:19 -0700494 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495
496 // failed to lock - AudioFlinger is probably deadlocked
497 if (!locked) {
498 String8 result(kDeadlockedString);
499 write(fd, result.string(), result.size());
500 }
501
Eric Laurent021cf962014-05-13 10:18:14 -0700502 bool clientLocked = dumpTryLock(mClientLock);
503 if (!clientLocked) {
504 String8 result(kClientLockedString);
505 write(fd, result.string(), result.size());
506 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700507
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700508 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700509 mEffectsFactoryHal->dumpEffects(fd);
510 } else {
511 String8 result(kNoEffectsFactory);
512 write(fd, result.string(), result.size());
513 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700514
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700516 if (clientLocked) {
517 mClientLock.unlock();
518 }
519
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 dumpInternals(fd, args);
521
522 // dump playback threads
523 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
524 mPlaybackThreads.valueAt(i)->dump(fd, args);
525 }
526
527 // dump record threads
528 for (size_t i = 0; i < mRecordThreads.size(); i++) {
529 mRecordThreads.valueAt(i)->dump(fd, args);
530 }
531
Eric Laurent6acd1d42017-01-04 14:23:29 -0800532 // dump mmap threads
533 for (size_t i = 0; i < mMmapThreads.size(); i++) {
534 mMmapThreads.valueAt(i)->dump(fd, args);
535 }
536
Eric Laurentaaa44472014-09-12 17:41:50 -0700537 // dump orphan effect chains
538 if (mOrphanEffectChains.size() != 0) {
539 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
540 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
541 mOrphanEffectChains.valueAt(i)->dump(fd, args);
542 }
543 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700544 // dump all hardware devs
545 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700546 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
547 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700549
Mikhail Naganov201369b2018-05-16 16:52:32 -0700550 mPatchPanel.dump(fd);
551
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700552 // dump external setParameters
553 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
554 dprintf(fd, "\n%s setParameters:\n", name);
555 logger.dump(fd, " " /* prefix */);
556 };
557 dumpLogger(mRejectedSetParameterLog, "Rejected");
558 dumpLogger(mAppSetParameterLog, "App");
559 dumpLogger(mSystemSetParameterLog, "System");
560
Andy Hunga8115dc2018-08-24 15:51:59 -0700561 // dump historical threads in the last 10 seconds
562 const std::string threadLog = mThreadLog.dumpToString(
563 "Historical Thread Log ", 0 /* lines */,
564 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
565 write(fd, threadLog.c_str(), threadLog.size());
566
rago3bd1c872016-09-26 12:58:14 -0700567 BUFLOG_RESET;
568
Glenn Kastend65d73c2012-06-22 17:21:07 -0700569 if (locked) {
570 mLock.unlock();
571 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800572
Andy Hung8946a282018-04-19 20:04:56 -0700573#ifdef TEE_SINK
574 // NBAIO_Tee dump is safe to call outside of AF lock.
575 NBAIO_Tee::dumpAll(fd, "_DUMP");
576#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800577 // append a copy of media.log here by forwarding fd to it, but don't attempt
578 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700579 if (sMediaLogServiceAsBinder != 0) {
580 dprintf(fd, "\nmedia.log:\n");
581 Vector<String16> args;
582 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800583 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700584
585 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700586 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700587 bool unreachableMemory = false;
588 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700589 if (arg == String16("-m")) {
590 dumpMem = true;
591 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700592 unreachableMemory = true;
593 }
594 }
595
Andy Hung07b745e2016-05-23 16:21:07 -0700596 if (dumpMem) {
597 dprintf(fd, "\nDumping memory:\n");
598 std::string s = dumpMemoryAddresses(100 /* limit */);
599 write(fd, s.c_str(), s.size());
600 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700601 if (unreachableMemory) {
602 dprintf(fd, "\nDumping unreachable memory:\n");
603 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700604 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700605 write(fd, s.c_str(), s.size());
606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 }
608 return NO_ERROR;
609}
610
Eric Laurent021cf962014-05-13 10:18:14 -0700611sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800612{
Eric Laurent021cf962014-05-13 10:18:14 -0700613 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800614 // If pid is already in the mClients wp<> map, then use that entry
615 // (for which promote() is always != 0), otherwise create a new entry and Client.
616 sp<Client> client = mClients.valueFor(pid).promote();
617 if (client == 0) {
618 client = new Client(this, pid);
619 mClients.add(pid, client);
620 }
621
622 return client;
623}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
Glenn Kasten9e58b552013-01-18 15:09:48 -0800625sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
626{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700627 // If there is no memory allocated for logs, return a dummy writer that does nothing.
628 // Similarly if we can't contact the media.log service, also return a dummy writer.
629 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800630 return new NBLog::Writer();
631 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700632 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
633 // If allocation fails, consult the vector of previously unregistered writers
634 // and garbage-collect one or more them until an allocation succeeds
635 if (shared == 0) {
636 Mutex::Autolock _l(mUnregisteredWritersLock);
637 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
638 {
639 // Pick the oldest stale writer to garbage-collect
640 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
641 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700642 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700643 // Now the media.log remote reference to IMemory is gone. When our last local
644 // reference to IMemory also drops to zero at end of this block,
645 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
646 }
647 // Re-attempt the allocation
648 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
649 if (shared != 0) {
650 goto success;
651 }
652 }
653 // Even after garbage-collecting all old writers, there is still not enough memory,
654 // so return a dummy writer
655 return new NBLog::Writer();
656 }
657success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700658 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800659 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
660 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700661 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800662 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800663}
664
665void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
666{
Glenn Kasten685ef092013-02-04 08:15:34 -0800667 if (writer == 0) {
668 return;
669 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800670 sp<IMemory> iMemory(writer->getIMemory());
671 if (iMemory == 0) {
672 return;
673 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700674 // Rather than removing the writer immediately, append it to a queue of old writers to
675 // be garbage-collected later. This allows us to continue to view old logs for a while.
676 Mutex::Autolock _l(mUnregisteredWritersLock);
677 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800678}
679
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680// IAudioFlinger interface
681
Eric Laurent21da6472017-11-09 16:29:26 -0800682sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
683 CreateTrackOutput& output,
684 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685{
686 sp<PlaybackThread::Track> track;
687 sp<TrackHandle> trackHandle;
688 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800690 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800691 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800692 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693
Eric Laurent21da6472017-11-09 16:29:26 -0800694 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700695 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800696 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700697 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
698 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700699 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700700
Andy Hung4ef19fa2018-05-15 19:35:29 -0700701 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800702 ALOGW_IF(clientUid != callingUid,
703 "%s uid %d tried to pass itself off as %d",
704 __FUNCTION__, callingUid, clientUid);
705 clientUid = callingUid;
706 updatePid = true;
707 }
708 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700709 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800710 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800711 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700712 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800713 __func__, callingUid, callingPid, clientPid);
714 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700715 }
716
Eric Laurent21da6472017-11-09 16:29:26 -0800717 audio_session_t sessionId = input.sessionId;
718 if (sessionId == AUDIO_SESSION_ALLOCATE) {
719 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800720 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
721 lStatus = BAD_VALUE;
722 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800723 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800724
Eric Laurent21da6472017-11-09 16:29:26 -0800725 output.sessionId = sessionId;
726 output.outputId = AUDIO_IO_HANDLE_NONE;
727 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700728 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200729 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800730 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800731
732 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
733 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
734 goto Exit;
735 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800736 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
737 // but if someone uses binder directly they could bypass that and cause us to crash
738 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000739 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 lStatus = BAD_VALUE;
741 goto Exit;
742 }
743
Glenn Kasten53b5d092014-02-05 10:00:23 -0800744 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800745 if (!audio_is_output_channel(input.config.channel_mask)) {
746 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800747 lStatus = BAD_VALUE;
748 goto Exit;
749 }
750
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700751 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800752 if (!audio_is_valid_format(input.config.format)) {
753 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700754 lStatus = BAD_VALUE;
755 goto Exit;
756 }
757
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 {
759 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800760 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700761 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800762 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 lStatus = BAD_VALUE;
764 goto Exit;
765 }
766
Eric Laurent21da6472017-11-09 16:29:26 -0800767 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768
Glenn Kastene848bd92014-03-13 15:00:32 -0700769 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800770 // check if an effect chain with the same session ID is present on another
771 // output thread and move it here.
772 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
773 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
774 if (mPlaybackThreads.keyAt(i) != output.outputId) {
775 uint32_t sessions = t->hasAudioSession(sessionId);
776 if (sessions & ThreadBase::EFFECT_SESSION) {
777 effectThread = t.get();
778 break;
Eric Laurentde070132010-07-13 04:45:46 -0700779 }
780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 }
Eric Laurent21da6472017-11-09 16:29:26 -0800782 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783
Eric Laurent21da6472017-11-09 16:29:26 -0800784 output.sampleRate = input.config.sample_rate;
785 output.frameCount = input.frameCount;
786 output.notificationFrameCount = input.notificationFrameCount;
787 output.flags = input.flags;
788
Eric Laurent42984412019-05-09 17:57:03 -0700789 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700790 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800791 &output.frameCount, &output.notificationFrameCount,
792 input.notificationsPerBuffer, input.speed,
793 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700794 callingPid, input.clientInfo.clientTid, clientUid,
795 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800796 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700797 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700798
Eric Laurent21da6472017-11-09 16:29:26 -0800799 output.afFrameCount = thread->frameCount();
800 output.afSampleRate = thread->sampleRate();
801 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800802 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800803
Kevin Rocard153f92d2018-12-18 18:33:28 -0800804 if (lStatus == NO_ERROR) {
805 // Connect secondary outputs. Failure on a secondary output must not imped the primary
806 // Any secondary output setup failure will lead to a desync between the AP and AF until
807 // the track is destroyed.
808 TeePatches teePatches;
809 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
810 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
811 if (secondaryThread == NULL) {
812 ALOGE("no playback thread found for secondary output %d", output.outputId);
813 continue;
814 }
815
816 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
817
818 using namespace std::chrono_literals;
819 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
820 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
821 output.sampleRate,
822 inChannelMask,
823 input.config.format,
824 frameCount,
825 NULL /* buffer */,
826 (size_t)0 /* bufferSize */,
827 AUDIO_INPUT_FLAG_DIRECT,
828 0ns /* timeout */);
829 status_t status = patchRecord->initCheck();
830 if (status != NO_ERROR) {
831 ALOGE("Secondary output patchRecord init failed: %d", status);
832 continue;
833 }
Andy Hungae22b482019-05-09 15:38:55 -0700834
835 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
836 // for fast usage: thread has fast mixer, sample rate matches, etc.;
837 // for now, we exclude fast tracks by removing the Fast flag.
838 const audio_output_flags_t outputFlags =
839 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800840 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
841 streamType,
842 output.sampleRate,
843 input.config.channel_mask,
844 input.config.format,
845 frameCount,
846 patchRecord->buffer(),
847 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700848 outputFlags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800849 0ns /* timeout */);
850 status = patchTrack->initCheck();
851 if (status != NO_ERROR) {
852 ALOGE("Secondary output patchTrack init failed: %d", status);
853 continue;
854 }
855 teePatches.push_back({patchRecord, patchTrack});
856 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800857 // In case the downstream patchTrack on the secondaryThread temporarily outlives
858 // our created track, ensure the corresponding patchRecord is still alive.
859 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
860 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800861 }
862 track->setTeePatches(std::move(teePatches));
863 }
864
Eric Laurent39e94f82010-07-28 01:32:47 -0700865 // move effect chain to this output thread if an effect on same session was waiting
866 // for a track to be created
867 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700868 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700869 Mutex::Autolock _dl(thread->mLock);
870 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700871 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
872 effectThreadId = thread->id();
873 effectIds = thread->getEffectIds_l(sessionId);
874 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700875 }
Eric Laurenta011e352012-03-29 15:51:43 -0700876
877 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700878 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800879 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700880 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700881 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700882 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700883 } else {
884 mPendingSyncEvents[i]->cancel();
885 }
Eric Laurenta011e352012-03-29 15:51:43 -0700886 mPendingSyncEvents.removeAt(i);
887 i--;
888 }
889 }
890 }
Glenn Kastene198c362013-08-13 09:13:36 -0700891
Eric Laurent21da6472017-11-09 16:29:26 -0800892 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
Glenn Kastene198c362013-08-13 09:13:36 -0700894
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700895 if (lStatus != NO_ERROR) {
896 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700897 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700898 // Don't hold mClientLock when releasing the reference on the track as the
899 // destructor will acquire it.
900 {
901 Mutex::Autolock _cl(mClientLock);
902 client.clear();
903 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700905 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 }
907
Eric Laurent6c796322019-04-09 14:13:17 -0700908 // effectThreadId is not NONE if an effect chain corresponding to the track session
909 // was found on another thread and must be moved on this thread
910 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
911 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
912 }
913
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700914 // return handle to client
915 trackHandle = new TrackHandle(track);
916
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800918 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700919 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800920 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700921 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 return trackHandle;
923}
924
Glenn Kasten2c073da2016-02-26 09:14:08 -0800925uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926{
927 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800928 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800930 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 return 0;
932 }
933 return thread->sampleRate();
934}
935
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800936audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937{
938 Mutex::Autolock _l(mLock);
939 PlaybackThread *thread = checkPlaybackThread_l(output);
940 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000941 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800942 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943 }
944 return thread->format();
945}
946
Glenn Kasten2c073da2016-02-26 09:14:08 -0800947size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948{
949 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800950 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800952 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 return 0;
954 }
Glenn Kasten58912562012-04-03 10:45:00 -0700955 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
956 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700957 return thread->frameCount();
958}
959
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700960size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
961{
962 Mutex::Autolock _l(mLock);
963 ThreadBase *thread = checkThread_l(ioHandle);
964 if (thread == NULL) {
965 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
966 return 0;
967 }
968 return thread->frameCountHAL();
969}
970
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800971uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972{
973 Mutex::Autolock _l(mLock);
974 PlaybackThread *thread = checkPlaybackThread_l(output);
975 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800976 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977 return 0;
978 }
979 return thread->latency();
980}
981
982status_t AudioFlinger::setMasterVolume(float value)
983{
Eric Laurenta1884f92011-08-23 08:25:03 -0700984 status_t ret = initCheck();
985 if (ret != NO_ERROR) {
986 return ret;
987 }
988
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 // check calling permissions
990 if (!settingsAllowed()) {
991 return PERMISSION_DENIED;
992 }
993
Eric Laurenta4c5a552012-03-29 10:12:40 -0700994 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700995 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700996
John Grossmanee578c02012-07-23 17:05:46 -0700997 // Set master volume in the HALs which support it.
998 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
999 AutoMutex lock(mHardwareLock);
1000 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001001
John Grossmanee578c02012-07-23 17:05:46 -07001002 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1003 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001004 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -08001005 }
John Grossmanee578c02012-07-23 17:05:46 -07001006 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008
John Grossmanee578c02012-07-23 17:05:46 -07001009 // Now set the master volume in each playback thread. Playback threads
1010 // assigned to HALs which do not have master volume support will apply
1011 // master volume during the mix operation. Threads with HALs which do
1012 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001013 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1014 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1015 continue;
1016 }
John Grossmanee578c02012-07-23 17:05:46 -07001017 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001018 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019
1020 return NO_ERROR;
1021}
1022
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001023status_t AudioFlinger::setMasterBalance(float balance)
1024{
1025 status_t ret = initCheck();
1026 if (ret != NO_ERROR) {
1027 return ret;
1028 }
1029
1030 // check calling permissions
1031 if (!settingsAllowed()) {
1032 return PERMISSION_DENIED;
1033 }
1034
1035 // check range
1036 if (isnan(balance) || fabs(balance) > 1.f) {
1037 return BAD_VALUE;
1038 }
1039
1040 Mutex::Autolock _l(mLock);
1041
1042 // short cut.
1043 if (mMasterBalance == balance) return NO_ERROR;
1044
1045 mMasterBalance = balance;
1046
1047 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1048 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1049 continue;
1050 }
1051 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1052 }
1053
1054 return NO_ERROR;
1055}
1056
Glenn Kastenf78aee72012-01-04 11:00:47 -08001057status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058{
Eric Laurenta1884f92011-08-23 08:25:03 -07001059 status_t ret = initCheck();
1060 if (ret != NO_ERROR) {
1061 return ret;
1062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063
1064 // check calling permissions
1065 if (!settingsAllowed()) {
1066 return PERMISSION_DENIED;
1067 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001068 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001069 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 return BAD_VALUE;
1071 }
1072
1073 { // scope for the lock
1074 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001075 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001077 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mHardwareStatus = AUDIO_HW_IDLE;
1079 }
1080
1081 if (NO_ERROR == ret) {
1082 Mutex::Autolock _l(mLock);
1083 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001084 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001085 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 }
1087
1088 return ret;
1089}
1090
1091status_t AudioFlinger::setMicMute(bool state)
1092{
Eric Laurenta1884f92011-08-23 08:25:03 -07001093 status_t ret = initCheck();
1094 if (ret != NO_ERROR) {
1095 return ret;
1096 }
1097
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 // check calling permissions
1099 if (!settingsAllowed()) {
1100 return PERMISSION_DENIED;
1101 }
1102
1103 AutoMutex lock(mHardwareLock);
1104 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001105 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001106 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1107 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001108 if (result != NO_ERROR) {
1109 ret = result;
1110 }
1111 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 mHardwareStatus = AUDIO_HW_IDLE;
1113 return ret;
1114}
1115
1116bool AudioFlinger::getMicMute() const
1117{
Eric Laurenta1884f92011-08-23 08:25:03 -07001118 status_t ret = initCheck();
1119 if (ret != NO_ERROR) {
1120 return false;
1121 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001122 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001123 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001124 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001126 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001127 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1128 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001129 if (result == NO_ERROR) {
1130 mute = mute && state;
1131 }
1132 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001134
1135 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136}
1137
Eric Laurent5ada82e2019-08-29 17:53:54 -07001138void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001139{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001140 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001141
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001142 AutoMutex lock(mLock);
1143 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001144 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001145 }
1146 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001147 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001148 }
1149}
1150
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151status_t AudioFlinger::setMasterMute(bool muted)
1152{
John Grossmand8f178d2012-07-20 14:51:35 -07001153 status_t ret = initCheck();
1154 if (ret != NO_ERROR) {
1155 return ret;
1156 }
1157
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 // check calling permissions
1159 if (!settingsAllowed()) {
1160 return PERMISSION_DENIED;
1161 }
1162
John Grossmanee578c02012-07-23 17:05:46 -07001163 Mutex::Autolock _l(mLock);
1164 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001165
John Grossmanee578c02012-07-23 17:05:46 -07001166 // Set master mute in the HALs which support it.
1167 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1168 AutoMutex lock(mHardwareLock);
1169 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001170
John Grossmanee578c02012-07-23 17:05:46 -07001171 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1172 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001173 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001174 }
John Grossmanee578c02012-07-23 17:05:46 -07001175 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001176 }
1177
John Grossmanee578c02012-07-23 17:05:46 -07001178 // Now set the master mute in each playback thread. Playback threads
1179 // assigned to HALs which do not have master mute support will apply master
1180 // mute during the mix operation. Threads with HALs which do support master
1181 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001182 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1183 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1184 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186
1187 return NO_ERROR;
1188}
1189
1190float AudioFlinger::masterVolume() const
1191{
Glenn Kasten98067102011-12-13 11:47:54 -08001192 Mutex::Autolock _l(mLock);
1193 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194}
1195
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001196status_t AudioFlinger::getMasterBalance(float *balance) const
1197{
1198 Mutex::Autolock _l(mLock);
1199 *balance = getMasterBalance_l();
1200 return NO_ERROR; // if called through binder, may return a transactional error
1201}
1202
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203bool AudioFlinger::masterMute() const
1204{
Glenn Kasten98067102011-12-13 11:47:54 -08001205 Mutex::Autolock _l(mLock);
1206 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207}
1208
John Grossman4ff14ba2012-02-08 16:37:41 -08001209float AudioFlinger::masterVolume_l() const
1210{
John Grossman4ff14ba2012-02-08 16:37:41 -08001211 return mMasterVolume;
1212}
1213
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001214float AudioFlinger::getMasterBalance_l() const
1215{
1216 return mMasterBalance;
1217}
1218
John Grossmand8f178d2012-07-20 14:51:35 -07001219bool AudioFlinger::masterMute_l() const
1220{
John Grossmanee578c02012-07-23 17:05:46 -07001221 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001222}
1223
Eric Laurent223fd5c2014-11-11 13:43:36 -08001224status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1225{
1226 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001227 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001228 return BAD_VALUE;
1229 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001230 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1231 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1232 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001233 return PERMISSION_DENIED;
1234 }
1235
1236 return NO_ERROR;
1237}
1238
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001239status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1240 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241{
1242 // check calling permissions
1243 if (!settingsAllowed()) {
1244 return PERMISSION_DENIED;
1245 }
1246
Eric Laurent223fd5c2014-11-11 13:43:36 -08001247 status_t status = checkStreamType(stream);
1248 if (status != NO_ERROR) {
1249 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250 }
Eric Laurent98e38192018-02-15 18:31:53 -08001251 if (output == AUDIO_IO_HANDLE_NONE) {
1252 return BAD_VALUE;
1253 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001254 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1255 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256
1257 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001258 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1259 if (volumeInterface == NULL) {
1260 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001261 }
Eric Laurent98e38192018-02-15 18:31:53 -08001262 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263
1264 return NO_ERROR;
1265}
1266
Glenn Kastenfff6d712012-01-12 16:38:12 -08001267status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268{
1269 // check calling permissions
1270 if (!settingsAllowed()) {
1271 return PERMISSION_DENIED;
1272 }
1273
Eric Laurent223fd5c2014-11-11 13:43:36 -08001274 status_t status = checkStreamType(stream);
1275 if (status != NO_ERROR) {
1276 return status;
1277 }
1278 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1279
1280 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001281 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282 return BAD_VALUE;
1283 }
1284
Eric Laurent93575202011-01-18 18:39:02 -08001285 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001287 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1288 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1289 volumeInterfaces[i]->setStreamMute(stream, muted);
1290 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291
1292 return NO_ERROR;
1293}
1294
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001295float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001297 status_t status = checkStreamType(stream);
1298 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299 return 0.0f;
1300 }
Eric Laurent98e38192018-02-15 18:31:53 -08001301 if (output == AUDIO_IO_HANDLE_NONE) {
1302 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303 }
1304
Eric Laurent98e38192018-02-15 18:31:53 -08001305 AutoMutex lock(mLock);
1306 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1307 if (volumeInterface == NULL) {
1308 return 0.0f;
1309 }
1310
1311 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001312}
1313
Glenn Kastenfff6d712012-01-12 16:38:12 -08001314bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001316 status_t status = checkStreamType(stream);
1317 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318 return true;
1319 }
1320
Glenn Kasten6637baa2012-01-09 09:40:36 -08001321 AutoMutex lock(mLock);
1322 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001323}
1324
Eric Laurent054d9d32015-04-24 08:48:48 -07001325
1326void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1327{
1328 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1329 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1330 }
1331}
1332
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001333// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1334void AudioFlinger::forwardParametersToDownstreamPatches_l(
1335 audio_io_handle_t upStream, const String8& keyValuePairs,
1336 std::function<bool(const sp<PlaybackThread>&)> useThread)
1337{
1338 std::vector<PatchPanel::SoftwarePatch> swPatches;
1339 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1340 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1341 __func__, swPatches.size(), upStream);
1342 for (const auto& swPatch : swPatches) {
1343 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1344 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1345 downStream->setParameters(keyValuePairs);
1346 }
1347 }
1348}
1349
Eric Laurentf1047e82018-04-16 19:18:20 -07001350// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1351// Some keys are used for audio routing and audio path configuration and should be reserved for use
1352// by audio policy and audio flinger for functional, privacy and security reasons.
1353void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1354{
1355 static const String8 kReservedParameters[] = {
1356 String8(AudioParameter::keyRouting),
1357 String8(AudioParameter::keySamplingRate),
1358 String8(AudioParameter::keyFormat),
1359 String8(AudioParameter::keyChannels),
1360 String8(AudioParameter::keyFrameCount),
1361 String8(AudioParameter::keyInputSource),
1362 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001363 String8(AudioParameter::keyDeviceConnect),
1364 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001365 String8(AudioParameter::keyStreamSupportedFormats),
1366 String8(AudioParameter::keyStreamSupportedChannels),
1367 String8(AudioParameter::keyStreamSupportedSamplingRates),
1368 };
1369
Andy Hung4ef19fa2018-05-15 19:35:29 -07001370 if (isAudioServerUid(callingUid)) {
1371 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001372 }
1373
1374 AudioParameter param = AudioParameter(keyValuePairs);
1375 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001376 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001377 for (auto& key : kReservedParameters) {
1378 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001379 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001380 param.remove(key);
1381 }
1382 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001383 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1384 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001385 keyValuePairs = param.toString();
1386}
1387
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001388void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1389 size_t rejectedKVPSize, const String8& rejectedKVPs,
1390 uid_t callingUid) {
1391 auto prefix = String8::format("UID %5d", callingUid);
1392 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1393 if (rejectedKVPSize != 0) {
1394 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1395 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1396 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1397 } else {
1398 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1399 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1400 }
1401}
1402
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001403status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001404{
Eric Laurentf1047e82018-04-16 19:18:20 -07001405 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1406 ioHandle, keyValuePairs.string(),
1407 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001408
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409 // check calling permissions
1410 if (!settingsAllowed()) {
1411 return PERMISSION_DENIED;
1412 }
1413
Eric Laurentf1047e82018-04-16 19:18:20 -07001414 String8 filteredKeyValuePairs = keyValuePairs;
1415 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1416
1417 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1418
Glenn Kasten142f5192014-03-25 17:44:59 -07001419 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1420 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001421 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001422 // result will remain NO_INIT if no audio device is present
1423 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001424 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001425 AutoMutex lock(mHardwareLock);
1426 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1427 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001428 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001429 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001430 // return success if at least one audio device accepts the parameters as not all
1431 // HALs are requested to support all parameters. If no audio device supports the
1432 // requested parameters, the last error is reported.
1433 if (final_result != NO_ERROR) {
1434 final_result = result;
1435 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001436 }
1437 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001438 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001439 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001440 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001441 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001442 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1443 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001444 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001445 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001446 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001447 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001448 }
1449 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001450 String8 screenState;
1451 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001452 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001453 if (isOff != (AudioFlinger::mScreenState & 1)) {
1454 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001455 }
1456 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001457 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458 }
1459
1460 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1461 // and the thread is exited once the lock is released
1462 sp<ThreadBase> thread;
1463 {
1464 Mutex::Autolock _l(mLock);
1465 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001466 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001468 if (thread == 0) {
1469 thread = checkMmapThread_l(ioHandle);
1470 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001471 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001472 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001473 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001474 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001475 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1476 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001477 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001478 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 }
1480 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001481 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001482 status_t result = thread->setParameters(filteredKeyValuePairs);
1483 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1484 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 }
1486 return BAD_VALUE;
1487}
1488
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001489String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001491 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1492 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493
Eric Laurenta4c5a552012-03-29 10:12:40 -07001494 Mutex::Autolock _l(mLock);
1495
Glenn Kasten142f5192014-03-25 17:44:59 -07001496 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001497 String8 out_s8;
1498
Dima Zavin799a70e2011-04-18 16:57:27 -07001499 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001500 String8 s;
1501 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001502 {
1503 AutoMutex lock(mHardwareLock);
1504 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001505 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1506 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001507 mHardwareStatus = AUDIO_HW_IDLE;
1508 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001509 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001510 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001511 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 }
1513
Eric Laurent6acd1d42017-01-04 14:23:29 -08001514 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1515 if (thread == NULL) {
1516 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1517 if (thread == NULL) {
1518 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1519 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001520 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001521 }
1522 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001524 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525}
1526
Glenn Kastendd8104c2012-07-02 12:42:44 -07001527size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1528 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529{
Eric Laurenta1884f92011-08-23 08:25:03 -07001530 status_t ret = initCheck();
1531 if (ret != NO_ERROR) {
1532 return 0;
1533 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001534 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001535 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001536 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001537 return 0;
1538 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001539
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001540 AutoMutex lock(mHardwareLock);
1541 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001542 audio_config_t config, proposed;
1543 memset(&proposed, 0, sizeof(proposed));
1544 proposed.sample_rate = sampleRate;
1545 proposed.channel_mask = channelMask;
1546 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001547
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001548 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001549 size_t frames;
1550 for (;;) {
1551 // Note: config is currently a const parameter for get_input_buffer_size()
1552 // but we use a copy from proposed in case config changes from the call.
1553 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001554 status_t result = dev->getInputBufferSize(&config, &frames);
1555 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001556 break; // hal success, config is the result
1557 }
1558 // change one parameter of the configuration each iteration to a more "common" value
1559 // to see if the device will support it.
1560 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1561 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1562 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1563 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1564 } else {
1565 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1566 "format %#x, channelMask 0x%X",
1567 sampleRate, format, channelMask);
1568 break; // retries failed, break out of loop with frames == 0.
1569 }
1570 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001571 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001572 if (frames > 0 && config.sample_rate != sampleRate) {
1573 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1574 }
1575 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576}
1577
Glenn Kasten5f972c02014-01-13 09:59:31 -08001578uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 Mutex::Autolock _l(mLock);
1581
1582 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1583 if (recordThread != NULL) {
1584 return recordThread->getInputFramesLost();
1585 }
1586 return 0;
1587}
1588
1589status_t AudioFlinger::setVoiceVolume(float value)
1590{
Eric Laurenta1884f92011-08-23 08:25:03 -07001591 status_t ret = initCheck();
1592 if (ret != NO_ERROR) {
1593 return ret;
1594 }
1595
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 // check calling permissions
1597 if (!settingsAllowed()) {
1598 return PERMISSION_DENIED;
1599 }
1600
1601 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001602 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001603 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001604 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 mHardwareStatus = AUDIO_HW_IDLE;
1606
1607 return ret;
1608}
1609
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001610status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001611 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613 Mutex::Autolock _l(mLock);
1614
1615 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1616 if (playbackThread != NULL) {
1617 return playbackThread->getRenderPosition(halFrames, dspFrames);
1618 }
1619
1620 return BAD_VALUE;
1621}
1622
1623void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1624{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001626 if (client == 0) {
1627 return;
1628 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001629 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001630 {
1631 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001632 if (mNotificationClients.indexOfKey(pid) < 0) {
1633 sp<NotificationClient> notificationClient = new NotificationClient(this,
1634 client,
1635 pid);
1636 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637
Eric Laurent021cf962014-05-13 10:18:14 -07001638 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639
Marco Nelissen06b46062014-11-14 07:58:25 -08001640 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001641 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001642 }
1643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644
Eric Laurent021cf962014-05-13 10:18:14 -07001645 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001646 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001647 // the config change is always sent from playback or record threads to avoid deadlock
1648 // with AudioSystem::gLock
1649 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001650 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001651 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001653 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001654 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 }
1656}
1657
1658void AudioFlinger::removeNotificationClient(pid_t pid)
1659{
Eric Laurent6c796322019-04-09 14:13:17 -07001660 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001661 {
Eric Laurent6c796322019-04-09 14:13:17 -07001662 Mutex::Autolock _l(mLock);
1663 {
1664 Mutex::Autolock _cl(mClientLock);
1665 mNotificationClients.removeItem(pid);
1666 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001667
Eric Laurent6c796322019-04-09 14:13:17 -07001668 ALOGV("%d died, releasing its sessions", pid);
1669 size_t num = mAudioSessionRefs.size();
1670 bool removed = false;
1671 for (size_t i = 0; i < num; ) {
1672 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1673 ALOGV(" pid %d @ %zu", ref->mPid, i);
1674 if (ref->mPid == pid) {
1675 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1676 mAudioSessionRefs.removeAt(i);
1677 delete ref;
1678 removed = true;
1679 num--;
1680 } else {
1681 i++;
1682 }
1683 }
1684 if (removed) {
1685 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001686 }
1687 }
Eric Laurent6c796322019-04-09 14:13:17 -07001688 for (auto& effect : removedEffects) {
1689 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001690 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691}
1692
Eric Laurent73e26b62015-04-27 16:55:58 -07001693void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001694 const sp<AudioIoDescriptor>& ioDesc,
1695 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696{
Eric Laurent021cf962014-05-13 10:18:14 -07001697 Mutex::Autolock _l(mClientLock);
1698 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001700 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1701 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1702 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 }
1704}
1705
Eric Laurent021cf962014-05-13 10:18:14 -07001706// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707void AudioFlinger::removeClient_l(pid_t pid)
1708{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001709 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001710 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 mClients.removeItem(pid);
1712}
1713
Eric Laurent717e1282012-06-29 16:36:52 -07001714// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001715sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1716 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001717{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001718 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001719
1720 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001721 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001722 ALOG_ASSERT(thread == 0);
1723 thread = mPlaybackThreads.valueAt(i);
1724 }
1725 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001726 if (thread != nullptr) {
1727 return thread;
1728 }
1729 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1730 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1731 ALOG_ASSERT(thread == 0);
1732 thread = mRecordThreads.valueAt(i);
1733 }
1734 }
1735 if (thread != nullptr) {
1736 return thread;
1737 }
1738 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1739 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1740 ALOG_ASSERT(thread == 0);
1741 thread = mMmapThreads.valueAt(i);
1742 }
1743 }
Eric Laurent717e1282012-06-29 16:36:52 -07001744 return thread;
1745}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748
1749// ----------------------------------------------------------------------------
1750
1751AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1752 : RefBase(),
1753 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001754 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755{
Andy Hung6f248bb2018-01-23 14:04:37 -08001756 mMemoryDealer = new MemoryDealer(
1757 audioFlinger->getClientSharedHeapSize(),
1758 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759}
1760
Eric Laurent021cf962014-05-13 10:18:14 -07001761// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762AudioFlinger::Client::~Client()
1763{
1764 mAudioFlinger->removeClient_l(mPid);
1765}
1766
Glenn Kasten435dbe62012-01-30 10:15:48 -08001767sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768{
1769 return mMemoryDealer;
1770}
1771
1772// ----------------------------------------------------------------------------
1773
1774AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1775 const sp<IAudioFlingerClient>& client,
1776 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001777 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778{
1779}
1780
1781AudioFlinger::NotificationClient::~NotificationClient()
1782{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783}
1784
Glenn Kasten0f11b512014-01-31 16:18:54 -08001785void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786{
1787 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001788 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789}
1790
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001791// ----------------------------------------------------------------------------
1792AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1793 : mPendingRequests(false) {}
1794
1795
1796void AudioFlinger::MediaLogNotifier::requestMerge() {
1797 AutoMutex _l(mMutex);
1798 mPendingRequests = true;
1799 mCond.signal();
1800}
1801
1802bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001803 // Should already have been checked, but just in case
1804 if (sMediaLogService == 0) {
1805 return false;
1806 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001807 // Wait until there are pending requests
1808 {
1809 AutoMutex _l(mMutex);
1810 mPendingRequests = false; // to ignore past requests
1811 while (!mPendingRequests) {
1812 mCond.wait(mMutex);
1813 // TODO may also need an exitPending check
1814 }
1815 mPendingRequests = false;
1816 }
1817 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001818 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001819 usleep(kPostTriggerSleepPeriod);
1820 return true;
1821}
1822
1823void AudioFlinger::requestLogMerge() {
1824 mMediaLogNotifier->requestMerge();
1825}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826
1827// ----------------------------------------------------------------------------
1828
Eric Laurentf14db3c2017-12-08 14:20:36 -08001829sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1830 CreateRecordOutput& output,
1831 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832{
1833 sp<RecordThread::RecordTrack> recordTrack;
1834 sp<RecordHandle> recordHandle;
1835 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001837 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001838 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839
Eric Laurentf14db3c2017-12-08 14:20:36 -08001840 output.cblk.clear();
1841 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001842 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001843
Eric Laurentf14db3c2017-12-08 14:20:36 -08001844 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001845 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001846 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001847 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001848 ALOGW_IF(clientUid != callingUid,
1849 "%s uid %d tried to pass itself off as %d",
1850 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001851 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001852 updatePid = true;
1853 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001854 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001855 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001856 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001857 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001858 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001859 __func__, callingUid, callingPid, clientPid);
1860 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001861 }
1862
Andy Hung6770c6f2015-04-07 13:43:36 -07001863 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001864 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1865 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001866 lStatus = BAD_VALUE;
1867 goto Exit;
1868 }
1869
Glenn Kasten53b5d092014-02-05 10:00:23 -08001870 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001871 if (!audio_is_input_channel(input.config.channel_mask)) {
1872 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001873 lStatus = BAD_VALUE;
1874 goto Exit;
1875 }
1876
Eric Laurentf14db3c2017-12-08 14:20:36 -08001877 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1878 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1879 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1880 lStatus = BAD_VALUE;
1881 goto Exit;
1882 }
1883
1884 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001885 output.selectedDeviceId = input.selectedDeviceId;
1886 output.flags = input.flags;
1887
1888 client = registerPid(clientPid);
1889
1890 // Not a conventional loop, but a retry loop for at most two iterations total.
1891 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1892 // Exits loop via break on no error of got exit on error
1893 // The sp<> references will be dropped when re-entering scope.
1894 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1895 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001896 // release previously opened input if retrying.
1897 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1898 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001899 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001900 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001901 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001902 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001903 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001904 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001905 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001906 sessionId,
1907 // FIXME compare to AudioTrack
1908 clientPid,
1909 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001910 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001911 &input.config,
1912 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07001913 if (lStatus != NO_ERROR) {
1914 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
1915 goto Exit;
1916 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001917
Glenn Kasten05997e22014-03-13 15:08:33 -07001918 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001920 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 if (thread == NULL) {
jiabinc1de2df2019-05-07 14:26:40 -07001922 ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 lStatus = BAD_VALUE;
1924 goto Exit;
1925 }
1926
Eric Laurentf14db3c2017-12-08 14:20:36 -08001927 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928
Eric Laurentf14db3c2017-12-08 14:20:36 -08001929 output.sampleRate = input.config.sample_rate;
1930 output.frameCount = input.frameCount;
1931 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001932
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001933 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001934 input.config.format, input.config.channel_mask,
1935 &output.frameCount, sessionId,
1936 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001937 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001938 input.clientInfo.clientTid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07001939 &lStatus, portId,
1940 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001941 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001942
Eric Laurentf14db3c2017-12-08 14:20:36 -08001943 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1944 // audio policy manager without FAST constraint
1945 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001946 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001947 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001948
1949 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001950 goto Exit;
1951 }
1952
1953 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1954 // session and move it to this thread.
1955 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1956 if (chain != 0) {
1957 Mutex::Autolock _l(thread->mLock);
1958 thread->addEffectChain_l(chain);
1959 }
1960 break;
1961 }
1962 // End of retry loop.
1963 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 }
Glenn Kastene198c362013-08-13 09:13:36 -07001965
Eric Laurentf14db3c2017-12-08 14:20:36 -08001966 output.cblk = recordTrack->getCblk();
1967 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001968 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001969
1970 // return handle to client
1971 recordHandle = new RecordHandle(recordTrack);
1972
1973Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001974 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001975 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001976 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001977 // Don't hold mClientLock when releasing the reference on the track as the
1978 // destructor will acquire it.
1979 {
1980 Mutex::Autolock _cl(mClientLock);
1981 client.clear();
1982 }
Eric Laurent896c9672017-12-08 14:08:45 -08001983 recordTrack.clear();
1984 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001985 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987 }
1988
Glenn Kasten9156ef32013-08-06 15:39:08 -07001989 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 return recordHandle;
1991}
1992
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001993
1994
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995// ----------------------------------------------------------------------------
1996
Eric Laurenta4c5a552012-03-29 10:12:40 -07001997audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1998{
Eric Laurent44622db2014-08-01 19:00:33 -07001999 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002000 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002001 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002002 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002003 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002004 }
2005 Mutex::Autolock _l(mLock);
2006 return loadHwModule_l(name);
2007}
2008
2009// loadHwModule_l() must be called with AudioFlinger::mLock held
2010audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2011{
2012 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2013 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2014 ALOGW("loadHwModule() module %s already loaded", name);
2015 return mAudioHwDevs.keyAt(i);
2016 }
2017 }
2018
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002019 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002020
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002021 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002022 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002023 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002024 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002025 }
2026
2027 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002028 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002029 mHardwareStatus = AUDIO_HW_IDLE;
2030 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002031 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002032 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002033 }
2034
John Grossmanee578c02012-07-23 17:05:46 -07002035 // Check and cache this HAL's level of support for master mute and master
2036 // volume. If this is the first HAL opened, and it supports the get
2037 // methods, use the initial values provided by the HAL as the current
2038 // master mute and volume settings.
2039
2040 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2041 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002042 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002043
2044 if (0 == mAudioHwDevs.size()) {
2045 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002046 float mv;
2047 if (OK == dev->getMasterVolume(&mv)) {
2048 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002049 }
2050
2051 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002052 bool mm;
2053 if (OK == dev->getMasterMute(&mm)) {
2054 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002055 }
2056 }
2057
Eric Laurenta4c5a552012-03-29 10:12:40 -07002058 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002059 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002060 flags = static_cast<AudioHwDevice::Flags>(flags |
2061 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2062 }
2063
2064 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002065 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002066 flags = static_cast<AudioHwDevice::Flags>(flags |
2067 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2068 }
2069
Eric Laurenta4c5a552012-03-29 10:12:40 -07002070 mHardwareStatus = AUDIO_HW_IDLE;
2071 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002072 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002073 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2074 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2075 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002076
Glenn Kastena13cde92016-03-28 15:26:02 -07002077 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002078 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002079
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002080 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002081
2082 return handle;
2083
2084}
2085
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002086// ----------------------------------------------------------------------------
2087
Glenn Kasten3b16c762012-11-14 08:44:39 -08002088uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002089{
2090 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002091 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002092 return thread != NULL ? thread->sampleRate() : 0;
2093}
2094
Glenn Kastene33054e2012-11-14 12:54:39 -08002095size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002096{
2097 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002098 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002099 return thread != NULL ? thread->frameCountHAL() : 0;
2100}
2101
2102// ----------------------------------------------------------------------------
2103
Andy Hung6f248bb2018-01-23 14:04:37 -08002104status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002105{
2106 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002107 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002108 return PERMISSION_DENIED;
2109 }
2110 Mutex::Autolock _l(mLock);
2111 if (mIsDeviceTypeKnown) {
2112 return INVALID_OPERATION;
2113 }
2114 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002115 mTotalMemory = totalMemory;
2116 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2117 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2118 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2119 // though actual setting is determined through device configuration.
2120 constexpr int64_t GB = 1024 * 1024 * 1024;
2121 mClientSharedHeapSize =
2122 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2123 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2124 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2125 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2126 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002127 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002128
2129 // TODO: Cache the client shared heap size in a persistent property.
2130 // It's possible that a native process or Java service or app accesses audioserver
2131 // after it is registered by system server, but before AudioService updates
2132 // the memory info. This would occur immediately after boot or an audioserver
2133 // crash and restore. Before update from AudioService, the client would get the
2134 // minimum heap size.
2135
2136 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2137 (isLowRamDevice ? "true" : "false"),
2138 (long long)mTotalMemory,
2139 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002140 return NO_ERROR;
2141}
2142
Andy Hung6f248bb2018-01-23 14:04:37 -08002143size_t AudioFlinger::getClientSharedHeapSize() const
2144{
2145 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2146 if (heapSizeInBytes != 0) { // read-only property overrides all.
2147 return heapSizeInBytes;
2148 }
2149 return mClientSharedHeapSize;
2150}
2151
Mikhail Naganovdea53042018-04-26 13:10:21 -07002152status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2153{
2154 ALOGV(__func__);
2155
2156 audio_module_handle_t module;
2157 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2158 module = config->ext.device.hw_module;
2159 } else {
2160 module = config->ext.mix.hw_module;
2161 }
2162
2163 Mutex::Autolock _l(mLock);
2164 ssize_t index = mAudioHwDevs.indexOfKey(module);
2165 if (index < 0) {
2166 ALOGW("%s() bad hw module %d", __func__, module);
2167 return BAD_VALUE;
2168 }
2169
2170 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2171 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2172}
2173
Eric Laurent93c3d412014-08-01 14:48:35 -07002174audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2175{
2176 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002177
2178 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2179 if (index >= 0) {
2180 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2181 mHwAvSyncIds.valueAt(index), sessionId);
2182 return mHwAvSyncIds.valueAt(index);
2183 }
2184
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002185 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002186 if (dev == NULL) {
2187 return AUDIO_HW_SYNC_INVALID;
2188 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002189 String8 reply;
2190 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002191 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002192 param = AudioParameter(reply);
2193 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002194
2195 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002196 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002197 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2198 return AUDIO_HW_SYNC_INVALID;
2199 }
2200
2201 // allow only one session for a given HW A/V sync ID.
2202 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2203 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2204 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2205 value, mHwAvSyncIds.keyAt(i));
2206 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002207 break;
2208 }
2209 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002210
2211 mHwAvSyncIds.add(sessionId, value);
2212
2213 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2214 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2215 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002216 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002217 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002218 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002219 String8 keyValuePairs = param.toString();
2220 thread->setParameters(keyValuePairs);
2221 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2222 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002223 break;
2224 }
2225 }
2226
2227 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2228 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002229}
2230
Eric Laurent72e3f392015-05-20 14:43:50 -07002231status_t AudioFlinger::systemReady()
2232{
2233 Mutex::Autolock _l(mLock);
2234 ALOGI("%s", __FUNCTION__);
2235 if (mSystemReady) {
2236 ALOGW("%s called twice", __FUNCTION__);
2237 return NO_ERROR;
2238 }
2239 mSystemReady = true;
2240 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2241 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2242 thread->systemReady();
2243 }
2244 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2245 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2246 thread->systemReady();
2247 }
2248 return NO_ERROR;
2249}
2250
jiabin46a76fa2018-01-05 10:18:21 -08002251status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2252{
jiabin9ff780e2018-03-19 18:19:52 -07002253 AutoMutex lock(mHardwareLock);
2254 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2255 status_t status = dev->getMicrophones(microphones);
2256 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002257}
2258
Eric Laurentfa90e842014-10-17 18:12:31 -07002259// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2260void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2261{
2262 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2263 if (index >= 0) {
2264 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2265 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2266 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002267 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002268 String8 keyValuePairs = param.toString();
2269 thread->setParameters(keyValuePairs);
2270 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2271 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002272 }
2273}
2274
2275
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002276// ----------------------------------------------------------------------------
2277
Eric Laurent83b88082014-06-20 18:31:16 -07002278
Eric Laurent6acd1d42017-01-04 14:23:29 -08002279sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002280 audio_io_handle_t *output,
2281 audio_config_t *config,
2282 audio_devices_t devices,
2283 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002284 audio_output_flags_t flags)
2285{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002286 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002287 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002288 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002289 }
2290
Eric Laurentcf2c0212014-07-25 16:20:43 -07002291 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002292 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2293 } else {
2294 // Audio Policy does not currently request a specific output handle.
2295 // If this is ever needed, see openInput_l() for example code.
2296 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2297 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002298 }
Eric Laurent83b88082014-06-20 18:31:16 -07002299
2300 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2301
Eric Laurent83b88082014-06-20 18:31:16 -07002302 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002303 // This if statement allows overriding the audio policy settings
2304 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2305 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2306 // Check only for Normal Mixing mode
2307 if (kEnableExtendedPrecision) {
2308 // Specify format (uncomment one below to choose)
2309 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2310 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2311 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2312 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002313 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002314 }
2315 if (kEnableExtendedChannels) {
2316 // Specify channel mask (uncomment one below to choose)
2317 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2318 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2319 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2320 }
Eric Laurent83b88082014-06-20 18:31:16 -07002321 }
2322
Phil Burk062e67a2015-02-11 13:40:50 -08002323 AudioStreamOut *outputStream = NULL;
2324 status_t status = outHwDev->openOutputStream(
2325 &outputStream,
2326 *output,
2327 devices,
2328 flags,
2329 config,
2330 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002331
2332 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002333
Phil Burk062e67a2015-02-11 13:40:50 -08002334 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002335 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2336 sp<MmapPlaybackThread> thread =
2337 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2338 devices, AUDIO_DEVICE_NONE, mSystemReady);
2339 mMmapThreads.add(*output, thread);
2340 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2341 *output, thread.get());
2342 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002343 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002344 sp<PlaybackThread> thread;
2345 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2346 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2347 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2348 *output, thread.get());
2349 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2350 || !isValidPcmSinkFormat(config->format)
2351 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2352 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2353 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2354 *output, thread.get());
2355 } else {
2356 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2357 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2358 *output, thread.get());
2359 }
2360 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002361 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002362 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002363 }
Eric Laurent83b88082014-06-20 18:31:16 -07002364 }
2365
2366 return 0;
2367}
2368
Eric Laurentcf2c0212014-07-25 16:20:43 -07002369status_t AudioFlinger::openOutput(audio_module_handle_t module,
2370 audio_io_handle_t *output,
2371 audio_config_t *config,
2372 audio_devices_t *devices,
2373 const String8& address,
2374 uint32_t *latencyMs,
2375 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002377 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2378 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002379 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002380 (devices != NULL) ? *devices : 0,
2381 config->sample_rate,
2382 config->format,
2383 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002384 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002386 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002387 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002389
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 Mutex::Autolock _l(mLock);
2391
Eric Laurent6acd1d42017-01-04 14:23:29 -08002392 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002393 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002394 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2395 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2396 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397
Eric Laurent6acd1d42017-01-04 14:23:29 -08002398 // notify client processes of the new output creation
2399 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002400
Eric Laurent6acd1d42017-01-04 14:23:29 -08002401 // the first primary output opened designates the primary hw device
2402 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002403 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002404 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002405
Eric Laurent6acd1d42017-01-04 14:23:29 -08002406 AutoMutex lock(mHardwareLock);
2407 mHardwareStatus = AUDIO_HW_SET_MODE;
2408 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2409 mHardwareStatus = AUDIO_HW_IDLE;
2410 }
2411 } else {
2412 MmapThread *mmapThread = (MmapThread *)thread.get();
2413 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002414 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002415 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416 }
2417
Eric Laurentcf2c0212014-07-25 16:20:43 -07002418 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419}
2420
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002421audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2422 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423{
2424 Mutex::Autolock _l(mLock);
2425 MixerThread *thread1 = checkMixerThread_l(output1);
2426 MixerThread *thread2 = checkMixerThread_l(output2);
2427
2428 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002429 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2430 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002431 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433
Glenn Kasteneeecb982016-02-26 10:44:04 -08002434 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002435 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 thread->addOutputTrack(thread2);
2437 mPlaybackThreads.add(id, thread);
2438 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002439 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 return id;
2441}
2442
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002443status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444{
Glenn Kastend96c5722012-04-25 13:44:49 -07002445 return closeOutput_nonvirtual(output);
2446}
2447
2448status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2449{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 // keep strong reference on the playback thread so that
2451 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002452 sp<PlaybackThread> playbackThread;
2453 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 {
2455 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002456 playbackThread = checkPlaybackThread_l(output);
2457 if (playbackThread != NULL) {
2458 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459
Andy Hungdc099c22018-09-18 13:46:39 -07002460 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002461
Eric Laurent6acd1d42017-01-04 14:23:29 -08002462 if (playbackThread->type() == ThreadBase::MIXER) {
2463 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2464 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2465 DuplicatingThread *dupThread =
2466 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2467 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2468 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002469 }
2470 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002471
2472
Eric Laurent6acd1d42017-01-04 14:23:29 -08002473 mPlaybackThreads.removeItem(output);
2474 // save all effects to the default thread
2475 if (mPlaybackThreads.size()) {
2476 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2477 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002478 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002479 Mutex::Autolock _dl(dstThread->mLock);
2480 Mutex::Autolock _sl(playbackThread->mLock);
2481 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2482 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002483 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002484 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 }
2487 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002488 } else {
2489 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2490 if (mmapThread == 0) {
2491 return BAD_VALUE;
2492 }
Andy Hungdc099c22018-09-18 13:46:39 -07002493 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002494 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002495 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002497 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2498 ioDesc->mIoHandle = output;
2499 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002500 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002502 // The thread entity (active unit of execution) is no longer running here,
2503 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504
Eric Laurent6acd1d42017-01-04 14:23:29 -08002505 if (playbackThread != 0) {
2506 playbackThread->exit();
2507 if (!playbackThread->isDuplicating()) {
2508 closeOutputFinish(playbackThread);
2509 }
2510 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002511 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002512 mmapThread->exit();
2513 AudioStreamOut *out = mmapThread->clearOutput();
2514 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2515 // from now on thread->mOutput is NULL
2516 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 }
2518 return NO_ERROR;
2519}
2520
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002521void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002522{
2523 AudioStreamOut *out = thread->clearOutput();
2524 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2525 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002526 delete out;
2527}
2528
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002529void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002530{
2531 mPlaybackThreads.removeItem(thread->mId);
2532 thread->exit();
2533 closeOutputFinish(thread);
2534}
2535
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002536status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537{
2538 Mutex::Autolock _l(mLock);
2539 PlaybackThread *thread = checkPlaybackThread_l(output);
2540
2541 if (thread == NULL) {
2542 return BAD_VALUE;
2543 }
2544
Steve Block3856b092011-10-20 11:56:00 +01002545 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 thread->suspend();
2547
2548 return NO_ERROR;
2549}
2550
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002551status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552{
2553 Mutex::Autolock _l(mLock);
2554 PlaybackThread *thread = checkPlaybackThread_l(output);
2555
2556 if (thread == NULL) {
2557 return BAD_VALUE;
2558 }
2559
Steve Block3856b092011-10-20 11:56:00 +01002560 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561
2562 thread->restore();
2563
2564 return NO_ERROR;
2565}
2566
Eric Laurentcf2c0212014-07-25 16:20:43 -07002567status_t AudioFlinger::openInput(audio_module_handle_t module,
2568 audio_io_handle_t *input,
2569 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002570 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002571 const String8& address,
2572 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002573 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574{
Eric Laurent83b88082014-06-20 18:31:16 -07002575 Mutex::Autolock _l(mLock);
2576
Glenn Kastene7d66712015-03-05 13:46:52 -08002577 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002578 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002579 }
2580
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002581 sp<ThreadBase> thread = openInput_l(
2582 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002583
2584 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002585 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002586 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002587 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002589 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002590}
Dima Zavin799a70e2011-04-18 16:57:27 -07002591
Eric Laurent6acd1d42017-01-04 14:23:29 -08002592sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002593 audio_io_handle_t *input,
2594 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002595 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002596 const String8& address,
2597 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002598 audio_input_flags_t flags,
2599 audio_devices_t outputDevice,
2600 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002601{
Glenn Kastene7d66712015-03-05 13:46:52 -08002602 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002603 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002604 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002605 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002606 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002607
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002608 // Some flags are specific to framework and must not leak to the HAL.
2609 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2610
Glenn Kasteneeecb982016-02-26 10:44:04 -08002611 // Audio Policy can request a specific handle for hardware hotword.
2612 // The goal here is not to re-open an already opened input.
2613 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002614 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002615 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2616 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2617 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2618 return 0;
2619 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2620 // This should not happen in a transient state with current design.
2621 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2622 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002623 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002624
Eric Laurentcf2c0212014-07-25 16:20:43 -07002625 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002626 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002627 sp<StreamInHalInterface> inStream;
2628 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002629 *input, devices, &halconfig, flags, address.string(), source,
2630 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002631 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2632 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002633 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002634 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002635 halconfig.sample_rate,
2636 halconfig.format,
2637 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002638 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002639 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002641 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002642 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002643 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002644 audio_is_linear_pcm(config->format) &&
2645 audio_is_linear_pcm(halconfig.format) &&
2646 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002647 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2648 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002649 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002650 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002651 inStream.clear();
2652 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002653 *input, devices, &halconfig, flags, address.string(), source,
2654 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002655 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 }
2657
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002658 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002659 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002660 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2661 sp<MmapCaptureThread> thread =
2662 new MmapCaptureThread(this, *input,
2663 inHwDev, inputStream,
2664 primaryOutputDevice_l(), devices, mSystemReady);
2665 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002666 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2667 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002668 return thread;
2669 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002670 // Start record thread
2671 // RecordThread requires both input and output device indication to forward to audio
2672 // pre processing modules
2673 sp<RecordThread> thread = new RecordThread(this,
2674 inputStream,
2675 *input,
2676 primaryOutputDevice_l(),
2677 devices,
2678 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002679 );
2680 mRecordThreads.add(*input, thread);
2681 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2682 return thread;
2683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 }
2685
Eric Laurentcf2c0212014-07-25 16:20:43 -07002686 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 return 0;
2688}
2689
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002690status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691{
Glenn Kastend96c5722012-04-25 13:44:49 -07002692 return closeInput_nonvirtual(input);
2693}
2694
2695status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2696{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 // keep strong reference on the record thread so that
2698 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002699 sp<RecordThread> recordThread;
2700 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 {
2702 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002703 recordThread = checkRecordThread_l(input);
2704 if (recordThread != 0) {
2705 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706
Andy Hungdc099c22018-09-18 13:46:39 -07002707 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002708
Eric Laurent6acd1d42017-01-04 14:23:29 -08002709 // If we still have effect chains, it means that a client still holds a handle
2710 // on at least one effect. We must either move the chain to an existing thread with the
2711 // same session ID or put it aside in case a new record thread is opened for a
2712 // new capture on the same session
2713 sp<EffectChain> chain;
2714 {
2715 Mutex::Autolock _sl(recordThread->mLock);
2716 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2717 // Note: maximum one chain per record thread
2718 if (effectChains.size() != 0) {
2719 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002720 }
2721 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002722 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002723 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002724 // This should only happen in case of overlap between one thread tear down and the
2725 // creation of its replacement
2726 size_t i;
2727 for (i = 0; i < mRecordThreads.size(); i++) {
2728 sp<RecordThread> t = mRecordThreads.valueAt(i);
2729 if (t == recordThread) {
2730 continue;
2731 }
2732 if (t->hasAudioSession(chain->sessionId()) != 0) {
2733 Mutex::Autolock _l(t->mLock);
2734 ALOGV("closeInput() found thread %d for effect session %d",
2735 t->id(), chain->sessionId());
2736 t->addEffectChain_l(chain);
2737 break;
2738 }
2739 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002740 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002741 if (i == mRecordThreads.size()) {
2742 putOrphanEffectChain_l(chain);
2743 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002744 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002745 mRecordThreads.removeItem(input);
2746 } else {
2747 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2748 if (mmapThread == 0) {
2749 return BAD_VALUE;
2750 }
Andy Hungdc099c22018-09-18 13:46:39 -07002751 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002752 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002753 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002754 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2755 ioDesc->mIoHandle = input;
2756 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 }
Eric Laurent83b88082014-06-20 18:31:16 -07002758 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2759 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002760 if (recordThread != 0) {
2761 closeInputFinish(recordThread);
2762 } else if (mmapThread != 0) {
2763 mmapThread->exit();
2764 AudioStreamIn *in = mmapThread->clearInput();
2765 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2766 // from now on thread->mInput is NULL
2767 delete in;
2768 }
Eric Laurent83b88082014-06-20 18:31:16 -07002769 return NO_ERROR;
2770}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002772void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002773{
2774 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002775 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002776 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002777 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002778 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002779}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002781void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002782{
2783 mRecordThreads.removeItem(thread->mId);
2784 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785}
2786
Glenn Kastend2304db2014-02-03 07:40:31 -08002787status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788{
2789 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002790 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791
2792 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2793 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002794 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002795 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002796 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2797 mMmapThreads[i]->invalidateTracks(stream);
2798 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 return NO_ERROR;
2800}
2801
2802
Glenn Kasteneeecb982016-02-26 10:44:04 -08002803audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804{
Glenn Kasten9d003132016-04-06 14:38:09 -07002805 // This is a binder API, so a malicious client could pass in a bad parameter.
2806 // Check for that before calling the internal API nextUniqueId().
2807 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2808 ALOGE("newAudioUniqueId invalid use %d", use);
2809 return AUDIO_UNIQUE_ID_ALLOCATE;
2810 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002811 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812}
2813
Glenn Kastend848eb42016-03-08 13:42:11 -08002814void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002815{
2816 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002817 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002818 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002819 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2820 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002821 caller = pid;
2822 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002823
Eric Laurent021cf962014-05-13 10:18:14 -07002824 {
2825 Mutex::Autolock _cl(mClientLock);
2826 // Ignore requests received from processes not known as notification client. The request
2827 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2828 // called from a different pid leaving a stale session reference. Also we don't know how
2829 // to clear this reference if the client process dies.
2830 if (mNotificationClients.indexOfKey(caller) < 0) {
2831 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2832 return;
2833 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002834 }
2835
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002836 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002837 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002838 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002839 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2840 ref->mCnt++;
2841 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002842 return;
2843 }
2844 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002845 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2846 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002847}
2848
Glenn Kastend848eb42016-03-08 13:42:11 -08002849void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002850{
Eric Laurent6c796322019-04-09 14:13:17 -07002851 std::vector< sp<EffectModule> > removedEffects;
2852 {
2853 Mutex::Autolock _l(mLock);
2854 pid_t caller = IPCThreadState::self()->getCallingPid();
2855 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2856 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2857 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2858 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002859 }
Eric Laurent6c796322019-04-09 14:13:17 -07002860 size_t num = mAudioSessionRefs.size();
2861 for (size_t i = 0; i < num; i++) {
2862 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2863 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2864 ref->mCnt--;
2865 ALOGV(" decremented refcount to %d", ref->mCnt);
2866 if (ref->mCnt == 0) {
2867 mAudioSessionRefs.removeAt(i);
2868 delete ref;
2869 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2870 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2871 }
2872 goto Exit;
2873 }
2874 }
2875 // If the caller is audioserver it is likely that the session being released was acquired
2876 // on behalf of a process not in notification clients and we ignore the warning.
2877 ALOGW_IF(!isAudioServerUid(callerUid),
2878 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002879 }
Eric Laurent6c796322019-04-09 14:13:17 -07002880
2881Exit:
2882 for (auto& effect : removedEffects) {
2883 effect->updatePolicyState();
2884 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002885}
2886
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002887bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2888{
2889 size_t num = mAudioSessionRefs.size();
2890 for (size_t i = 0; i < num; i++) {
2891 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2892 if (ref->mSessionid == audioSession) {
2893 return true;
2894 }
2895 }
2896 return false;
2897}
2898
Eric Laurent6c796322019-04-09 14:13:17 -07002899std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002900
Steve Block3856b092011-10-20 11:56:00 +01002901 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002902
2903 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002904 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002905
2906 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2907 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002908 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002909 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2910 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002911 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2912 chains.push(ec);
2913 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002914 }
2915 }
Eric Laurent6c796322019-04-09 14:13:17 -07002916
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002917 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2918 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002919 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002920 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2921 sp<EffectChain> ec = t->mEffectChains[j];
2922 chains.push(ec);
2923 }
2924 }
2925
Eric Laurent6c796322019-04-09 14:13:17 -07002926 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2927 sp<MmapThread> t = mMmapThreads.valueAt(i);
2928 Mutex::Autolock _l(t->mLock);
2929 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2930 sp<EffectChain> ec = t->mEffectChains[j];
2931 chains.push(ec);
2932 }
2933 }
2934
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002935 for (size_t i = 0; i < chains.size(); i++) {
2936 sp<EffectChain> ec = chains[i];
2937 int sessionid = ec->sessionId();
2938 sp<ThreadBase> t = ec->mThread.promote();
2939 if (t == 0) {
2940 continue;
2941 }
2942 size_t numsessionrefs = mAudioSessionRefs.size();
2943 bool found = false;
2944 for (size_t k = 0; k < numsessionrefs; k++) {
2945 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002946 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002947 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002948 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002949 found = true;
2950 break;
2951 }
2952 }
2953 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002954 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002955 // remove all effects from the chain
2956 while (ec->mEffects.size()) {
2957 sp<EffectModule> effect = ec->mEffects[0];
2958 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002959 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002960 if (effect->purgeHandles()) {
2961 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002962 }
Eric Laurent6c796322019-04-09 14:13:17 -07002963 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002964 }
2965 }
2966 }
Eric Laurent6c796322019-04-09 14:13:17 -07002967 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002968}
2969
Andy Hungdc099c22018-09-18 13:46:39 -07002970// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2971void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2972{
2973 audio_utils::FdToString fdToString;
2974 const int fd = fdToString.fd();
2975 if (fd >= 0) {
2976 thread->dump(fd, {} /* args */);
2977 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2978 }
2979}
2980
Glenn Kasteneeecb982016-02-26 10:44:04 -08002981// checkThread_l() must be called with AudioFlinger::mLock held
2982AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2983{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002984 ThreadBase *thread = checkMmapThread_l(ioHandle);
2985 if (thread == 0) {
2986 switch (audio_unique_id_get_use(ioHandle)) {
2987 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2988 thread = checkPlaybackThread_l(ioHandle);
2989 break;
2990 case AUDIO_UNIQUE_ID_USE_INPUT:
2991 thread = checkRecordThread_l(ioHandle);
2992 break;
2993 default:
2994 break;
2995 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002996 }
2997 return thread;
2998}
2999
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003001AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002{
Glenn Kastena1117922012-01-26 10:53:32 -08003003 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004}
3005
3006// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003007AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008{
3009 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003010 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011}
3012
3013// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003014AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015{
Glenn Kastena1117922012-01-26 10:53:32 -08003016 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017}
3018
Eric Laurent6acd1d42017-01-04 14:23:29 -08003019// checkMmapThread_l() must be called with AudioFlinger::mLock held
3020AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3021{
3022 return mMmapThreads.valueFor(io).get();
3023}
3024
3025
3026// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3027AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3028{
Eric Laurent7459b902017-04-19 18:10:41 -07003029 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003030 if (volumeInterface == nullptr) {
3031 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3032 if (mmapThread != nullptr) {
3033 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003034 MmapPlaybackThread *mmapPlaybackThread =
3035 static_cast<MmapPlaybackThread *>(mmapThread);
3036 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003037 }
3038 }
3039 }
3040 return volumeInterface;
3041}
3042
3043Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3044{
3045 Vector <VolumeInterface *> volumeInterfaces;
3046 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003047 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003048 }
3049 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3050 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003051 MmapPlaybackThread *mmapPlaybackThread =
3052 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3053 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003054 }
3055 }
3056 return volumeInterfaces;
3057}
3058
Glenn Kasteneeecb982016-02-26 10:44:04 -08003059audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060{
Glenn Kasten9d003132016-04-06 14:38:09 -07003061 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003062 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003063 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3064 for (int retry = 0; retry < maxRetries; retry++) {
3065 // The cast allows wraparound from max positive to min negative instead of abort
3066 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3067 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3068 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3069 // allow wrap by skipping 0 and -1 for session ids
3070 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3071 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3072 return (audio_unique_id_t) (base | use);
3073 }
3074 }
3075 // We have no way of recovering from wraparound
3076 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3077 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078}
3079
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003080AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003081{
3082 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3083 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003084 if(thread->isDuplicating()) {
3085 continue;
3086 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003087 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003088 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003089 return thread;
3090 }
3091 }
3092 return NULL;
3093}
3094
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003095audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003096{
3097 PlaybackThread *thread = primaryPlaybackThread_l();
3098
3099 if (thread == NULL) {
3100 return 0;
3101 }
3102
Eric Laurentf1c04f92012-08-28 14:26:53 -07003103 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003104}
3105
Glenn Kastena7335632016-06-09 17:09:53 -07003106AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3107{
3108 size_t minFrameCount = 0;
3109 PlaybackThread *minThread = NULL;
3110 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3111 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3112 if (!thread->isDuplicating()) {
3113 size_t frameCount = thread->frameCountHAL();
3114 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3115 (frameCount == minFrameCount && thread->hasFastMixer() &&
3116 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3117 minFrameCount = frameCount;
3118 minThread = thread;
3119 }
3120 }
3121 }
3122 return minThread;
3123}
3124
Eric Laurenta011e352012-03-29 15:51:43 -07003125sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003126 audio_session_t triggerSession,
3127 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003128 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003129 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003130{
3131 Mutex::Autolock _l(mLock);
3132
3133 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3134 status_t playStatus = NAME_NOT_FOUND;
3135 status_t recStatus = NAME_NOT_FOUND;
3136 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3137 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3138 if (playStatus == NO_ERROR) {
3139 return event;
3140 }
3141 }
3142 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3143 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3144 if (recStatus == NO_ERROR) {
3145 return event;
3146 }
3147 }
3148 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3149 mPendingSyncEvents.add(event);
3150 } else {
3151 ALOGV("createSyncEvent() invalid event %d", event->type());
3152 event.clear();
3153 }
3154 return event;
3155}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003156
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157// ----------------------------------------------------------------------------
3158// Effect management
3159// ----------------------------------------------------------------------------
3160
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003161sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3162 return mEffectsFactoryHal;
3163}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164
Glenn Kastenf587ba52012-01-26 16:25:10 -08003165status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166{
3167 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003168 if (mEffectsFactoryHal.get()) {
3169 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3170 } else {
3171 return -ENODEV;
3172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173}
3174
Glenn Kastenf587ba52012-01-26 16:25:10 -08003175status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176{
3177 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003178 if (mEffectsFactoryHal.get()) {
3179 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3180 } else {
3181 return -ENODEV;
3182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183}
3184
Glenn Kasten5e92a782012-01-30 07:40:52 -08003185status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003186 const effect_uuid_t *pTypeUuid,
3187 uint32_t preferredTypeFlag,
3188 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003190 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3191 return BAD_VALUE;
3192 }
3193
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003195
3196 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003197 return -ENODEV;
3198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003200 status_t status = NO_ERROR;
3201 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3202 // If uuid is specified, request effect descriptor from that.
3203 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3204 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3205 // If uuid is not specified, look for an available implementation
3206 // of the required type instead.
3207
3208 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3209 effect_descriptor_t desc;
3210 desc.flags = 0; // prevent compiler warning
3211
3212 uint32_t numEffects = 0;
3213 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3214 if (status < 0) {
3215 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3216 return status;
3217 }
3218
3219 bool found = false;
3220 for (uint32_t i = 0; i < numEffects; i++) {
3221 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3222 if (status < 0) {
3223 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3224 continue;
3225 }
3226 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3227 // If matching type found save effect descriptor.
3228 found = true;
3229 *descriptor = desc;
3230
3231 // If there's no preferred flag or this descriptor matches the preferred
3232 // flag, success! If this descriptor doesn't match the preferred
3233 // flag, continue enumeration in case a better matching version of this
3234 // effect type is available. Note that this means if no effect with a
3235 // correct flag is found, the descriptor returned will correspond to the
3236 // last effect that at least had a matching type uuid (if any).
3237 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3238 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3239 break;
3240 }
3241 }
3242 }
3243
3244 if (!found) {
3245 status = NAME_NOT_FOUND;
3246 ALOGW("getEffectDescriptor(): Effect not found by type.");
3247 }
3248 } else {
3249 status = BAD_VALUE;
3250 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3251 }
3252 return status;
3253}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003255sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 effect_descriptor_t *pDesc,
3257 const sp<IEffectClient>& effectClient,
3258 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003259 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003260 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003261 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003262 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 status_t *status,
3264 int *id,
3265 int *enabled)
3266{
3267 status_t lStatus = NO_ERROR;
3268 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270
Eric Laurentb6436272016-12-07 19:24:50 -08003271 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003272 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003273 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3274 ALOGW_IF(pid != -1 && pid != callingPid,
3275 "%s uid %d pid %d tried to pass itself off as pid %d",
3276 __func__, callingUid, callingPid, pid);
3277 pid = callingPid;
3278 }
3279
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003280 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3281 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282
3283 if (pDesc == NULL) {
3284 lStatus = BAD_VALUE;
3285 goto Exit;
3286 }
3287
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003288 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003289 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003290 lStatus = NO_INIT;
3291 goto Exit;
3292 }
3293
Andy Hung6096dcd2019-03-13 13:20:30 -07003294 // check audio settings permission for global effects
3295 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3296 if (!settingsAllowed()) {
3297 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3298 lStatus = PERMISSION_DENIED;
3299 goto Exit;
3300 }
3301 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3302 if (!isAudioServerUid(callingUid)) {
3303 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3304 lStatus = PERMISSION_DENIED;
3305 goto Exit;
3306 }
3307
3308 if (io == AUDIO_IO_HANDLE_NONE) {
3309 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3310 lStatus = BAD_VALUE;
3311 goto Exit;
3312 }
3313 } else {
3314 // general sessionId.
3315
3316 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3317 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3318 lStatus = BAD_VALUE;
3319 goto Exit;
3320 }
3321
3322 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3323 // to prevent creating an effect when one doesn't actually have track with that session?
3324 }
3325
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003327 // Get the full effect descriptor from the uuid/type.
3328 // If the session is the output mix, prefer an auxiliary effect,
3329 // otherwise no preference.
3330 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3331 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3332 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3333 if (lStatus < 0) {
3334 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3335 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 }
3337
3338 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003339 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3341 lStatus = INVALID_OPERATION;
3342 goto Exit;
3343 }
3344
Eric Laurent59255e42011-07-27 19:49:51 -07003345 // check recording permission for visualizer
3346 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003347 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003348 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003349 lStatus = PERMISSION_DENIED;
3350 goto Exit;
3351 }
3352
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003354 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003355 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003356 // if the output returned by getOutputForEffect() is removed before we lock the
3357 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3358 // and we will exit safely
3359 io = AudioSystem::getOutputForEffect(&desc);
3360 ALOGV("createEffect got output %d", io);
3361 }
3362
3363 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003364
3365 // If output is not specified try to find a matching audio session ID in one of the
3366 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003367 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3368 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003369 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3370 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003371 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003372 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003373 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3374 if (io == AUDIO_IO_HANDLE_NONE) {
3375 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003377 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003378 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003379 }
Andy Hung444bb552019-03-14 17:06:39 -07003380
3381 // If you wish to create a Record preprocessing AudioEffect in Java,
3382 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3383 // Otherwise it will fail when created on a Playback thread by legacy
3384 // handling below. Ditto with Mmap, the associated Mmap track must be created
3385 // before creating the AudioEffect or the io handle must be specified.
3386 //
3387 // Detect if the effect is created after an AudioRecord is destroyed.
3388 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3389 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3390 " for session %d no longer exists",
3391 __func__, desc.name, sessionId);
3392 lStatus = PERMISSION_DENIED;
3393 goto Exit;
3394 }
3395
3396 // Legacy handling of creating an effect on an expired or made-up
3397 // session id. We think that it is a Playback effect.
3398 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003399 // If no output thread contains the requested session ID, default to
3400 // first output. The effect chain will be moved to the correct output
3401 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003402 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003403 io = mPlaybackThreads.keyAt(0);
3404 }
Steve Block3856b092011-10-20 11:56:00 +01003405 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003406 } else if (checkPlaybackThread_l(io) != nullptr) {
3407 // allow only one effect chain per sessionId on mPlaybackThreads.
3408 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3409 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3410 if (io == checkIo) continue;
3411 const uint32_t sessionType =
3412 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3413 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3414 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3415 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3416 android_errorWriteLog(0x534e4554, "123237974");
3417 lStatus = BAD_VALUE;
3418 goto Exit;
3419 }
3420 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003421 }
3422 ThreadBase *thread = checkRecordThread_l(io);
3423 if (thread == NULL) {
3424 thread = checkPlaybackThread_l(io);
3425 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003426 thread = checkMmapThread_l(io);
3427 if (thread == NULL) {
3428 ALOGE("createEffect() unknown output thread");
3429 lStatus = BAD_VALUE;
3430 goto Exit;
3431 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003432 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003433 } else {
3434 // Check if one effect chain was awaiting for an effect to be created on this
3435 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003436 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003437 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003438 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003439 thread->addEffectChain_l(chain);
3440 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003442
Eric Laurent021cf962014-05-13 10:18:14 -07003443 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003445 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003446 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003447 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003448 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003449 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003450 // remove local strong reference to Client with mClientLock held
3451 Mutex::Autolock _cl(mClientLock);
3452 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003453 } else {
3454 // handle must be valid here, but check again to be safe.
3455 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003456 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457 }
3458
Eric Laurent6c796322019-04-09 14:13:17 -07003459 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3460 // Check CPU and memory usage
3461 sp<EffectModule> effect = handle->effect().promote();
3462 if (effect != nullptr) {
3463 status_t rStatus = effect->updatePolicyState();
3464 if (rStatus != NO_ERROR) {
3465 lStatus = rStatus;
3466 }
3467 }
3468 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003469 handle.clear();
3470 }
3471
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003473 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 return handle;
3475}
3476
Glenn Kastend848eb42016-03-08 13:42:11 -08003477status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003478 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003479{
Steve Block3856b092011-10-20 11:56:00 +01003480 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003481 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003482 Mutex::Autolock _l(mLock);
3483 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003484 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003485 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
Eric Laurentde070132010-07-13 04:45:46 -07003487 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3488 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003489 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003490 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 }
Eric Laurentde070132010-07-13 04:45:46 -07003492 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3493 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003494 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003495 return BAD_VALUE;
3496 }
3497
3498 Mutex::Autolock _dl(dstThread->mLock);
3499 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003500 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501}
3502
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003503
3504void AudioFlinger::setEffectSuspended(int effectId,
3505 audio_session_t sessionId,
3506 bool suspended)
3507{
3508 Mutex::Autolock _l(mLock);
3509
3510 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3511 if (thread == nullptr) {
3512 return;
3513 }
3514 Mutex::Autolock _sl(thread->mLock);
3515 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3516 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3517}
3518
3519
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003520// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003521status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003522 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003523 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003524{
Steve Block3856b092011-10-20 11:56:00 +01003525 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003526 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003527
Eric Laurent59255e42011-07-27 19:49:51 -07003528 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003529 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003530 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003531 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003532 return INVALID_OPERATION;
3533 }
3534
Eric Laurent4c415062016-06-17 16:14:16 -07003535 // Check whether the destination thread and all effects in the chain are compatible
3536 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003537 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003538 " destination thread %p is not compatible with effects in the chain",
3539 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003540 return INVALID_OPERATION;
3541 }
3542
Eric Laurent39e94f82010-07-28 01:32:47 -07003543 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003544 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003545 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003546 // removed.
3547 srcThread->removeEffectChain_l(chain);
3548
3549 // transfer all effects one by one so that new effect chain is created on new thread with
3550 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003551 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003552 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003553 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003554 Vector< sp<EffectModule> > removed;
3555 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003556 while (effect != 0) {
3557 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003558 removed.add(effect);
3559 status = dstThread->addEffect_l(effect);
3560 if (status != NO_ERROR) {
3561 break;
3562 }
Eric Laurentec35a142011-10-05 17:42:25 -07003563 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3564 if (effect->state() == EffectModule::ACTIVE ||
3565 effect->state() == EffectModule::STOPPING) {
3566 effect->start();
3567 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003568 // if the move request is not received from audio policy manager, the effect must be
3569 // re-registered with the new strategy and output
3570 if (dstChain == 0) {
3571 dstChain = effect->chain().promote();
3572 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003573 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003574 status = NO_INIT;
3575 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003576 }
3577 strategy = dstChain->strategy();
3578 }
Eric Laurentde070132010-07-13 04:45:46 -07003579 effect = chain->getEffectFromId_l(0);
3580 }
3581
Eric Laurent5baf2af2013-09-12 17:37:00 -07003582 if (status != NO_ERROR) {
3583 for (size_t i = 0; i < removed.size(); i++) {
3584 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003585 }
3586 }
3587
3588 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589}
3590
Eric Laurent6c796322019-04-09 14:13:17 -07003591status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3592 const sp<PlaybackThread>& dstThread,
3593 sp<PlaybackThread> *srcThread)
3594{
3595 status_t status = NO_ERROR;
3596 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003597 sp<PlaybackThread> thread =
3598 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003599
3600 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3601 Mutex::Autolock _dl(dstThread->mLock);
3602 Mutex::Autolock _sl(thread->mLock);
3603 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3604 sp<EffectChain> dstChain;
3605 if (srcChain == 0) {
3606 return INVALID_OPERATION;
3607 }
3608
3609 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3610 if (effect == 0) {
3611 return INVALID_OPERATION;
3612 }
3613 thread->removeEffect_l(effect);
3614 status = dstThread->addEffect_l(effect);
3615 if (status != NO_ERROR) {
3616 thread->addEffect_l(effect);
3617 status = INVALID_OPERATION;
3618 goto Exit;
3619 }
3620
3621 dstChain = effect->chain().promote();
3622 if (dstChain == 0) {
3623 thread->addEffect_l(effect);
3624 status = INVALID_OPERATION;
3625 }
3626
3627Exit:
3628 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3629 if (effect->state() == EffectModule::ACTIVE ||
3630 effect->state() == EffectModule::STOPPING) {
3631 effect->start();
3632 }
3633 }
3634
3635 if (status == NO_ERROR && srcThread != nullptr) {
3636 *srcThread = thread;
3637 }
3638 return status;
3639}
3640
Eric Laurent5baf2af2013-09-12 17:37:00 -07003641bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003642{
3643 if (mGlobalEffectEnableTime != 0 &&
3644 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3645 return true;
3646 }
3647
3648 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3649 sp<EffectChain> ec =
3650 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003651 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003652 return true;
3653 }
3654 }
3655 return false;
3656}
3657
Eric Laurent5baf2af2013-09-12 17:37:00 -07003658void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003659{
3660 Mutex::Autolock _l(mLock);
3661
3662 mGlobalEffectEnableTime = systemTime();
3663
3664 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3665 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3666 if (t->mType == ThreadBase::OFFLOAD) {
3667 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3668 }
3669 }
3670
3671}
3672
Eric Laurentaaa44472014-09-12 17:41:50 -07003673status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3674{
Eric Laurentd8365c52017-07-16 15:27:05 -07003675 // clear possible suspended state before parking the chain so that it starts in default state
3676 // when attached to a new record thread
3677 chain->setEffectSuspended_l(FX_IID_AEC, false);
3678 chain->setEffectSuspended_l(FX_IID_NS, false);
3679
Glenn Kastend848eb42016-03-08 13:42:11 -08003680 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003681 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003682 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003683 if (index >= 0) {
3684 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3685 return ALREADY_EXISTS;
3686 }
3687 mOrphanEffectChains.add(session, chain);
3688 return NO_ERROR;
3689}
3690
3691sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3692{
3693 sp<EffectChain> chain;
3694 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003695 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003696 if (index >= 0) {
3697 chain = mOrphanEffectChains.valueAt(index);
3698 mOrphanEffectChains.removeItemsAt(index);
3699 }
3700 return chain;
3701}
3702
3703bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3704{
3705 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003706 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003707 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003708 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003709 if (index >= 0) {
3710 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003711 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003712 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003713 mOrphanEffectChains.removeItemsAt(index);
3714 }
3715 return true;
3716 }
3717 return false;
3718}
3719
3720
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721// ----------------------------------------------------------------------------
3722
3723status_t AudioFlinger::onTransact(
3724 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3725{
3726 return BnAudioFlinger::onTransact(code, data, reply, flags);
3727}
3728
Glenn Kasten63238ef2015-03-02 15:50:29 -08003729} // namespace android