blob: 55db699e0274d9d49c069f57e5fa2345c5e837c7 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/time.h>
28#include <sys/resource.h>
29
jiabin57303cc2018-12-18 15:45:57 -080030#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070036#include <media/audiohal/DeviceHalInterface.h>
37#include <media/audiohal/DevicesFactoryHalInterface.h>
38#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070039#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070041#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <utils/String16.h>
43#include <utils/threads.h>
44
Steven Morelandf0c02ce2018-02-23 14:53:55 -080045#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/properties.h>
47
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070051#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Andy Hung6770c6f2015-04-07 13:43:36 -070053#include <media/AudioResamplerPublic.h>
54
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_visualizer.h>
56#include <system/audio_effects/effect_ns.h>
57#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070068#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080074#include "TypedLogger.h"
75
Mathias Agopian65ab4712010-07-14 17:59:35 -070076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
John Grossman1c345192012-03-27 14:00:17 -070078// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
Eric Laurentde070132010-07-13 04:45:46 -070090
Mathias Agopian65ab4712010-07-14 17:59:35 -070091namespace android {
92
Glenn Kastenec1d6b52011-12-12 09:04:45 -080093static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
94static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070095static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070096static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten58912562012-04-03 10:45:00 -070098
John Grossman4ff14ba2012-02-08 16:37:41 -080099nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700102
Eric Laurent813e2a72013-08-31 12:59:48 -0700103// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
104// we define a minimum time during which a global effect is considered enabled.
105static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
106
Eric Laurentfc235202016-12-20 18:48:17 -0800107Mutex gLock;
108wp<AudioFlinger> gAudioFlinger;
109
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700110// Keep a strong reference to media.log service around forever.
111// The service is within our parent process so it can never die in a way that we could observe.
112// These two variables are const after initialization.
113static sp<IBinder> sMediaLogServiceAsBinder;
114static sp<IMediaLogService> sMediaLogService;
115
116static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
117
118static void sMediaLogInit()
119{
120 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
121 if (sMediaLogServiceAsBinder != 0) {
122 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
123 }
124}
125
jiabin57303cc2018-12-18 15:45:57 -0800126// Keep a strong reference to external vibrator service
127static sp<os::IExternalVibratorService> sExternalVibratorService;
128
129static sp<os::IExternalVibratorService> getExternalVibratorService() {
130 if (sExternalVibratorService == 0) {
131 sp <IBinder> binder = defaultServiceManager()->getService(
132 String16("external_vibrator_service"));
133 if (binder != 0) {
134 sExternalVibratorService =
135 interface_cast<os::IExternalVibratorService>(binder);
136 }
137 }
138 return sExternalVibratorService;
139}
140
Mathias Agopian65ab4712010-07-14 17:59:35 -0700141// ----------------------------------------------------------------------------
142
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700143std::string formatToString(audio_format_t format) {
144 std::string result;
145 FormatConverter::toString(format, result);
146 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800147}
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800153 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800155 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700156 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700159 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800160 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700161 mBtNrecIsOff(false),
162 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700163 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800164 mTotalMemory(0),
165 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700166 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700167 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700168 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700170 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
171 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
172 // zero ID has a special meaning, so unavailable
173 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
174 }
175
Glenn Kastenae0cff12016-02-24 13:57:49 -0800176 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800177 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800178 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
179 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700180 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800181 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700182
Wei Jia3f273d12015-11-24 09:06:49 -0800183 // reset battery stats.
184 // if the audio service has crashed, battery stats could be left
185 // in bad state, reset the state upon service start.
186 BatteryNotifier::getInstance().noteResetAudio();
187
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700188 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700189 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
190
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800191 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192}
193
194void AudioFlinger::onFirstRef()
195{
Eric Laurent93575202011-01-18 18:39:02 -0800196 Mutex::Autolock _l(mLock);
197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800199 char val_str[PROPERTY_VALUE_MAX] = { 0 };
200 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
201 uint32_t int_val;
202 if (1 == sscanf(val_str, "%u", &int_val)) {
203 mStandbyTimeInNsecs = milliseconds(int_val);
204 ALOGI("Using %u mSec as standby time.", int_val);
205 } else {
206 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
207 ALOGI("Using default %u mSec as standby time.",
208 (uint32_t)(mStandbyTimeInNsecs / 1000000));
209 }
210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211
Eric Laurenta4c5a552012-03-29 10:12:40 -0700212 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800213
214 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215}
216
217AudioFlinger::~AudioFlinger()
218{
219 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700220 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700221 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700222 }
223 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700224 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700225 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226 }
Andy Hungb4946b62019-03-14 11:19:28 -0700227 while (!mMmapThreads.isEmpty()) {
228 const audio_io_handle_t io = mMmapThreads.keyAt(0);
229 if (mMmapThreads.valueAt(0)->isOutput()) {
230 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
231 } else {
232 closeInput_nonvirtual(io); // removes entry from mMmapThreads
233 }
234 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700235
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800236 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
237 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700238 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700240
241 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700242 if (sMediaLogService != 0) {
243 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
244 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
245 mUnregisteredWriters.pop();
246 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700247 }
248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Eric Laurentfc235202016-12-20 18:48:17 -0800251//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800252__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800253status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
254 const audio_attributes_t *attr,
255 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700256 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800257 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800258 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800259 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700260 sp<MmapStreamInterface>& interface,
261 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800262{
263 sp<AudioFlinger> af;
264 {
265 Mutex::Autolock _l(gLock);
266 af = gAudioFlinger.promote();
267 }
268 status_t ret = NO_INIT;
269 if (af != 0) {
270 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800271 direction, attr, config, client, deviceId,
272 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800273 }
274 return ret;
275}
276
Eric Laurent6acd1d42017-01-04 14:23:29 -0800277status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
278 const audio_attributes_t *attr,
279 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700280 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800281 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800282 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800283 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700284 sp<MmapStreamInterface>& interface,
285 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800286{
287 status_t ret = initCheck();
288 if (ret != NO_ERROR) {
289 return ret;
290 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800291 audio_session_t actualSessionId = *sessionId;
292 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
293 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
294 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800295 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700296 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800297 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
298 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
299 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
300 fullConfig.sample_rate = config->sample_rate;
301 fullConfig.channel_mask = config->channel_mask;
302 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800303 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800304 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800305 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200306 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800307 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800308 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
309 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800310 deviceId, &portId, &secondaryOutputs);
311 ALOGW_IF(!secondaryOutputs.empty(),
312 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800313 } else {
314 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800315 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800316 client.clientPid,
317 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800318 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800319 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700320 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800321 }
322 if (ret != NO_ERROR) {
323 return ret;
324 }
325
326 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
327 // audio policy manager and we can retrieve it
328 sp<MmapThread> thread = mMmapThreads.valueFor(io);
329 if (thread != 0) {
330 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800331 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700332 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800333 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800334 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700335 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700336 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700337 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800338 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700339 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800340 ret = NO_INIT;
341 }
342
343 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
344
Eric Laurentfc235202016-12-20 18:48:17 -0800345 return ret;
346}
347
jiabin57303cc2018-12-18 15:45:57 -0800348/* static */
349int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
350 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
351 if (evs != 0) {
352 int32_t ret;
353 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
354 if (status.isOk()) {
355 return ret;
356 }
357 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800358 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800359}
360
361/* static */
362void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
363 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
364 if (evs != 0) {
365 evs->onExternalVibrationStop(*externalVibration);
366 }
367}
368
Eric Laurenta4c5a552012-03-29 10:12:40 -0700369static const char * const audio_interfaces[] = {
370 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
371 AUDIO_HARDWARE_MODULE_ID_A2DP,
372 AUDIO_HARDWARE_MODULE_ID_USB,
373};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700374
Phil Burk062e67a2015-02-11 13:40:50 -0800375AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700376 audio_module_handle_t module,
377 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700378{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700379 // if module is 0, the request comes from an old policy manager and we should load
380 // well known modules
381 if (module == 0) {
382 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700383 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700384 loadHwModule_l(audio_interfaces[i]);
385 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700386 // then try to find a module supporting the requested device.
387 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
388 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700389 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
390 uint32_t supportedDevices;
391 if (dev->getSupportedDevices(&supportedDevices) == OK &&
392 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700393 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700394 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700395 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700396 } else {
397 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700398 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
399 if (audioHwDevice != NULL) {
400 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700401 }
402 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700403
Dima Zavin799a70e2011-04-18 16:57:27 -0700404 return NULL;
405}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406
Glenn Kasten0f11b512014-01-31 16:18:54 -0800407void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408{
409 const size_t SIZE = 256;
410 char buffer[SIZE];
411 String8 result;
412
413 result.append("Clients:\n");
414 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800415 sp<Client> client = mClients.valueAt(i).promote();
416 if (client != 0) {
417 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
418 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 }
420 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700421
Eric Laurentd1b28d42013-09-18 18:47:13 -0700422 result.append("Notification Clients:\n");
423 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
424 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
425 result.append(buffer);
426 }
427
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700428 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800429 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700430 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
431 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800432 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700433 result.append(buffer);
434 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436}
437
438
Glenn Kasten0f11b512014-01-31 16:18:54 -0800439void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440{
441 const size_t SIZE = 256;
442 char buffer[SIZE];
443 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800444 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445
John Grossman4ff14ba2012-02-08 16:37:41 -0800446 snprintf(buffer, SIZE, "Hardware status: %d\n"
447 "Standby Time mSec: %u\n",
448 hardwareStatus,
449 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 result.append(buffer);
451 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452}
453
Glenn Kasten0f11b512014-01-31 16:18:54 -0800454void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455{
456 const size_t SIZE = 256;
457 char buffer[SIZE];
458 String8 result;
459 snprintf(buffer, SIZE, "Permission Denial: "
460 "can't dump AudioFlinger from pid=%d, uid=%d\n",
461 IPCThreadState::self()->getCallingPid(),
462 IPCThreadState::self()->getCallingUid());
463 result.append(buffer);
464 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465}
466
Eric Laurent81784c32012-11-19 14:55:58 -0800467bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700469 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
470 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471}
472
473status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
474{
Glenn Kasten44deb052012-02-05 18:09:08 -0800475 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476 dumpPermissionDenial(fd, args);
477 } else {
478 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800479 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480 if (!hardwareLocked) {
481 String8 result(kHardwareLockedString);
482 write(fd, result.string(), result.size());
483 } else {
484 mHardwareLock.unlock();
485 }
486
Eric Tan7b651152018-07-13 10:17:19 -0700487 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488
489 // failed to lock - AudioFlinger is probably deadlocked
490 if (!locked) {
491 String8 result(kDeadlockedString);
492 write(fd, result.string(), result.size());
493 }
494
Eric Laurent021cf962014-05-13 10:18:14 -0700495 bool clientLocked = dumpTryLock(mClientLock);
496 if (!clientLocked) {
497 String8 result(kClientLockedString);
498 write(fd, result.string(), result.size());
499 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700500
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700501 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700502 mEffectsFactoryHal->dumpEffects(fd);
503 } else {
504 String8 result(kNoEffectsFactory);
505 write(fd, result.string(), result.size());
506 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700507
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700509 if (clientLocked) {
510 mClientLock.unlock();
511 }
512
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513 dumpInternals(fd, args);
514
515 // dump playback threads
516 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
517 mPlaybackThreads.valueAt(i)->dump(fd, args);
518 }
519
520 // dump record threads
521 for (size_t i = 0; i < mRecordThreads.size(); i++) {
522 mRecordThreads.valueAt(i)->dump(fd, args);
523 }
524
Eric Laurent6acd1d42017-01-04 14:23:29 -0800525 // dump mmap threads
526 for (size_t i = 0; i < mMmapThreads.size(); i++) {
527 mMmapThreads.valueAt(i)->dump(fd, args);
528 }
529
Eric Laurentaaa44472014-09-12 17:41:50 -0700530 // dump orphan effect chains
531 if (mOrphanEffectChains.size() != 0) {
532 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
533 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
534 mOrphanEffectChains.valueAt(i)->dump(fd, args);
535 }
536 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700537 // dump all hardware devs
538 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700539 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
540 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700542
Mikhail Naganov201369b2018-05-16 16:52:32 -0700543 mPatchPanel.dump(fd);
544
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700545 // dump external setParameters
546 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
547 dprintf(fd, "\n%s setParameters:\n", name);
548 logger.dump(fd, " " /* prefix */);
549 };
550 dumpLogger(mRejectedSetParameterLog, "Rejected");
551 dumpLogger(mAppSetParameterLog, "App");
552 dumpLogger(mSystemSetParameterLog, "System");
553
Andy Hunga8115dc2018-08-24 15:51:59 -0700554 // dump historical threads in the last 10 seconds
555 const std::string threadLog = mThreadLog.dumpToString(
556 "Historical Thread Log ", 0 /* lines */,
557 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
558 write(fd, threadLog.c_str(), threadLog.size());
559
rago3bd1c872016-09-26 12:58:14 -0700560 BUFLOG_RESET;
561
Glenn Kastend65d73c2012-06-22 17:21:07 -0700562 if (locked) {
563 mLock.unlock();
564 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800565
Andy Hung8946a282018-04-19 20:04:56 -0700566#ifdef TEE_SINK
567 // NBAIO_Tee dump is safe to call outside of AF lock.
568 NBAIO_Tee::dumpAll(fd, "_DUMP");
569#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800570 // append a copy of media.log here by forwarding fd to it, but don't attempt
571 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700572 if (sMediaLogServiceAsBinder != 0) {
573 dprintf(fd, "\nmedia.log:\n");
574 Vector<String16> args;
575 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800576 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700577
578 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700579 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700580 bool unreachableMemory = false;
581 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700582 if (arg == String16("-m")) {
583 dumpMem = true;
584 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700585 unreachableMemory = true;
586 }
587 }
588
Andy Hung07b745e2016-05-23 16:21:07 -0700589 if (dumpMem) {
590 dprintf(fd, "\nDumping memory:\n");
591 std::string s = dumpMemoryAddresses(100 /* limit */);
592 write(fd, s.c_str(), s.size());
593 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700594 if (unreachableMemory) {
595 dprintf(fd, "\nDumping unreachable memory:\n");
596 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700597 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700598 write(fd, s.c_str(), s.size());
599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 }
601 return NO_ERROR;
602}
603
Eric Laurent021cf962014-05-13 10:18:14 -0700604sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800605{
Eric Laurent021cf962014-05-13 10:18:14 -0700606 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800607 // If pid is already in the mClients wp<> map, then use that entry
608 // (for which promote() is always != 0), otherwise create a new entry and Client.
609 sp<Client> client = mClients.valueFor(pid).promote();
610 if (client == 0) {
611 client = new Client(this, pid);
612 mClients.add(pid, client);
613 }
614
615 return client;
616}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617
Glenn Kasten9e58b552013-01-18 15:09:48 -0800618sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
619{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700620 // If there is no memory allocated for logs, return a dummy writer that does nothing.
621 // Similarly if we can't contact the media.log service, also return a dummy writer.
622 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800623 return new NBLog::Writer();
624 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700625 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
626 // If allocation fails, consult the vector of previously unregistered writers
627 // and garbage-collect one or more them until an allocation succeeds
628 if (shared == 0) {
629 Mutex::Autolock _l(mUnregisteredWritersLock);
630 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
631 {
632 // Pick the oldest stale writer to garbage-collect
633 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
634 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700635 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700636 // Now the media.log remote reference to IMemory is gone. When our last local
637 // reference to IMemory also drops to zero at end of this block,
638 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
639 }
640 // Re-attempt the allocation
641 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
642 if (shared != 0) {
643 goto success;
644 }
645 }
646 // Even after garbage-collecting all old writers, there is still not enough memory,
647 // so return a dummy writer
648 return new NBLog::Writer();
649 }
650success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800651 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
652 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
653 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700654 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800655 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800656}
657
658void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
659{
Glenn Kasten685ef092013-02-04 08:15:34 -0800660 if (writer == 0) {
661 return;
662 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800663 sp<IMemory> iMemory(writer->getIMemory());
664 if (iMemory == 0) {
665 return;
666 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700667 // Rather than removing the writer immediately, append it to a queue of old writers to
668 // be garbage-collected later. This allows us to continue to view old logs for a while.
669 Mutex::Autolock _l(mUnregisteredWritersLock);
670 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800671}
672
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673// IAudioFlinger interface
674
Eric Laurent21da6472017-11-09 16:29:26 -0800675sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
676 CreateTrackOutput& output,
677 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678{
679 sp<PlaybackThread::Track> track;
680 sp<TrackHandle> trackHandle;
681 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800683 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800684 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800685 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686
Eric Laurent21da6472017-11-09 16:29:26 -0800687 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700688 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800689 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700690 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
691 std::vector<int> effectIds;
692
693
Andy Hung4ef19fa2018-05-15 19:35:29 -0700694 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800695 ALOGW_IF(clientUid != callingUid,
696 "%s uid %d tried to pass itself off as %d",
697 __FUNCTION__, callingUid, clientUid);
698 clientUid = callingUid;
699 updatePid = true;
700 }
701 pid_t clientPid = input.clientInfo.clientPid;
702 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700703 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800704 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700705 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800706 __func__, callingUid, callingPid, clientPid);
707 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700708 }
709
Eric Laurent21da6472017-11-09 16:29:26 -0800710 audio_session_t sessionId = input.sessionId;
711 if (sessionId == AUDIO_SESSION_ALLOCATE) {
712 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800713 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
714 lStatus = BAD_VALUE;
715 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800716 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800717
Eric Laurent21da6472017-11-09 16:29:26 -0800718 output.sessionId = sessionId;
719 output.outputId = AUDIO_IO_HANDLE_NONE;
720 output.selectedDeviceId = input.selectedDeviceId;
721
722 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200723 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800724 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800725
726 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
727 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
728 goto Exit;
729 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800730 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
731 // but if someone uses binder directly they could bypass that and cause us to crash
732 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000733 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734 lStatus = BAD_VALUE;
735 goto Exit;
736 }
737
Glenn Kasten53b5d092014-02-05 10:00:23 -0800738 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800739 if (!audio_is_output_channel(input.config.channel_mask)) {
740 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800741 lStatus = BAD_VALUE;
742 goto Exit;
743 }
744
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700745 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800746 if (!audio_is_valid_format(input.config.format)) {
747 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700748 lStatus = BAD_VALUE;
749 goto Exit;
750 }
751
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 {
753 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800754 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800756 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757 lStatus = BAD_VALUE;
758 goto Exit;
759 }
760
Eric Laurent21da6472017-11-09 16:29:26 -0800761 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762
Glenn Kastene848bd92014-03-13 15:00:32 -0700763 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800764 // check if an effect chain with the same session ID is present on another
765 // output thread and move it here.
766 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
767 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
768 if (mPlaybackThreads.keyAt(i) != output.outputId) {
769 uint32_t sessions = t->hasAudioSession(sessionId);
770 if (sessions & ThreadBase::EFFECT_SESSION) {
771 effectThread = t.get();
772 break;
Eric Laurentde070132010-07-13 04:45:46 -0700773 }
774 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700775 }
Eric Laurent21da6472017-11-09 16:29:26 -0800776 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777
Eric Laurent21da6472017-11-09 16:29:26 -0800778 output.sampleRate = input.config.sample_rate;
779 output.frameCount = input.frameCount;
780 output.notificationFrameCount = input.notificationFrameCount;
781 output.flags = input.flags;
782
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700783 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
784 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800785 &output.frameCount, &output.notificationFrameCount,
786 input.notificationsPerBuffer, input.speed,
787 input.sharedBuffer, sessionId, &output.flags,
788 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800789 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700790 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700791
Eric Laurent21da6472017-11-09 16:29:26 -0800792 output.afFrameCount = thread->frameCount();
793 output.afSampleRate = thread->sampleRate();
794 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800795 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800796
Kevin Rocard153f92d2018-12-18 18:33:28 -0800797 if (lStatus == NO_ERROR) {
798 // Connect secondary outputs. Failure on a secondary output must not imped the primary
799 // Any secondary output setup failure will lead to a desync between the AP and AF until
800 // the track is destroyed.
801 TeePatches teePatches;
802 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
803 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
804 if (secondaryThread == NULL) {
805 ALOGE("no playback thread found for secondary output %d", output.outputId);
806 continue;
807 }
808
809 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
810
811 using namespace std::chrono_literals;
812 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
813 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
814 output.sampleRate,
815 inChannelMask,
816 input.config.format,
817 frameCount,
818 NULL /* buffer */,
819 (size_t)0 /* bufferSize */,
820 AUDIO_INPUT_FLAG_DIRECT,
821 0ns /* timeout */);
822 status_t status = patchRecord->initCheck();
823 if (status != NO_ERROR) {
824 ALOGE("Secondary output patchRecord init failed: %d", status);
825 continue;
826 }
827 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
828 streamType,
829 output.sampleRate,
830 input.config.channel_mask,
831 input.config.format,
832 frameCount,
833 patchRecord->buffer(),
834 patchRecord->bufferSize(),
835 output.flags,
836 0ns /* timeout */);
837 status = patchTrack->initCheck();
838 if (status != NO_ERROR) {
839 ALOGE("Secondary output patchTrack init failed: %d", status);
840 continue;
841 }
842 teePatches.push_back({patchRecord, patchTrack});
843 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800844 // In case the downstream patchTrack on the secondaryThread temporarily outlives
845 // our created track, ensure the corresponding patchRecord is still alive.
846 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
847 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800848 }
849 track->setTeePatches(std::move(teePatches));
850 }
851
Eric Laurent39e94f82010-07-28 01:32:47 -0700852 // move effect chain to this output thread if an effect on same session was waiting
853 // for a track to be created
854 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700855 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700856 Mutex::Autolock _dl(thread->mLock);
857 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700858 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
859 effectThreadId = thread->id();
860 effectIds = thread->getEffectIds_l(sessionId);
861 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700862 }
Eric Laurenta011e352012-03-29 15:51:43 -0700863
864 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700865 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800866 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700867 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700868 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700869 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700870 } else {
871 mPendingSyncEvents[i]->cancel();
872 }
Eric Laurenta011e352012-03-29 15:51:43 -0700873 mPendingSyncEvents.removeAt(i);
874 i--;
875 }
876 }
877 }
Glenn Kastene198c362013-08-13 09:13:36 -0700878
Eric Laurent21da6472017-11-09 16:29:26 -0800879 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 }
Glenn Kastene198c362013-08-13 09:13:36 -0700881
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700882 if (lStatus != NO_ERROR) {
883 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700884 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700885 // Don't hold mClientLock when releasing the reference on the track as the
886 // destructor will acquire it.
887 {
888 Mutex::Autolock _cl(mClientLock);
889 client.clear();
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700892 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
894
Eric Laurent6c796322019-04-09 14:13:17 -0700895 // effectThreadId is not NONE if an effect chain corresponding to the track session
896 // was found on another thread and must be moved on this thread
897 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
898 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
899 }
900
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700901 // return handle to client
902 trackHandle = new TrackHandle(track);
903
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800905 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700906 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800907 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700908 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909 return trackHandle;
910}
911
Glenn Kasten2c073da2016-02-26 09:14:08 -0800912uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913{
914 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800915 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800917 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 return 0;
919 }
920 return thread->sampleRate();
921}
922
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800923audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924{
925 Mutex::Autolock _l(mLock);
926 PlaybackThread *thread = checkPlaybackThread_l(output);
927 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000928 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800929 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 }
931 return thread->format();
932}
933
Glenn Kasten2c073da2016-02-26 09:14:08 -0800934size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935{
936 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800937 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800939 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 return 0;
941 }
Glenn Kasten58912562012-04-03 10:45:00 -0700942 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
943 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 return thread->frameCount();
945}
946
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700947size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
948{
949 Mutex::Autolock _l(mLock);
950 ThreadBase *thread = checkThread_l(ioHandle);
951 if (thread == NULL) {
952 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
953 return 0;
954 }
955 return thread->frameCountHAL();
956}
957
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800958uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959{
960 Mutex::Autolock _l(mLock);
961 PlaybackThread *thread = checkPlaybackThread_l(output);
962 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800963 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 return 0;
965 }
966 return thread->latency();
967}
968
969status_t AudioFlinger::setMasterVolume(float value)
970{
Eric Laurenta1884f92011-08-23 08:25:03 -0700971 status_t ret = initCheck();
972 if (ret != NO_ERROR) {
973 return ret;
974 }
975
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 // check calling permissions
977 if (!settingsAllowed()) {
978 return PERMISSION_DENIED;
979 }
980
Eric Laurenta4c5a552012-03-29 10:12:40 -0700981 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700982 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700983
John Grossmanee578c02012-07-23 17:05:46 -0700984 // Set master volume in the HALs which support it.
985 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
986 AutoMutex lock(mHardwareLock);
987 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800988
John Grossmanee578c02012-07-23 17:05:46 -0700989 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
990 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700991 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800992 }
John Grossmanee578c02012-07-23 17:05:46 -0700993 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995
John Grossmanee578c02012-07-23 17:05:46 -0700996 // Now set the master volume in each playback thread. Playback threads
997 // assigned to HALs which do not have master volume support will apply
998 // master volume during the mix operation. Threads with HALs which do
999 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001000 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1001 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1002 continue;
1003 }
John Grossmanee578c02012-07-23 17:05:46 -07001004 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006
1007 return NO_ERROR;
1008}
1009
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001010status_t AudioFlinger::setMasterBalance(float balance)
1011{
1012 status_t ret = initCheck();
1013 if (ret != NO_ERROR) {
1014 return ret;
1015 }
1016
1017 // check calling permissions
1018 if (!settingsAllowed()) {
1019 return PERMISSION_DENIED;
1020 }
1021
1022 // check range
1023 if (isnan(balance) || fabs(balance) > 1.f) {
1024 return BAD_VALUE;
1025 }
1026
1027 Mutex::Autolock _l(mLock);
1028
1029 // short cut.
1030 if (mMasterBalance == balance) return NO_ERROR;
1031
1032 mMasterBalance = balance;
1033
1034 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1035 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1036 continue;
1037 }
1038 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1039 }
1040
1041 return NO_ERROR;
1042}
1043
Glenn Kastenf78aee72012-01-04 11:00:47 -08001044status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045{
Eric Laurenta1884f92011-08-23 08:25:03 -07001046 status_t ret = initCheck();
1047 if (ret != NO_ERROR) {
1048 return ret;
1049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050
1051 // check calling permissions
1052 if (!settingsAllowed()) {
1053 return PERMISSION_DENIED;
1054 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001055 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001056 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 return BAD_VALUE;
1058 }
1059
1060 { // scope for the lock
1061 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001062 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001064 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 mHardwareStatus = AUDIO_HW_IDLE;
1066 }
1067
1068 if (NO_ERROR == ret) {
1069 Mutex::Autolock _l(mLock);
1070 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001071 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001072 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 }
1074
1075 return ret;
1076}
1077
1078status_t AudioFlinger::setMicMute(bool state)
1079{
Eric Laurenta1884f92011-08-23 08:25:03 -07001080 status_t ret = initCheck();
1081 if (ret != NO_ERROR) {
1082 return ret;
1083 }
1084
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 // check calling permissions
1086 if (!settingsAllowed()) {
1087 return PERMISSION_DENIED;
1088 }
1089
1090 AutoMutex lock(mHardwareLock);
1091 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001092 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001093 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1094 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001095 if (result != NO_ERROR) {
1096 ret = result;
1097 }
1098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 mHardwareStatus = AUDIO_HW_IDLE;
1100 return ret;
1101}
1102
1103bool AudioFlinger::getMicMute() const
1104{
Eric Laurenta1884f92011-08-23 08:25:03 -07001105 status_t ret = initCheck();
1106 if (ret != NO_ERROR) {
1107 return false;
1108 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001109 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001110 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001111 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001113 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001114 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1115 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001116 if (result == NO_ERROR) {
1117 mute = mute && state;
1118 }
1119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001121
1122 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123}
1124
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001125void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1126{
1127 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1128
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001129 AutoMutex lock(mLock);
1130 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001131 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1132 }
1133 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1134 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001135 }
1136}
1137
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138status_t AudioFlinger::setMasterMute(bool muted)
1139{
John Grossmand8f178d2012-07-20 14:51:35 -07001140 status_t ret = initCheck();
1141 if (ret != NO_ERROR) {
1142 return ret;
1143 }
1144
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 // check calling permissions
1146 if (!settingsAllowed()) {
1147 return PERMISSION_DENIED;
1148 }
1149
John Grossmanee578c02012-07-23 17:05:46 -07001150 Mutex::Autolock _l(mLock);
1151 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001152
John Grossmanee578c02012-07-23 17:05:46 -07001153 // Set master mute in the HALs which support it.
1154 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1155 AutoMutex lock(mHardwareLock);
1156 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001157
John Grossmanee578c02012-07-23 17:05:46 -07001158 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1159 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001160 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001161 }
John Grossmanee578c02012-07-23 17:05:46 -07001162 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001163 }
1164
John Grossmanee578c02012-07-23 17:05:46 -07001165 // Now set the master mute in each playback thread. Playback threads
1166 // assigned to HALs which do not have master mute support will apply master
1167 // mute during the mix operation. Threads with HALs which do support master
1168 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001169 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1170 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1171 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173
1174 return NO_ERROR;
1175}
1176
1177float AudioFlinger::masterVolume() const
1178{
Glenn Kasten98067102011-12-13 11:47:54 -08001179 Mutex::Autolock _l(mLock);
1180 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181}
1182
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001183status_t AudioFlinger::getMasterBalance(float *balance) const
1184{
1185 Mutex::Autolock _l(mLock);
1186 *balance = getMasterBalance_l();
1187 return NO_ERROR; // if called through binder, may return a transactional error
1188}
1189
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190bool AudioFlinger::masterMute() const
1191{
Glenn Kasten98067102011-12-13 11:47:54 -08001192 Mutex::Autolock _l(mLock);
1193 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194}
1195
John Grossman4ff14ba2012-02-08 16:37:41 -08001196float AudioFlinger::masterVolume_l() const
1197{
John Grossman4ff14ba2012-02-08 16:37:41 -08001198 return mMasterVolume;
1199}
1200
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001201float AudioFlinger::getMasterBalance_l() const
1202{
1203 return mMasterBalance;
1204}
1205
John Grossmand8f178d2012-07-20 14:51:35 -07001206bool AudioFlinger::masterMute_l() const
1207{
John Grossmanee578c02012-07-23 17:05:46 -07001208 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001209}
1210
Eric Laurent223fd5c2014-11-11 13:43:36 -08001211status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1212{
1213 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001214 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001215 return BAD_VALUE;
1216 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001217 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1218 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1219 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001220 return PERMISSION_DENIED;
1221 }
1222
1223 return NO_ERROR;
1224}
1225
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001226status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1227 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228{
1229 // check calling permissions
1230 if (!settingsAllowed()) {
1231 return PERMISSION_DENIED;
1232 }
1233
Eric Laurent223fd5c2014-11-11 13:43:36 -08001234 status_t status = checkStreamType(stream);
1235 if (status != NO_ERROR) {
1236 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 }
Eric Laurent98e38192018-02-15 18:31:53 -08001238 if (output == AUDIO_IO_HANDLE_NONE) {
1239 return BAD_VALUE;
1240 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001241 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1242 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243
1244 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001245 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1246 if (volumeInterface == NULL) {
1247 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 }
Eric Laurent98e38192018-02-15 18:31:53 -08001249 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250
1251 return NO_ERROR;
1252}
1253
Glenn Kastenfff6d712012-01-12 16:38:12 -08001254status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255{
1256 // check calling permissions
1257 if (!settingsAllowed()) {
1258 return PERMISSION_DENIED;
1259 }
1260
Eric Laurent223fd5c2014-11-11 13:43:36 -08001261 status_t status = checkStreamType(stream);
1262 if (status != NO_ERROR) {
1263 return status;
1264 }
1265 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1266
1267 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001268 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 return BAD_VALUE;
1270 }
1271
Eric Laurent93575202011-01-18 18:39:02 -08001272 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001274 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1275 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1276 volumeInterfaces[i]->setStreamMute(stream, muted);
1277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001278
1279 return NO_ERROR;
1280}
1281
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001282float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001284 status_t status = checkStreamType(stream);
1285 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 return 0.0f;
1287 }
Eric Laurent98e38192018-02-15 18:31:53 -08001288 if (output == AUDIO_IO_HANDLE_NONE) {
1289 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290 }
1291
Eric Laurent98e38192018-02-15 18:31:53 -08001292 AutoMutex lock(mLock);
1293 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1294 if (volumeInterface == NULL) {
1295 return 0.0f;
1296 }
1297
1298 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299}
1300
Glenn Kastenfff6d712012-01-12 16:38:12 -08001301bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001303 status_t status = checkStreamType(stream);
1304 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 return true;
1306 }
1307
Glenn Kasten6637baa2012-01-09 09:40:36 -08001308 AutoMutex lock(mLock);
1309 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310}
1311
Eric Laurent054d9d32015-04-24 08:48:48 -07001312
1313void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1314{
1315 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1316 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1317 }
1318}
1319
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001320// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1321void AudioFlinger::forwardParametersToDownstreamPatches_l(
1322 audio_io_handle_t upStream, const String8& keyValuePairs,
1323 std::function<bool(const sp<PlaybackThread>&)> useThread)
1324{
1325 std::vector<PatchPanel::SoftwarePatch> swPatches;
1326 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1327 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1328 __func__, swPatches.size(), upStream);
1329 for (const auto& swPatch : swPatches) {
1330 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1331 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1332 downStream->setParameters(keyValuePairs);
1333 }
1334 }
1335}
1336
Eric Laurentf1047e82018-04-16 19:18:20 -07001337// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1338// Some keys are used for audio routing and audio path configuration and should be reserved for use
1339// by audio policy and audio flinger for functional, privacy and security reasons.
1340void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1341{
1342 static const String8 kReservedParameters[] = {
1343 String8(AudioParameter::keyRouting),
1344 String8(AudioParameter::keySamplingRate),
1345 String8(AudioParameter::keyFormat),
1346 String8(AudioParameter::keyChannels),
1347 String8(AudioParameter::keyFrameCount),
1348 String8(AudioParameter::keyInputSource),
1349 String8(AudioParameter::keyMonoOutput),
1350 String8(AudioParameter::keyStreamConnect),
1351 String8(AudioParameter::keyStreamDisconnect),
1352 String8(AudioParameter::keyStreamSupportedFormats),
1353 String8(AudioParameter::keyStreamSupportedChannels),
1354 String8(AudioParameter::keyStreamSupportedSamplingRates),
1355 };
1356
Andy Hung4ef19fa2018-05-15 19:35:29 -07001357 if (isAudioServerUid(callingUid)) {
1358 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001359 }
1360
1361 AudioParameter param = AudioParameter(keyValuePairs);
1362 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001363 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001364 for (auto& key : kReservedParameters) {
1365 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001366 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001367 param.remove(key);
1368 }
1369 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001370 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1371 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001372 keyValuePairs = param.toString();
1373}
1374
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001375void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1376 size_t rejectedKVPSize, const String8& rejectedKVPs,
1377 uid_t callingUid) {
1378 auto prefix = String8::format("UID %5d", callingUid);
1379 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1380 if (rejectedKVPSize != 0) {
1381 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1382 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1383 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1384 } else {
1385 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1386 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1387 }
1388}
1389
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001390status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391{
Eric Laurentf1047e82018-04-16 19:18:20 -07001392 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1393 ioHandle, keyValuePairs.string(),
1394 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001395
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 // check calling permissions
1397 if (!settingsAllowed()) {
1398 return PERMISSION_DENIED;
1399 }
1400
Eric Laurentf1047e82018-04-16 19:18:20 -07001401 String8 filteredKeyValuePairs = keyValuePairs;
1402 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1403
1404 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1405
Glenn Kasten142f5192014-03-25 17:44:59 -07001406 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1407 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001408 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001409 // result will remain NO_INIT if no audio device is present
1410 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001411 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001412 AutoMutex lock(mHardwareLock);
1413 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1414 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001415 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001416 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001417 // return success if at least one audio device accepts the parameters as not all
1418 // HALs are requested to support all parameters. If no audio device supports the
1419 // requested parameters, the last error is reported.
1420 if (final_result != NO_ERROR) {
1421 final_result = result;
1422 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001423 }
1424 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001425 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001426 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001427 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001428 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001429 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1430 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001431 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001432 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001433 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001434 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001435 }
1436 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001437 String8 screenState;
1438 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001439 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001440 if (isOff != (AudioFlinger::mScreenState & 1)) {
1441 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001442 }
1443 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001444 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445 }
1446
1447 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1448 // and the thread is exited once the lock is released
1449 sp<ThreadBase> thread;
1450 {
1451 Mutex::Autolock _l(mLock);
1452 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001453 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001455 if (thread == 0) {
1456 thread = checkMmapThread_l(ioHandle);
1457 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001458 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001459 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001460 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001461 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001462 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1463 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001464 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 }
1467 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001468 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001469 status_t result = thread->setParameters(filteredKeyValuePairs);
1470 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1471 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 }
1473 return BAD_VALUE;
1474}
1475
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001476String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001478 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1479 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480
Eric Laurenta4c5a552012-03-29 10:12:40 -07001481 Mutex::Autolock _l(mLock);
1482
Glenn Kasten142f5192014-03-25 17:44:59 -07001483 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001484 String8 out_s8;
1485
Dima Zavin799a70e2011-04-18 16:57:27 -07001486 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001487 String8 s;
1488 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001489 {
1490 AutoMutex lock(mHardwareLock);
1491 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001492 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1493 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001494 mHardwareStatus = AUDIO_HW_IDLE;
1495 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001496 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001497 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001498 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 }
1500
Eric Laurent6acd1d42017-01-04 14:23:29 -08001501 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1502 if (thread == NULL) {
1503 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1504 if (thread == NULL) {
1505 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1506 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001507 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001508 }
1509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001511 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512}
1513
Glenn Kastendd8104c2012-07-02 12:42:44 -07001514size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1515 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516{
Eric Laurenta1884f92011-08-23 08:25:03 -07001517 status_t ret = initCheck();
1518 if (ret != NO_ERROR) {
1519 return 0;
1520 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001521 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001522 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001523 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001524 return 0;
1525 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001526
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001527 AutoMutex lock(mHardwareLock);
1528 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001529 audio_config_t config, proposed;
1530 memset(&proposed, 0, sizeof(proposed));
1531 proposed.sample_rate = sampleRate;
1532 proposed.channel_mask = channelMask;
1533 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001534
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001535 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001536 size_t frames;
1537 for (;;) {
1538 // Note: config is currently a const parameter for get_input_buffer_size()
1539 // but we use a copy from proposed in case config changes from the call.
1540 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001541 status_t result = dev->getInputBufferSize(&config, &frames);
1542 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001543 break; // hal success, config is the result
1544 }
1545 // change one parameter of the configuration each iteration to a more "common" value
1546 // to see if the device will support it.
1547 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1548 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1549 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1550 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1551 } else {
1552 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1553 "format %#x, channelMask 0x%X",
1554 sampleRate, format, channelMask);
1555 break; // retries failed, break out of loop with frames == 0.
1556 }
1557 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001558 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001559 if (frames > 0 && config.sample_rate != sampleRate) {
1560 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1561 }
1562 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563}
1564
Glenn Kasten5f972c02014-01-13 09:59:31 -08001565uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 Mutex::Autolock _l(mLock);
1568
1569 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1570 if (recordThread != NULL) {
1571 return recordThread->getInputFramesLost();
1572 }
1573 return 0;
1574}
1575
1576status_t AudioFlinger::setVoiceVolume(float value)
1577{
Eric Laurenta1884f92011-08-23 08:25:03 -07001578 status_t ret = initCheck();
1579 if (ret != NO_ERROR) {
1580 return ret;
1581 }
1582
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 // check calling permissions
1584 if (!settingsAllowed()) {
1585 return PERMISSION_DENIED;
1586 }
1587
1588 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001589 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001590 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001591 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 mHardwareStatus = AUDIO_HW_IDLE;
1593
1594 return ret;
1595}
1596
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001597status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001598 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 Mutex::Autolock _l(mLock);
1601
1602 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1603 if (playbackThread != NULL) {
1604 return playbackThread->getRenderPosition(halFrames, dspFrames);
1605 }
1606
1607 return BAD_VALUE;
1608}
1609
1610void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1611{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001613 if (client == 0) {
1614 return;
1615 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001616 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001617 {
1618 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001619 if (mNotificationClients.indexOfKey(pid) < 0) {
1620 sp<NotificationClient> notificationClient = new NotificationClient(this,
1621 client,
1622 pid);
1623 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624
Eric Laurent021cf962014-05-13 10:18:14 -07001625 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626
Marco Nelissen06b46062014-11-14 07:58:25 -08001627 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001628 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001629 }
1630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631
Eric Laurent021cf962014-05-13 10:18:14 -07001632 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001633 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001634 // the config change is always sent from playback or record threads to avoid deadlock
1635 // with AudioSystem::gLock
1636 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001637 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001640 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001641 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642 }
1643}
1644
1645void AudioFlinger::removeNotificationClient(pid_t pid)
1646{
Eric Laurent6c796322019-04-09 14:13:17 -07001647 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001648 {
Eric Laurent6c796322019-04-09 14:13:17 -07001649 Mutex::Autolock _l(mLock);
1650 {
1651 Mutex::Autolock _cl(mClientLock);
1652 mNotificationClients.removeItem(pid);
1653 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001654
Eric Laurent6c796322019-04-09 14:13:17 -07001655 ALOGV("%d died, releasing its sessions", pid);
1656 size_t num = mAudioSessionRefs.size();
1657 bool removed = false;
1658 for (size_t i = 0; i < num; ) {
1659 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1660 ALOGV(" pid %d @ %zu", ref->mPid, i);
1661 if (ref->mPid == pid) {
1662 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1663 mAudioSessionRefs.removeAt(i);
1664 delete ref;
1665 removed = true;
1666 num--;
1667 } else {
1668 i++;
1669 }
1670 }
1671 if (removed) {
1672 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001673 }
1674 }
Eric Laurent6c796322019-04-09 14:13:17 -07001675 for (auto& effect : removedEffects) {
1676 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678}
1679
Eric Laurent73e26b62015-04-27 16:55:58 -07001680void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001681 const sp<AudioIoDescriptor>& ioDesc,
1682 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683{
Eric Laurent021cf962014-05-13 10:18:14 -07001684 Mutex::Autolock _l(mClientLock);
1685 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001687 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1688 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1689 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 }
1691}
1692
Eric Laurent021cf962014-05-13 10:18:14 -07001693// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694void AudioFlinger::removeClient_l(pid_t pid)
1695{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001696 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001697 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 mClients.removeItem(pid);
1699}
1700
Eric Laurent717e1282012-06-29 16:36:52 -07001701// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001702sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1703 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001704{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001705 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001706
1707 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001708 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001709 ALOG_ASSERT(thread == 0);
1710 thread = mPlaybackThreads.valueAt(i);
1711 }
1712 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001713 if (thread != nullptr) {
1714 return thread;
1715 }
1716 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1717 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1718 ALOG_ASSERT(thread == 0);
1719 thread = mRecordThreads.valueAt(i);
1720 }
1721 }
1722 if (thread != nullptr) {
1723 return thread;
1724 }
1725 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1726 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1727 ALOG_ASSERT(thread == 0);
1728 thread = mMmapThreads.valueAt(i);
1729 }
1730 }
Eric Laurent717e1282012-06-29 16:36:52 -07001731 return thread;
1732}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735
1736// ----------------------------------------------------------------------------
1737
1738AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1739 : RefBase(),
1740 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001741 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742{
Andy Hung6f248bb2018-01-23 14:04:37 -08001743 mMemoryDealer = new MemoryDealer(
1744 audioFlinger->getClientSharedHeapSize(),
1745 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746}
1747
Eric Laurent021cf962014-05-13 10:18:14 -07001748// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749AudioFlinger::Client::~Client()
1750{
1751 mAudioFlinger->removeClient_l(mPid);
1752}
1753
Glenn Kasten435dbe62012-01-30 10:15:48 -08001754sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755{
1756 return mMemoryDealer;
1757}
1758
1759// ----------------------------------------------------------------------------
1760
1761AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1762 const sp<IAudioFlingerClient>& client,
1763 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001764 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765{
1766}
1767
1768AudioFlinger::NotificationClient::~NotificationClient()
1769{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770}
1771
Glenn Kasten0f11b512014-01-31 16:18:54 -08001772void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773{
1774 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001775 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776}
1777
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001778// ----------------------------------------------------------------------------
1779AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1780 : mPendingRequests(false) {}
1781
1782
1783void AudioFlinger::MediaLogNotifier::requestMerge() {
1784 AutoMutex _l(mMutex);
1785 mPendingRequests = true;
1786 mCond.signal();
1787}
1788
1789bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001790 // Should already have been checked, but just in case
1791 if (sMediaLogService == 0) {
1792 return false;
1793 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001794 // Wait until there are pending requests
1795 {
1796 AutoMutex _l(mMutex);
1797 mPendingRequests = false; // to ignore past requests
1798 while (!mPendingRequests) {
1799 mCond.wait(mMutex);
1800 // TODO may also need an exitPending check
1801 }
1802 mPendingRequests = false;
1803 }
1804 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001805 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001806 usleep(kPostTriggerSleepPeriod);
1807 return true;
1808}
1809
1810void AudioFlinger::requestLogMerge() {
1811 mMediaLogNotifier->requestMerge();
1812}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813
1814// ----------------------------------------------------------------------------
1815
Eric Laurentf14db3c2017-12-08 14:20:36 -08001816sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1817 CreateRecordOutput& output,
1818 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819{
1820 sp<RecordThread::RecordTrack> recordTrack;
1821 sp<RecordHandle> recordHandle;
1822 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001824 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001825 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826
Eric Laurentf14db3c2017-12-08 14:20:36 -08001827 output.cblk.clear();
1828 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001829 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001830
Eric Laurentf14db3c2017-12-08 14:20:36 -08001831 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001832 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001833 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001834 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001835 ALOGW_IF(clientUid != callingUid,
1836 "%s uid %d tried to pass itself off as %d",
1837 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001838 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001839 updatePid = true;
1840 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001841 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001842 if (updatePid) {
1843 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001844 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001845 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001846 __func__, callingUid, callingPid, clientPid);
1847 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001848 }
1849
Andy Hung6770c6f2015-04-07 13:43:36 -07001850 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001851 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1852 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001853 lStatus = BAD_VALUE;
1854 goto Exit;
1855 }
1856
Glenn Kasten53b5d092014-02-05 10:00:23 -08001857 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001858 if (!audio_is_input_channel(input.config.channel_mask)) {
1859 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001860 lStatus = BAD_VALUE;
1861 goto Exit;
1862 }
1863
Eric Laurentf14db3c2017-12-08 14:20:36 -08001864 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1865 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1866 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1867 lStatus = BAD_VALUE;
1868 goto Exit;
1869 }
1870
1871 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001872 output.selectedDeviceId = input.selectedDeviceId;
1873 output.flags = input.flags;
1874
1875 client = registerPid(clientPid);
1876
1877 // Not a conventional loop, but a retry loop for at most two iterations total.
1878 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1879 // Exits loop via break on no error of got exit on error
1880 // The sp<> references will be dropped when re-entering scope.
1881 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1882 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001883 // release previously opened input if retrying.
1884 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1885 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001886 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001887 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001888 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001889 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001890 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001891 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1892 sessionId,
1893 // FIXME compare to AudioTrack
1894 clientPid,
1895 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001896 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001897 &input.config,
1898 output.flags, &output.selectedDeviceId, &portId);
1899
Glenn Kasten05997e22014-03-13 15:08:33 -07001900 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001902 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001904 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 lStatus = BAD_VALUE;
1906 goto Exit;
1907 }
1908
Eric Laurentf14db3c2017-12-08 14:20:36 -08001909 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910
Eric Laurentf14db3c2017-12-08 14:20:36 -08001911 output.sampleRate = input.config.sample_rate;
1912 output.frameCount = input.frameCount;
1913 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001914
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001915 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001916 input.config.format, input.config.channel_mask,
1917 &output.frameCount, sessionId,
1918 &output.notificationFrameCount,
1919 clientUid, &output.flags,
1920 input.clientInfo.clientTid,
1921 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001922 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001923
Eric Laurentf14db3c2017-12-08 14:20:36 -08001924 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1925 // audio policy manager without FAST constraint
1926 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001927 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001928 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001929
1930 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001931 goto Exit;
1932 }
1933
1934 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1935 // session and move it to this thread.
1936 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1937 if (chain != 0) {
1938 Mutex::Autolock _l(thread->mLock);
1939 thread->addEffectChain_l(chain);
1940 }
1941 break;
1942 }
1943 // End of retry loop.
1944 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 }
Glenn Kastene198c362013-08-13 09:13:36 -07001946
Eric Laurentf14db3c2017-12-08 14:20:36 -08001947 output.cblk = recordTrack->getCblk();
1948 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001949 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001950
1951 // return handle to client
1952 recordHandle = new RecordHandle(recordTrack);
1953
1954Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001955 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001956 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001957 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001958 // Don't hold mClientLock when releasing the reference on the track as the
1959 // destructor will acquire it.
1960 {
1961 Mutex::Autolock _cl(mClientLock);
1962 client.clear();
1963 }
Eric Laurent896c9672017-12-08 14:08:45 -08001964 recordTrack.clear();
1965 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001966 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 }
1969
Glenn Kasten9156ef32013-08-06 15:39:08 -07001970 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 return recordHandle;
1972}
1973
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001974
1975
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976// ----------------------------------------------------------------------------
1977
Eric Laurenta4c5a552012-03-29 10:12:40 -07001978audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1979{
Eric Laurent44622db2014-08-01 19:00:33 -07001980 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001981 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001982 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001983 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001984 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001985 }
1986 Mutex::Autolock _l(mLock);
1987 return loadHwModule_l(name);
1988}
1989
1990// loadHwModule_l() must be called with AudioFlinger::mLock held
1991audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1992{
1993 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1994 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1995 ALOGW("loadHwModule() module %s already loaded", name);
1996 return mAudioHwDevs.keyAt(i);
1997 }
1998 }
1999
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002000 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002001
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002002 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002003 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002004 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002005 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002006 }
2007
2008 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002009 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002010 mHardwareStatus = AUDIO_HW_IDLE;
2011 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002012 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002013 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002014 }
2015
John Grossmanee578c02012-07-23 17:05:46 -07002016 // Check and cache this HAL's level of support for master mute and master
2017 // volume. If this is the first HAL opened, and it supports the get
2018 // methods, use the initial values provided by the HAL as the current
2019 // master mute and volume settings.
2020
2021 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2022 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002023 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002024
2025 if (0 == mAudioHwDevs.size()) {
2026 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002027 float mv;
2028 if (OK == dev->getMasterVolume(&mv)) {
2029 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002030 }
2031
2032 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002033 bool mm;
2034 if (OK == dev->getMasterMute(&mm)) {
2035 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002036 }
2037 }
2038
Eric Laurenta4c5a552012-03-29 10:12:40 -07002039 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002040 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002041 flags = static_cast<AudioHwDevice::Flags>(flags |
2042 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2043 }
2044
2045 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002046 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002047 flags = static_cast<AudioHwDevice::Flags>(flags |
2048 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2049 }
2050
Eric Laurenta4c5a552012-03-29 10:12:40 -07002051 mHardwareStatus = AUDIO_HW_IDLE;
2052 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002053 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002054 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2055 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2056 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002057
Glenn Kastena13cde92016-03-28 15:26:02 -07002058 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002059 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002060
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002061 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002062
2063 return handle;
2064
2065}
2066
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002067// ----------------------------------------------------------------------------
2068
Glenn Kasten3b16c762012-11-14 08:44:39 -08002069uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002070{
2071 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002072 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002073 return thread != NULL ? thread->sampleRate() : 0;
2074}
2075
Glenn Kastene33054e2012-11-14 12:54:39 -08002076size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002077{
2078 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002079 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002080 return thread != NULL ? thread->frameCountHAL() : 0;
2081}
2082
2083// ----------------------------------------------------------------------------
2084
Andy Hung6f248bb2018-01-23 14:04:37 -08002085status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002086{
2087 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002088 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002089 return PERMISSION_DENIED;
2090 }
2091 Mutex::Autolock _l(mLock);
2092 if (mIsDeviceTypeKnown) {
2093 return INVALID_OPERATION;
2094 }
2095 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002096 mTotalMemory = totalMemory;
2097 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2098 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2099 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2100 // though actual setting is determined through device configuration.
2101 constexpr int64_t GB = 1024 * 1024 * 1024;
2102 mClientSharedHeapSize =
2103 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2104 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2105 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2106 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2107 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002108 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002109
2110 // TODO: Cache the client shared heap size in a persistent property.
2111 // It's possible that a native process or Java service or app accesses audioserver
2112 // after it is registered by system server, but before AudioService updates
2113 // the memory info. This would occur immediately after boot or an audioserver
2114 // crash and restore. Before update from AudioService, the client would get the
2115 // minimum heap size.
2116
2117 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2118 (isLowRamDevice ? "true" : "false"),
2119 (long long)mTotalMemory,
2120 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002121 return NO_ERROR;
2122}
2123
Andy Hung6f248bb2018-01-23 14:04:37 -08002124size_t AudioFlinger::getClientSharedHeapSize() const
2125{
2126 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2127 if (heapSizeInBytes != 0) { // read-only property overrides all.
2128 return heapSizeInBytes;
2129 }
2130 return mClientSharedHeapSize;
2131}
2132
Mikhail Naganovdea53042018-04-26 13:10:21 -07002133status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2134{
2135 ALOGV(__func__);
2136
2137 audio_module_handle_t module;
2138 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2139 module = config->ext.device.hw_module;
2140 } else {
2141 module = config->ext.mix.hw_module;
2142 }
2143
2144 Mutex::Autolock _l(mLock);
2145 ssize_t index = mAudioHwDevs.indexOfKey(module);
2146 if (index < 0) {
2147 ALOGW("%s() bad hw module %d", __func__, module);
2148 return BAD_VALUE;
2149 }
2150
2151 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2152 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2153}
2154
Eric Laurent93c3d412014-08-01 14:48:35 -07002155audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2156{
2157 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002158
2159 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2160 if (index >= 0) {
2161 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2162 mHwAvSyncIds.valueAt(index), sessionId);
2163 return mHwAvSyncIds.valueAt(index);
2164 }
2165
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002166 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002167 if (dev == NULL) {
2168 return AUDIO_HW_SYNC_INVALID;
2169 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002170 String8 reply;
2171 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002172 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002173 param = AudioParameter(reply);
2174 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002175
2176 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002177 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002178 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2179 return AUDIO_HW_SYNC_INVALID;
2180 }
2181
2182 // allow only one session for a given HW A/V sync ID.
2183 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2184 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2185 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2186 value, mHwAvSyncIds.keyAt(i));
2187 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002188 break;
2189 }
2190 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002191
2192 mHwAvSyncIds.add(sessionId, value);
2193
2194 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2195 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2196 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002197 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002198 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002199 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002200 String8 keyValuePairs = param.toString();
2201 thread->setParameters(keyValuePairs);
2202 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2203 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002204 break;
2205 }
2206 }
2207
2208 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2209 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002210}
2211
Eric Laurent72e3f392015-05-20 14:43:50 -07002212status_t AudioFlinger::systemReady()
2213{
2214 Mutex::Autolock _l(mLock);
2215 ALOGI("%s", __FUNCTION__);
2216 if (mSystemReady) {
2217 ALOGW("%s called twice", __FUNCTION__);
2218 return NO_ERROR;
2219 }
2220 mSystemReady = true;
2221 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2222 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2223 thread->systemReady();
2224 }
2225 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2226 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2227 thread->systemReady();
2228 }
2229 return NO_ERROR;
2230}
2231
jiabin46a76fa2018-01-05 10:18:21 -08002232status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2233{
jiabin9ff780e2018-03-19 18:19:52 -07002234 AutoMutex lock(mHardwareLock);
2235 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2236 status_t status = dev->getMicrophones(microphones);
2237 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002238}
2239
Eric Laurentfa90e842014-10-17 18:12:31 -07002240// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2241void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2242{
2243 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2244 if (index >= 0) {
2245 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2246 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2247 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002248 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002249 String8 keyValuePairs = param.toString();
2250 thread->setParameters(keyValuePairs);
2251 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2252 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002253 }
2254}
2255
2256
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002257// ----------------------------------------------------------------------------
2258
Eric Laurent83b88082014-06-20 18:31:16 -07002259
Eric Laurent6acd1d42017-01-04 14:23:29 -08002260sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002261 audio_io_handle_t *output,
2262 audio_config_t *config,
2263 audio_devices_t devices,
2264 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002265 audio_output_flags_t flags)
2266{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002267 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002268 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002269 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002270 }
2271
Eric Laurentcf2c0212014-07-25 16:20:43 -07002272 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002273 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2274 } else {
2275 // Audio Policy does not currently request a specific output handle.
2276 // If this is ever needed, see openInput_l() for example code.
2277 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2278 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002279 }
Eric Laurent83b88082014-06-20 18:31:16 -07002280
2281 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2282
Eric Laurent83b88082014-06-20 18:31:16 -07002283 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002284 // This if statement allows overriding the audio policy settings
2285 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2286 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2287 // Check only for Normal Mixing mode
2288 if (kEnableExtendedPrecision) {
2289 // Specify format (uncomment one below to choose)
2290 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2291 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2292 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2293 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002294 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002295 }
2296 if (kEnableExtendedChannels) {
2297 // Specify channel mask (uncomment one below to choose)
2298 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2299 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2300 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2301 }
Eric Laurent83b88082014-06-20 18:31:16 -07002302 }
2303
Phil Burk062e67a2015-02-11 13:40:50 -08002304 AudioStreamOut *outputStream = NULL;
2305 status_t status = outHwDev->openOutputStream(
2306 &outputStream,
2307 *output,
2308 devices,
2309 flags,
2310 config,
2311 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002312
2313 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002314
Phil Burk062e67a2015-02-11 13:40:50 -08002315 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002316 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2317 sp<MmapPlaybackThread> thread =
2318 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2319 devices, AUDIO_DEVICE_NONE, mSystemReady);
2320 mMmapThreads.add(*output, thread);
2321 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2322 *output, thread.get());
2323 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002324 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002325 sp<PlaybackThread> thread;
2326 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2327 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2328 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2329 *output, thread.get());
2330 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2331 || !isValidPcmSinkFormat(config->format)
2332 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2333 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2334 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2335 *output, thread.get());
2336 } else {
2337 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2338 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2339 *output, thread.get());
2340 }
2341 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002342 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002343 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002344 }
Eric Laurent83b88082014-06-20 18:31:16 -07002345 }
2346
2347 return 0;
2348}
2349
Eric Laurentcf2c0212014-07-25 16:20:43 -07002350status_t AudioFlinger::openOutput(audio_module_handle_t module,
2351 audio_io_handle_t *output,
2352 audio_config_t *config,
2353 audio_devices_t *devices,
2354 const String8& address,
2355 uint32_t *latencyMs,
2356 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002358 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2359 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002360 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002361 (devices != NULL) ? *devices : 0,
2362 config->sample_rate,
2363 config->format,
2364 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002365 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002366
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002367 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002368 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002370
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 Mutex::Autolock _l(mLock);
2372
Eric Laurent6acd1d42017-01-04 14:23:29 -08002373 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002374 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002375 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2376 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2377 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378
Eric Laurent6acd1d42017-01-04 14:23:29 -08002379 // notify client processes of the new output creation
2380 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002381
Eric Laurent6acd1d42017-01-04 14:23:29 -08002382 // the first primary output opened designates the primary hw device
2383 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002384 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002385 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002386
Eric Laurent6acd1d42017-01-04 14:23:29 -08002387 AutoMutex lock(mHardwareLock);
2388 mHardwareStatus = AUDIO_HW_SET_MODE;
2389 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2390 mHardwareStatus = AUDIO_HW_IDLE;
2391 }
2392 } else {
2393 MmapThread *mmapThread = (MmapThread *)thread.get();
2394 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002395 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002396 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397 }
2398
Eric Laurentcf2c0212014-07-25 16:20:43 -07002399 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400}
2401
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002402audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2403 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404{
2405 Mutex::Autolock _l(mLock);
2406 MixerThread *thread1 = checkMixerThread_l(output1);
2407 MixerThread *thread2 = checkMixerThread_l(output2);
2408
2409 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002410 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2411 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002412 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413 }
2414
Glenn Kasteneeecb982016-02-26 10:44:04 -08002415 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002416 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 thread->addOutputTrack(thread2);
2418 mPlaybackThreads.add(id, thread);
2419 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002420 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 return id;
2422}
2423
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002424status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425{
Glenn Kastend96c5722012-04-25 13:44:49 -07002426 return closeOutput_nonvirtual(output);
2427}
2428
2429status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2430{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 // keep strong reference on the playback thread so that
2432 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002433 sp<PlaybackThread> playbackThread;
2434 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 {
2436 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002437 playbackThread = checkPlaybackThread_l(output);
2438 if (playbackThread != NULL) {
2439 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440
Andy Hungdc099c22018-09-18 13:46:39 -07002441 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002442
Eric Laurent6acd1d42017-01-04 14:23:29 -08002443 if (playbackThread->type() == ThreadBase::MIXER) {
2444 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2445 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2446 DuplicatingThread *dupThread =
2447 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2448 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2449 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002450 }
2451 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002452
2453
Eric Laurent6acd1d42017-01-04 14:23:29 -08002454 mPlaybackThreads.removeItem(output);
2455 // save all effects to the default thread
2456 if (mPlaybackThreads.size()) {
2457 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2458 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002459 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002460 Mutex::Autolock _dl(dstThread->mLock);
2461 Mutex::Autolock _sl(playbackThread->mLock);
2462 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2463 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002464 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002465 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002466 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467 }
2468 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002469 } else {
2470 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2471 if (mmapThread == 0) {
2472 return BAD_VALUE;
2473 }
Andy Hungdc099c22018-09-18 13:46:39 -07002474 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002475 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002476 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002478 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2479 ioDesc->mIoHandle = output;
2480 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002481 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002483 // The thread entity (active unit of execution) is no longer running here,
2484 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485
Eric Laurent6acd1d42017-01-04 14:23:29 -08002486 if (playbackThread != 0) {
2487 playbackThread->exit();
2488 if (!playbackThread->isDuplicating()) {
2489 closeOutputFinish(playbackThread);
2490 }
2491 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002492 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002493 mmapThread->exit();
2494 AudioStreamOut *out = mmapThread->clearOutput();
2495 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2496 // from now on thread->mOutput is NULL
2497 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 }
2499 return NO_ERROR;
2500}
2501
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002502void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002503{
2504 AudioStreamOut *out = thread->clearOutput();
2505 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2506 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002507 delete out;
2508}
2509
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002510void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002511{
2512 mPlaybackThreads.removeItem(thread->mId);
2513 thread->exit();
2514 closeOutputFinish(thread);
2515}
2516
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002517status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518{
2519 Mutex::Autolock _l(mLock);
2520 PlaybackThread *thread = checkPlaybackThread_l(output);
2521
2522 if (thread == NULL) {
2523 return BAD_VALUE;
2524 }
2525
Steve Block3856b092011-10-20 11:56:00 +01002526 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527 thread->suspend();
2528
2529 return NO_ERROR;
2530}
2531
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002532status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533{
2534 Mutex::Autolock _l(mLock);
2535 PlaybackThread *thread = checkPlaybackThread_l(output);
2536
2537 if (thread == NULL) {
2538 return BAD_VALUE;
2539 }
2540
Steve Block3856b092011-10-20 11:56:00 +01002541 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542
2543 thread->restore();
2544
2545 return NO_ERROR;
2546}
2547
Eric Laurentcf2c0212014-07-25 16:20:43 -07002548status_t AudioFlinger::openInput(audio_module_handle_t module,
2549 audio_io_handle_t *input,
2550 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002551 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002552 const String8& address,
2553 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002554 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555{
Eric Laurent83b88082014-06-20 18:31:16 -07002556 Mutex::Autolock _l(mLock);
2557
Glenn Kastene7d66712015-03-05 13:46:52 -08002558 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002559 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002560 }
2561
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002562 sp<ThreadBase> thread = openInput_l(
2563 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002564
2565 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002566 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002567 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002568 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002570 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002571}
Dima Zavin799a70e2011-04-18 16:57:27 -07002572
Eric Laurent6acd1d42017-01-04 14:23:29 -08002573sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002574 audio_io_handle_t *input,
2575 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002576 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002577 const String8& address,
2578 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002579 audio_input_flags_t flags,
2580 audio_devices_t outputDevice,
2581 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002582{
Glenn Kastene7d66712015-03-05 13:46:52 -08002583 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002584 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002585 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002586 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002587 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002588
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002589 // Some flags are specific to framework and must not leak to the HAL.
2590 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2591
Glenn Kasteneeecb982016-02-26 10:44:04 -08002592 // Audio Policy can request a specific handle for hardware hotword.
2593 // The goal here is not to re-open an already opened input.
2594 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002595 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002596 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2597 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2598 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2599 return 0;
2600 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2601 // This should not happen in a transient state with current design.
2602 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2603 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002604 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002605
Eric Laurentcf2c0212014-07-25 16:20:43 -07002606 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002607 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002608 sp<StreamInHalInterface> inStream;
2609 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002610 *input, devices, &halconfig, flags, address.string(), source,
2611 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002612 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2613 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002614 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002615 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002616 halconfig.sample_rate,
2617 halconfig.format,
2618 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002619 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002620 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002622 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002623 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002624 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002625 audio_is_linear_pcm(config->format) &&
2626 audio_is_linear_pcm(halconfig.format) &&
2627 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002628 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2629 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002630 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002631 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002632 inStream.clear();
2633 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002634 *input, devices, &halconfig, flags, address.string(), source,
2635 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002636 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 }
2638
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002639 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002640 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002641 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2642 sp<MmapCaptureThread> thread =
2643 new MmapCaptureThread(this, *input,
2644 inHwDev, inputStream,
2645 primaryOutputDevice_l(), devices, mSystemReady);
2646 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002647 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2648 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002649 return thread;
2650 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002651 // Start record thread
2652 // RecordThread requires both input and output device indication to forward to audio
2653 // pre processing modules
2654 sp<RecordThread> thread = new RecordThread(this,
2655 inputStream,
2656 *input,
2657 primaryOutputDevice_l(),
2658 devices,
2659 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002660 );
2661 mRecordThreads.add(*input, thread);
2662 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2663 return thread;
2664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665 }
2666
Eric Laurentcf2c0212014-07-25 16:20:43 -07002667 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 return 0;
2669}
2670
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002671status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672{
Glenn Kastend96c5722012-04-25 13:44:49 -07002673 return closeInput_nonvirtual(input);
2674}
2675
2676status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2677{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 // keep strong reference on the record thread so that
2679 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002680 sp<RecordThread> recordThread;
2681 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 {
2683 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002684 recordThread = checkRecordThread_l(input);
2685 if (recordThread != 0) {
2686 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687
Andy Hungdc099c22018-09-18 13:46:39 -07002688 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002689
Eric Laurent6acd1d42017-01-04 14:23:29 -08002690 // If we still have effect chains, it means that a client still holds a handle
2691 // on at least one effect. We must either move the chain to an existing thread with the
2692 // same session ID or put it aside in case a new record thread is opened for a
2693 // new capture on the same session
2694 sp<EffectChain> chain;
2695 {
2696 Mutex::Autolock _sl(recordThread->mLock);
2697 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2698 // Note: maximum one chain per record thread
2699 if (effectChains.size() != 0) {
2700 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002701 }
2702 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002703 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002704 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002705 // This should only happen in case of overlap between one thread tear down and the
2706 // creation of its replacement
2707 size_t i;
2708 for (i = 0; i < mRecordThreads.size(); i++) {
2709 sp<RecordThread> t = mRecordThreads.valueAt(i);
2710 if (t == recordThread) {
2711 continue;
2712 }
2713 if (t->hasAudioSession(chain->sessionId()) != 0) {
2714 Mutex::Autolock _l(t->mLock);
2715 ALOGV("closeInput() found thread %d for effect session %d",
2716 t->id(), chain->sessionId());
2717 t->addEffectChain_l(chain);
2718 break;
2719 }
2720 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002721 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002722 if (i == mRecordThreads.size()) {
2723 putOrphanEffectChain_l(chain);
2724 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002725 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002726 mRecordThreads.removeItem(input);
2727 } else {
2728 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2729 if (mmapThread == 0) {
2730 return BAD_VALUE;
2731 }
Andy Hungdc099c22018-09-18 13:46:39 -07002732 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002733 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002734 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002735 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2736 ioDesc->mIoHandle = input;
2737 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 }
Eric Laurent83b88082014-06-20 18:31:16 -07002739 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2740 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002741 if (recordThread != 0) {
2742 closeInputFinish(recordThread);
2743 } else if (mmapThread != 0) {
2744 mmapThread->exit();
2745 AudioStreamIn *in = mmapThread->clearInput();
2746 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2747 // from now on thread->mInput is NULL
2748 delete in;
2749 }
Eric Laurent83b88082014-06-20 18:31:16 -07002750 return NO_ERROR;
2751}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002753void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002754{
2755 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002756 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002757 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002758 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002759 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002760}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002762void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002763{
2764 mRecordThreads.removeItem(thread->mId);
2765 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766}
2767
Glenn Kastend2304db2014-02-03 07:40:31 -08002768status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769{
2770 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002771 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772
2773 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2774 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002775 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002776 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002777 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2778 mMmapThreads[i]->invalidateTracks(stream);
2779 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780 return NO_ERROR;
2781}
2782
2783
Glenn Kasteneeecb982016-02-26 10:44:04 -08002784audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785{
Glenn Kasten9d003132016-04-06 14:38:09 -07002786 // This is a binder API, so a malicious client could pass in a bad parameter.
2787 // Check for that before calling the internal API nextUniqueId().
2788 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2789 ALOGE("newAudioUniqueId invalid use %d", use);
2790 return AUDIO_UNIQUE_ID_ALLOCATE;
2791 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002792 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793}
2794
Glenn Kastend848eb42016-03-08 13:42:11 -08002795void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002796{
2797 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002798 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002799 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002800 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2801 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002802 caller = pid;
2803 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002804
Eric Laurent021cf962014-05-13 10:18:14 -07002805 {
2806 Mutex::Autolock _cl(mClientLock);
2807 // Ignore requests received from processes not known as notification client. The request
2808 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2809 // called from a different pid leaving a stale session reference. Also we don't know how
2810 // to clear this reference if the client process dies.
2811 if (mNotificationClients.indexOfKey(caller) < 0) {
2812 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2813 return;
2814 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002815 }
2816
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002817 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002818 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002819 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002820 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2821 ref->mCnt++;
2822 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002823 return;
2824 }
2825 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002826 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2827 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002828}
2829
Glenn Kastend848eb42016-03-08 13:42:11 -08002830void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002831{
Eric Laurent6c796322019-04-09 14:13:17 -07002832 std::vector< sp<EffectModule> > removedEffects;
2833 {
2834 Mutex::Autolock _l(mLock);
2835 pid_t caller = IPCThreadState::self()->getCallingPid();
2836 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2837 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2838 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2839 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002840 }
Eric Laurent6c796322019-04-09 14:13:17 -07002841 size_t num = mAudioSessionRefs.size();
2842 for (size_t i = 0; i < num; i++) {
2843 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2844 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2845 ref->mCnt--;
2846 ALOGV(" decremented refcount to %d", ref->mCnt);
2847 if (ref->mCnt == 0) {
2848 mAudioSessionRefs.removeAt(i);
2849 delete ref;
2850 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2851 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2852 }
2853 goto Exit;
2854 }
2855 }
2856 // If the caller is audioserver it is likely that the session being released was acquired
2857 // on behalf of a process not in notification clients and we ignore the warning.
2858 ALOGW_IF(!isAudioServerUid(callerUid),
2859 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002860 }
Eric Laurent6c796322019-04-09 14:13:17 -07002861
2862Exit:
2863 for (auto& effect : removedEffects) {
2864 effect->updatePolicyState();
2865 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002866}
2867
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002868bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2869{
2870 size_t num = mAudioSessionRefs.size();
2871 for (size_t i = 0; i < num; i++) {
2872 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2873 if (ref->mSessionid == audioSession) {
2874 return true;
2875 }
2876 }
2877 return false;
2878}
2879
Eric Laurent6c796322019-04-09 14:13:17 -07002880std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002881
Steve Block3856b092011-10-20 11:56:00 +01002882 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002883
2884 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002885 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002886
2887 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2888 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002889 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002890 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2891 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002892 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2893 chains.push(ec);
2894 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002895 }
2896 }
Eric Laurent6c796322019-04-09 14:13:17 -07002897
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002898 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2899 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002900 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002901 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2902 sp<EffectChain> ec = t->mEffectChains[j];
2903 chains.push(ec);
2904 }
2905 }
2906
Eric Laurent6c796322019-04-09 14:13:17 -07002907 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2908 sp<MmapThread> t = mMmapThreads.valueAt(i);
2909 Mutex::Autolock _l(t->mLock);
2910 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2911 sp<EffectChain> ec = t->mEffectChains[j];
2912 chains.push(ec);
2913 }
2914 }
2915
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002916 for (size_t i = 0; i < chains.size(); i++) {
2917 sp<EffectChain> ec = chains[i];
2918 int sessionid = ec->sessionId();
2919 sp<ThreadBase> t = ec->mThread.promote();
2920 if (t == 0) {
2921 continue;
2922 }
2923 size_t numsessionrefs = mAudioSessionRefs.size();
2924 bool found = false;
2925 for (size_t k = 0; k < numsessionrefs; k++) {
2926 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002927 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002928 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002929 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002930 found = true;
2931 break;
2932 }
2933 }
2934 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002935 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002936 // remove all effects from the chain
2937 while (ec->mEffects.size()) {
2938 sp<EffectModule> effect = ec->mEffects[0];
2939 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002940 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002941 if (effect->purgeHandles()) {
2942 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002943 }
Eric Laurent6c796322019-04-09 14:13:17 -07002944 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002945 }
2946 }
2947 }
Eric Laurent6c796322019-04-09 14:13:17 -07002948 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002949}
2950
Andy Hungdc099c22018-09-18 13:46:39 -07002951// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2952void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2953{
2954 audio_utils::FdToString fdToString;
2955 const int fd = fdToString.fd();
2956 if (fd >= 0) {
2957 thread->dump(fd, {} /* args */);
2958 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2959 }
2960}
2961
Glenn Kasteneeecb982016-02-26 10:44:04 -08002962// checkThread_l() must be called with AudioFlinger::mLock held
2963AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2964{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002965 ThreadBase *thread = checkMmapThread_l(ioHandle);
2966 if (thread == 0) {
2967 switch (audio_unique_id_get_use(ioHandle)) {
2968 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2969 thread = checkPlaybackThread_l(ioHandle);
2970 break;
2971 case AUDIO_UNIQUE_ID_USE_INPUT:
2972 thread = checkRecordThread_l(ioHandle);
2973 break;
2974 default:
2975 break;
2976 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002977 }
2978 return thread;
2979}
2980
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002982AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983{
Glenn Kastena1117922012-01-26 10:53:32 -08002984 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985}
2986
2987// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002988AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989{
2990 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002991 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992}
2993
2994// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002995AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002996{
Glenn Kastena1117922012-01-26 10:53:32 -08002997 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998}
2999
Eric Laurent6acd1d42017-01-04 14:23:29 -08003000// checkMmapThread_l() must be called with AudioFlinger::mLock held
3001AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3002{
3003 return mMmapThreads.valueFor(io).get();
3004}
3005
3006
3007// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3008AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3009{
Eric Laurent7459b902017-04-19 18:10:41 -07003010 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003011 if (volumeInterface == nullptr) {
3012 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3013 if (mmapThread != nullptr) {
3014 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003015 MmapPlaybackThread *mmapPlaybackThread =
3016 static_cast<MmapPlaybackThread *>(mmapThread);
3017 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003018 }
3019 }
3020 }
3021 return volumeInterface;
3022}
3023
3024Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3025{
3026 Vector <VolumeInterface *> volumeInterfaces;
3027 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003028 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003029 }
3030 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3031 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003032 MmapPlaybackThread *mmapPlaybackThread =
3033 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3034 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003035 }
3036 }
3037 return volumeInterfaces;
3038}
3039
Glenn Kasteneeecb982016-02-26 10:44:04 -08003040audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041{
Glenn Kasten9d003132016-04-06 14:38:09 -07003042 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003043 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003044 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3045 for (int retry = 0; retry < maxRetries; retry++) {
3046 // The cast allows wraparound from max positive to min negative instead of abort
3047 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3048 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3049 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3050 // allow wrap by skipping 0 and -1 for session ids
3051 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3052 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3053 return (audio_unique_id_t) (base | use);
3054 }
3055 }
3056 // We have no way of recovering from wraparound
3057 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3058 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059}
3060
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003061AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003062{
3063 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3064 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003065 if(thread->isDuplicating()) {
3066 continue;
3067 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003068 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003069 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003070 return thread;
3071 }
3072 }
3073 return NULL;
3074}
3075
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003076audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003077{
3078 PlaybackThread *thread = primaryPlaybackThread_l();
3079
3080 if (thread == NULL) {
3081 return 0;
3082 }
3083
Eric Laurentf1c04f92012-08-28 14:26:53 -07003084 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003085}
3086
Glenn Kastena7335632016-06-09 17:09:53 -07003087AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3088{
3089 size_t minFrameCount = 0;
3090 PlaybackThread *minThread = NULL;
3091 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3092 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3093 if (!thread->isDuplicating()) {
3094 size_t frameCount = thread->frameCountHAL();
3095 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3096 (frameCount == minFrameCount && thread->hasFastMixer() &&
3097 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3098 minFrameCount = frameCount;
3099 minThread = thread;
3100 }
3101 }
3102 }
3103 return minThread;
3104}
3105
Eric Laurenta011e352012-03-29 15:51:43 -07003106sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003107 audio_session_t triggerSession,
3108 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003109 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003110 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003111{
3112 Mutex::Autolock _l(mLock);
3113
3114 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3115 status_t playStatus = NAME_NOT_FOUND;
3116 status_t recStatus = NAME_NOT_FOUND;
3117 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3118 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3119 if (playStatus == NO_ERROR) {
3120 return event;
3121 }
3122 }
3123 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3124 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3125 if (recStatus == NO_ERROR) {
3126 return event;
3127 }
3128 }
3129 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3130 mPendingSyncEvents.add(event);
3131 } else {
3132 ALOGV("createSyncEvent() invalid event %d", event->type());
3133 event.clear();
3134 }
3135 return event;
3136}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003137
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138// ----------------------------------------------------------------------------
3139// Effect management
3140// ----------------------------------------------------------------------------
3141
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003142sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3143 return mEffectsFactoryHal;
3144}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145
Glenn Kastenf587ba52012-01-26 16:25:10 -08003146status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147{
3148 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003149 if (mEffectsFactoryHal.get()) {
3150 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3151 } else {
3152 return -ENODEV;
3153 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154}
3155
Glenn Kastenf587ba52012-01-26 16:25:10 -08003156status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157{
3158 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003159 if (mEffectsFactoryHal.get()) {
3160 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3161 } else {
3162 return -ENODEV;
3163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164}
3165
Glenn Kasten5e92a782012-01-30 07:40:52 -08003166status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003167 const effect_uuid_t *pTypeUuid,
3168 uint32_t preferredTypeFlag,
3169 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003171 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3172 return BAD_VALUE;
3173 }
3174
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003176
3177 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003178 return -ENODEV;
3179 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003181 status_t status = NO_ERROR;
3182 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3183 // If uuid is specified, request effect descriptor from that.
3184 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3185 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3186 // If uuid is not specified, look for an available implementation
3187 // of the required type instead.
3188
3189 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3190 effect_descriptor_t desc;
3191 desc.flags = 0; // prevent compiler warning
3192
3193 uint32_t numEffects = 0;
3194 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3195 if (status < 0) {
3196 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3197 return status;
3198 }
3199
3200 bool found = false;
3201 for (uint32_t i = 0; i < numEffects; i++) {
3202 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3203 if (status < 0) {
3204 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3205 continue;
3206 }
3207 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3208 // If matching type found save effect descriptor.
3209 found = true;
3210 *descriptor = desc;
3211
3212 // If there's no preferred flag or this descriptor matches the preferred
3213 // flag, success! If this descriptor doesn't match the preferred
3214 // flag, continue enumeration in case a better matching version of this
3215 // effect type is available. Note that this means if no effect with a
3216 // correct flag is found, the descriptor returned will correspond to the
3217 // last effect that at least had a matching type uuid (if any).
3218 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3219 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3220 break;
3221 }
3222 }
3223 }
3224
3225 if (!found) {
3226 status = NAME_NOT_FOUND;
3227 ALOGW("getEffectDescriptor(): Effect not found by type.");
3228 }
3229 } else {
3230 status = BAD_VALUE;
3231 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3232 }
3233 return status;
3234}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003236sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 effect_descriptor_t *pDesc,
3238 const sp<IEffectClient>& effectClient,
3239 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003240 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003241 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003242 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003243 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 status_t *status,
3245 int *id,
3246 int *enabled)
3247{
3248 status_t lStatus = NO_ERROR;
3249 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251
Eric Laurentb6436272016-12-07 19:24:50 -08003252 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003253 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003254 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3255 ALOGW_IF(pid != -1 && pid != callingPid,
3256 "%s uid %d pid %d tried to pass itself off as pid %d",
3257 __func__, callingUid, callingPid, pid);
3258 pid = callingPid;
3259 }
3260
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003261 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3262 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263
3264 if (pDesc == NULL) {
3265 lStatus = BAD_VALUE;
3266 goto Exit;
3267 }
3268
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003269 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003270 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003271 lStatus = NO_INIT;
3272 goto Exit;
3273 }
3274
Andy Hung6096dcd2019-03-13 13:20:30 -07003275 // check audio settings permission for global effects
3276 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3277 if (!settingsAllowed()) {
3278 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3279 lStatus = PERMISSION_DENIED;
3280 goto Exit;
3281 }
3282 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3283 if (!isAudioServerUid(callingUid)) {
3284 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3285 lStatus = PERMISSION_DENIED;
3286 goto Exit;
3287 }
3288
3289 if (io == AUDIO_IO_HANDLE_NONE) {
3290 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3291 lStatus = BAD_VALUE;
3292 goto Exit;
3293 }
3294 } else {
3295 // general sessionId.
3296
3297 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3298 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3299 lStatus = BAD_VALUE;
3300 goto Exit;
3301 }
3302
3303 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3304 // to prevent creating an effect when one doesn't actually have track with that session?
3305 }
3306
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003308 // Get the full effect descriptor from the uuid/type.
3309 // If the session is the output mix, prefer an auxiliary effect,
3310 // otherwise no preference.
3311 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3312 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3313 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3314 if (lStatus < 0) {
3315 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3316 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 }
3318
3319 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003320 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3322 lStatus = INVALID_OPERATION;
3323 goto Exit;
3324 }
3325
Eric Laurent59255e42011-07-27 19:49:51 -07003326 // check recording permission for visualizer
3327 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003328 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003329 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003330 lStatus = PERMISSION_DENIED;
3331 goto Exit;
3332 }
3333
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003335 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003336 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003337 // if the output returned by getOutputForEffect() is removed before we lock the
3338 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3339 // and we will exit safely
3340 io = AudioSystem::getOutputForEffect(&desc);
3341 ALOGV("createEffect got output %d", io);
3342 }
3343
3344 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345
3346 // If output is not specified try to find a matching audio session ID in one of the
3347 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003348 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3349 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003350 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3351 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003352 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003353 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003354 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3355 if (io == AUDIO_IO_HANDLE_NONE) {
3356 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003358 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003359 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003360 }
Andy Hung444bb552019-03-14 17:06:39 -07003361
3362 // If you wish to create a Record preprocessing AudioEffect in Java,
3363 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3364 // Otherwise it will fail when created on a Playback thread by legacy
3365 // handling below. Ditto with Mmap, the associated Mmap track must be created
3366 // before creating the AudioEffect or the io handle must be specified.
3367 //
3368 // Detect if the effect is created after an AudioRecord is destroyed.
3369 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3370 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3371 " for session %d no longer exists",
3372 __func__, desc.name, sessionId);
3373 lStatus = PERMISSION_DENIED;
3374 goto Exit;
3375 }
3376
3377 // Legacy handling of creating an effect on an expired or made-up
3378 // session id. We think that it is a Playback effect.
3379 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003380 // If no output thread contains the requested session ID, default to
3381 // first output. The effect chain will be moved to the correct output
3382 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003383 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003384 io = mPlaybackThreads.keyAt(0);
3385 }
Steve Block3856b092011-10-20 11:56:00 +01003386 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003387 } else if (checkPlaybackThread_l(io) != nullptr) {
3388 // allow only one effect chain per sessionId on mPlaybackThreads.
3389 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3390 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3391 if (io == checkIo) continue;
3392 const uint32_t sessionType =
3393 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3394 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3395 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3396 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3397 android_errorWriteLog(0x534e4554, "123237974");
3398 lStatus = BAD_VALUE;
3399 goto Exit;
3400 }
3401 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003402 }
3403 ThreadBase *thread = checkRecordThread_l(io);
3404 if (thread == NULL) {
3405 thread = checkPlaybackThread_l(io);
3406 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003407 thread = checkMmapThread_l(io);
3408 if (thread == NULL) {
3409 ALOGE("createEffect() unknown output thread");
3410 lStatus = BAD_VALUE;
3411 goto Exit;
3412 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003413 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003414 } else {
3415 // Check if one effect chain was awaiting for an effect to be created on this
3416 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003417 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003418 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003419 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003420 thread->addEffectChain_l(chain);
3421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003423
Eric Laurent021cf962014-05-13 10:18:14 -07003424 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003426 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003427 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003428 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003429 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003430 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003431 // remove local strong reference to Client with mClientLock held
3432 Mutex::Autolock _cl(mClientLock);
3433 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003434 } else {
3435 // handle must be valid here, but check again to be safe.
3436 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003437 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 }
3439
Eric Laurent6c796322019-04-09 14:13:17 -07003440 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3441 // Check CPU and memory usage
3442 sp<EffectModule> effect = handle->effect().promote();
3443 if (effect != nullptr) {
3444 status_t rStatus = effect->updatePolicyState();
3445 if (rStatus != NO_ERROR) {
3446 lStatus = rStatus;
3447 }
3448 }
3449 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003450 handle.clear();
3451 }
3452
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003454 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 return handle;
3456}
3457
Glenn Kastend848eb42016-03-08 13:42:11 -08003458status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003459 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003460{
Steve Block3856b092011-10-20 11:56:00 +01003461 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003462 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003463 Mutex::Autolock _l(mLock);
3464 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003465 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003466 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467 }
Eric Laurentde070132010-07-13 04:45:46 -07003468 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3469 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003470 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003471 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 }
Eric Laurentde070132010-07-13 04:45:46 -07003473 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3474 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003475 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003476 return BAD_VALUE;
3477 }
3478
3479 Mutex::Autolock _dl(dstThread->mLock);
3480 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003481 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482}
3483
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003484
3485void AudioFlinger::setEffectSuspended(int effectId,
3486 audio_session_t sessionId,
3487 bool suspended)
3488{
3489 Mutex::Autolock _l(mLock);
3490
3491 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3492 if (thread == nullptr) {
3493 return;
3494 }
3495 Mutex::Autolock _sl(thread->mLock);
3496 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3497 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3498}
3499
3500
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003501// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003502status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003503 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003504 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003505{
Steve Block3856b092011-10-20 11:56:00 +01003506 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003507 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003508
Eric Laurent59255e42011-07-27 19:49:51 -07003509 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003510 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003511 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003512 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003513 return INVALID_OPERATION;
3514 }
3515
Eric Laurent4c415062016-06-17 16:14:16 -07003516 // Check whether the destination thread and all effects in the chain are compatible
3517 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003518 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003519 " destination thread %p is not compatible with effects in the chain",
3520 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003521 return INVALID_OPERATION;
3522 }
3523
Eric Laurent39e94f82010-07-28 01:32:47 -07003524 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003525 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003526 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003527 // removed.
3528 srcThread->removeEffectChain_l(chain);
3529
3530 // transfer all effects one by one so that new effect chain is created on new thread with
3531 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003532 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003533 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003534 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003535 Vector< sp<EffectModule> > removed;
3536 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003537 while (effect != 0) {
3538 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003539 removed.add(effect);
3540 status = dstThread->addEffect_l(effect);
3541 if (status != NO_ERROR) {
3542 break;
3543 }
Eric Laurentec35a142011-10-05 17:42:25 -07003544 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3545 if (effect->state() == EffectModule::ACTIVE ||
3546 effect->state() == EffectModule::STOPPING) {
3547 effect->start();
3548 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003549 // if the move request is not received from audio policy manager, the effect must be
3550 // re-registered with the new strategy and output
3551 if (dstChain == 0) {
3552 dstChain = effect->chain().promote();
3553 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003554 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003555 status = NO_INIT;
3556 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003557 }
3558 strategy = dstChain->strategy();
3559 }
Eric Laurentde070132010-07-13 04:45:46 -07003560 effect = chain->getEffectFromId_l(0);
3561 }
3562
Eric Laurent5baf2af2013-09-12 17:37:00 -07003563 if (status != NO_ERROR) {
3564 for (size_t i = 0; i < removed.size(); i++) {
3565 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003566 }
3567 }
3568
3569 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570}
3571
Eric Laurent6c796322019-04-09 14:13:17 -07003572status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3573 const sp<PlaybackThread>& dstThread,
3574 sp<PlaybackThread> *srcThread)
3575{
3576 status_t status = NO_ERROR;
3577 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003578 sp<PlaybackThread> thread =
3579 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003580
3581 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3582 Mutex::Autolock _dl(dstThread->mLock);
3583 Mutex::Autolock _sl(thread->mLock);
3584 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3585 sp<EffectChain> dstChain;
3586 if (srcChain == 0) {
3587 return INVALID_OPERATION;
3588 }
3589
3590 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3591 if (effect == 0) {
3592 return INVALID_OPERATION;
3593 }
3594 thread->removeEffect_l(effect);
3595 status = dstThread->addEffect_l(effect);
3596 if (status != NO_ERROR) {
3597 thread->addEffect_l(effect);
3598 status = INVALID_OPERATION;
3599 goto Exit;
3600 }
3601
3602 dstChain = effect->chain().promote();
3603 if (dstChain == 0) {
3604 thread->addEffect_l(effect);
3605 status = INVALID_OPERATION;
3606 }
3607
3608Exit:
3609 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3610 if (effect->state() == EffectModule::ACTIVE ||
3611 effect->state() == EffectModule::STOPPING) {
3612 effect->start();
3613 }
3614 }
3615
3616 if (status == NO_ERROR && srcThread != nullptr) {
3617 *srcThread = thread;
3618 }
3619 return status;
3620}
3621
Eric Laurent5baf2af2013-09-12 17:37:00 -07003622bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003623{
3624 if (mGlobalEffectEnableTime != 0 &&
3625 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3626 return true;
3627 }
3628
3629 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3630 sp<EffectChain> ec =
3631 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003632 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003633 return true;
3634 }
3635 }
3636 return false;
3637}
3638
Eric Laurent5baf2af2013-09-12 17:37:00 -07003639void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003640{
3641 Mutex::Autolock _l(mLock);
3642
3643 mGlobalEffectEnableTime = systemTime();
3644
3645 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3646 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3647 if (t->mType == ThreadBase::OFFLOAD) {
3648 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3649 }
3650 }
3651
3652}
3653
Eric Laurentaaa44472014-09-12 17:41:50 -07003654status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3655{
Eric Laurentd8365c52017-07-16 15:27:05 -07003656 // clear possible suspended state before parking the chain so that it starts in default state
3657 // when attached to a new record thread
3658 chain->setEffectSuspended_l(FX_IID_AEC, false);
3659 chain->setEffectSuspended_l(FX_IID_NS, false);
3660
Glenn Kastend848eb42016-03-08 13:42:11 -08003661 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003662 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003663 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003664 if (index >= 0) {
3665 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3666 return ALREADY_EXISTS;
3667 }
3668 mOrphanEffectChains.add(session, chain);
3669 return NO_ERROR;
3670}
3671
3672sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3673{
3674 sp<EffectChain> chain;
3675 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003676 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003677 if (index >= 0) {
3678 chain = mOrphanEffectChains.valueAt(index);
3679 mOrphanEffectChains.removeItemsAt(index);
3680 }
3681 return chain;
3682}
3683
3684bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3685{
3686 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003687 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003688 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003689 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003690 if (index >= 0) {
3691 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003692 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003693 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003694 mOrphanEffectChains.removeItemsAt(index);
3695 }
3696 return true;
3697 }
3698 return false;
3699}
3700
3701
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702// ----------------------------------------------------------------------------
3703
3704status_t AudioFlinger::onTransact(
3705 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3706{
3707 return BnAudioFlinger::onTransact(code, data, reply, flags);
3708}
3709
Glenn Kasten63238ef2015-03-02 15:50:29 -08003710} // namespace android