blob: 0825cb4c339c196a3e18d52550f2e60abcb15cb1 [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;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700690 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800691 ALOGW_IF(clientUid != callingUid,
692 "%s uid %d tried to pass itself off as %d",
693 __FUNCTION__, callingUid, clientUid);
694 clientUid = callingUid;
695 updatePid = true;
696 }
697 pid_t clientPid = input.clientInfo.clientPid;
698 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700699 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800700 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700701 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800702 __func__, callingUid, callingPid, clientPid);
703 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700704 }
705
Eric Laurent21da6472017-11-09 16:29:26 -0800706 audio_session_t sessionId = input.sessionId;
707 if (sessionId == AUDIO_SESSION_ALLOCATE) {
708 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800709 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
710 lStatus = BAD_VALUE;
711 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800712 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800713
Eric Laurent21da6472017-11-09 16:29:26 -0800714 output.sessionId = sessionId;
715 output.outputId = AUDIO_IO_HANDLE_NONE;
716 output.selectedDeviceId = input.selectedDeviceId;
717
718 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200719 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800720 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800721
722 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
723 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
724 goto Exit;
725 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800726 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
727 // but if someone uses binder directly they could bypass that and cause us to crash
728 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000729 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 lStatus = BAD_VALUE;
731 goto Exit;
732 }
733
Glenn Kasten53b5d092014-02-05 10:00:23 -0800734 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800735 if (!audio_is_output_channel(input.config.channel_mask)) {
736 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800737 lStatus = BAD_VALUE;
738 goto Exit;
739 }
740
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700741 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800742 if (!audio_is_valid_format(input.config.format)) {
743 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700744 lStatus = BAD_VALUE;
745 goto Exit;
746 }
747
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 {
749 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800750 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800752 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753 lStatus = BAD_VALUE;
754 goto Exit;
755 }
756
Eric Laurent21da6472017-11-09 16:29:26 -0800757 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758
Glenn Kastene848bd92014-03-13 15:00:32 -0700759 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800760 // check if an effect chain with the same session ID is present on another
761 // output thread and move it here.
762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
763 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
764 if (mPlaybackThreads.keyAt(i) != output.outputId) {
765 uint32_t sessions = t->hasAudioSession(sessionId);
766 if (sessions & ThreadBase::EFFECT_SESSION) {
767 effectThread = t.get();
768 break;
Eric Laurentde070132010-07-13 04:45:46 -0700769 }
770 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771 }
Eric Laurent21da6472017-11-09 16:29:26 -0800772 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773
Eric Laurent21da6472017-11-09 16:29:26 -0800774 output.sampleRate = input.config.sample_rate;
775 output.frameCount = input.frameCount;
776 output.notificationFrameCount = input.notificationFrameCount;
777 output.flags = input.flags;
778
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700779 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
780 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800781 &output.frameCount, &output.notificationFrameCount,
782 input.notificationsPerBuffer, input.speed,
783 input.sharedBuffer, sessionId, &output.flags,
784 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800785 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700786 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700787
Eric Laurent21da6472017-11-09 16:29:26 -0800788 output.afFrameCount = thread->frameCount();
789 output.afSampleRate = thread->sampleRate();
790 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800791 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800792
Kevin Rocard153f92d2018-12-18 18:33:28 -0800793 if (lStatus == NO_ERROR) {
794 // Connect secondary outputs. Failure on a secondary output must not imped the primary
795 // Any secondary output setup failure will lead to a desync between the AP and AF until
796 // the track is destroyed.
797 TeePatches teePatches;
798 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
799 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
800 if (secondaryThread == NULL) {
801 ALOGE("no playback thread found for secondary output %d", output.outputId);
802 continue;
803 }
804
805 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
806
807 using namespace std::chrono_literals;
808 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
809 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
810 output.sampleRate,
811 inChannelMask,
812 input.config.format,
813 frameCount,
814 NULL /* buffer */,
815 (size_t)0 /* bufferSize */,
816 AUDIO_INPUT_FLAG_DIRECT,
817 0ns /* timeout */);
818 status_t status = patchRecord->initCheck();
819 if (status != NO_ERROR) {
820 ALOGE("Secondary output patchRecord init failed: %d", status);
821 continue;
822 }
823 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
824 streamType,
825 output.sampleRate,
826 input.config.channel_mask,
827 input.config.format,
828 frameCount,
829 patchRecord->buffer(),
830 patchRecord->bufferSize(),
831 output.flags,
832 0ns /* timeout */);
833 status = patchTrack->initCheck();
834 if (status != NO_ERROR) {
835 ALOGE("Secondary output patchTrack init failed: %d", status);
836 continue;
837 }
838 teePatches.push_back({patchRecord, patchTrack});
839 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800840 // In case the downstream patchTrack on the secondaryThread temporarily outlives
841 // our created track, ensure the corresponding patchRecord is still alive.
842 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
843 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800844 }
845 track->setTeePatches(std::move(teePatches));
846 }
847
Eric Laurent39e94f82010-07-28 01:32:47 -0700848 // move effect chain to this output thread if an effect on same session was waiting
849 // for a track to be created
850 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700851 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700852 Mutex::Autolock _dl(thread->mLock);
853 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800854 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700855 }
Eric Laurenta011e352012-03-29 15:51:43 -0700856
857 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700858 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800859 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700860 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700861 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700862 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700863 } else {
864 mPendingSyncEvents[i]->cancel();
865 }
Eric Laurenta011e352012-03-29 15:51:43 -0700866 mPendingSyncEvents.removeAt(i);
867 i--;
868 }
869 }
870 }
Glenn Kastene198c362013-08-13 09:13:36 -0700871
Eric Laurent21da6472017-11-09 16:29:26 -0800872 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873 }
Glenn Kastene198c362013-08-13 09:13:36 -0700874
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700875 if (lStatus != NO_ERROR) {
876 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700877 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700878 // Don't hold mClientLock when releasing the reference on the track as the
879 // destructor will acquire it.
880 {
881 Mutex::Autolock _cl(mClientLock);
882 client.clear();
883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700885 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700886 }
887
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700888 // return handle to client
889 trackHandle = new TrackHandle(track);
890
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800892 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700893 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800894 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700895 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 return trackHandle;
897}
898
Glenn Kasten2c073da2016-02-26 09:14:08 -0800899uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900{
901 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800902 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800904 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 return 0;
906 }
907 return thread->sampleRate();
908}
909
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800910audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911{
912 Mutex::Autolock _l(mLock);
913 PlaybackThread *thread = checkPlaybackThread_l(output);
914 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000915 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800916 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918 return thread->format();
919}
920
Glenn Kasten2c073da2016-02-26 09:14:08 -0800921size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922{
923 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800924 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800926 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 return 0;
928 }
Glenn Kasten58912562012-04-03 10:45:00 -0700929 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
930 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 return thread->frameCount();
932}
933
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700934size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
935{
936 Mutex::Autolock _l(mLock);
937 ThreadBase *thread = checkThread_l(ioHandle);
938 if (thread == NULL) {
939 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
940 return 0;
941 }
942 return thread->frameCountHAL();
943}
944
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800945uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946{
947 Mutex::Autolock _l(mLock);
948 PlaybackThread *thread = checkPlaybackThread_l(output);
949 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800950 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951 return 0;
952 }
953 return thread->latency();
954}
955
956status_t AudioFlinger::setMasterVolume(float value)
957{
Eric Laurenta1884f92011-08-23 08:25:03 -0700958 status_t ret = initCheck();
959 if (ret != NO_ERROR) {
960 return ret;
961 }
962
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 // check calling permissions
964 if (!settingsAllowed()) {
965 return PERMISSION_DENIED;
966 }
967
Eric Laurenta4c5a552012-03-29 10:12:40 -0700968 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700969 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700970
John Grossmanee578c02012-07-23 17:05:46 -0700971 // Set master volume in the HALs which support it.
972 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
973 AutoMutex lock(mHardwareLock);
974 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800975
John Grossmanee578c02012-07-23 17:05:46 -0700976 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
977 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700978 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800979 }
John Grossmanee578c02012-07-23 17:05:46 -0700980 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982
John Grossmanee578c02012-07-23 17:05:46 -0700983 // Now set the master volume in each playback thread. Playback threads
984 // assigned to HALs which do not have master volume support will apply
985 // master volume during the mix operation. Threads with HALs which do
986 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700987 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
988 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
989 continue;
990 }
John Grossmanee578c02012-07-23 17:05:46 -0700991 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993
994 return NO_ERROR;
995}
996
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100997status_t AudioFlinger::setMasterBalance(float balance)
998{
999 status_t ret = initCheck();
1000 if (ret != NO_ERROR) {
1001 return ret;
1002 }
1003
1004 // check calling permissions
1005 if (!settingsAllowed()) {
1006 return PERMISSION_DENIED;
1007 }
1008
1009 // check range
1010 if (isnan(balance) || fabs(balance) > 1.f) {
1011 return BAD_VALUE;
1012 }
1013
1014 Mutex::Autolock _l(mLock);
1015
1016 // short cut.
1017 if (mMasterBalance == balance) return NO_ERROR;
1018
1019 mMasterBalance = balance;
1020
1021 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1022 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1023 continue;
1024 }
1025 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1026 }
1027
1028 return NO_ERROR;
1029}
1030
Glenn Kastenf78aee72012-01-04 11:00:47 -08001031status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032{
Eric Laurenta1884f92011-08-23 08:25:03 -07001033 status_t ret = initCheck();
1034 if (ret != NO_ERROR) {
1035 return ret;
1036 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037
1038 // check calling permissions
1039 if (!settingsAllowed()) {
1040 return PERMISSION_DENIED;
1041 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001042 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001043 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044 return BAD_VALUE;
1045 }
1046
1047 { // scope for the lock
1048 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001049 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001051 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052 mHardwareStatus = AUDIO_HW_IDLE;
1053 }
1054
1055 if (NO_ERROR == ret) {
1056 Mutex::Autolock _l(mLock);
1057 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001058 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001059 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 }
1061
1062 return ret;
1063}
1064
1065status_t AudioFlinger::setMicMute(bool state)
1066{
Eric Laurenta1884f92011-08-23 08:25:03 -07001067 status_t ret = initCheck();
1068 if (ret != NO_ERROR) {
1069 return ret;
1070 }
1071
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 // check calling permissions
1073 if (!settingsAllowed()) {
1074 return PERMISSION_DENIED;
1075 }
1076
1077 AutoMutex lock(mHardwareLock);
1078 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001079 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001080 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1081 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001082 if (result != NO_ERROR) {
1083 ret = result;
1084 }
1085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 mHardwareStatus = AUDIO_HW_IDLE;
1087 return ret;
1088}
1089
1090bool AudioFlinger::getMicMute() const
1091{
Eric Laurenta1884f92011-08-23 08:25:03 -07001092 status_t ret = initCheck();
1093 if (ret != NO_ERROR) {
1094 return false;
1095 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001096 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001097 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001098 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001100 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001101 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1102 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001103 if (result == NO_ERROR) {
1104 mute = mute && state;
1105 }
1106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001108
1109 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110}
1111
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001112void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1113{
1114 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1115
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001116 AutoMutex lock(mLock);
1117 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001118 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1119 }
1120 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1121 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001122 }
1123}
1124
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125status_t AudioFlinger::setMasterMute(bool muted)
1126{
John Grossmand8f178d2012-07-20 14:51:35 -07001127 status_t ret = initCheck();
1128 if (ret != NO_ERROR) {
1129 return ret;
1130 }
1131
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 // check calling permissions
1133 if (!settingsAllowed()) {
1134 return PERMISSION_DENIED;
1135 }
1136
John Grossmanee578c02012-07-23 17:05:46 -07001137 Mutex::Autolock _l(mLock);
1138 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001139
John Grossmanee578c02012-07-23 17:05:46 -07001140 // Set master mute in the HALs which support it.
1141 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1142 AutoMutex lock(mHardwareLock);
1143 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001144
John Grossmanee578c02012-07-23 17:05:46 -07001145 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1146 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001147 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001148 }
John Grossmanee578c02012-07-23 17:05:46 -07001149 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001150 }
1151
John Grossmanee578c02012-07-23 17:05:46 -07001152 // Now set the master mute in each playback thread. Playback threads
1153 // assigned to HALs which do not have master mute support will apply master
1154 // mute during the mix operation. Threads with HALs which do support master
1155 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001156 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1157 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1158 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001159 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160
1161 return NO_ERROR;
1162}
1163
1164float AudioFlinger::masterVolume() const
1165{
Glenn Kasten98067102011-12-13 11:47:54 -08001166 Mutex::Autolock _l(mLock);
1167 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168}
1169
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001170status_t AudioFlinger::getMasterBalance(float *balance) const
1171{
1172 Mutex::Autolock _l(mLock);
1173 *balance = getMasterBalance_l();
1174 return NO_ERROR; // if called through binder, may return a transactional error
1175}
1176
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177bool AudioFlinger::masterMute() const
1178{
Glenn Kasten98067102011-12-13 11:47:54 -08001179 Mutex::Autolock _l(mLock);
1180 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181}
1182
John Grossman4ff14ba2012-02-08 16:37:41 -08001183float AudioFlinger::masterVolume_l() const
1184{
John Grossman4ff14ba2012-02-08 16:37:41 -08001185 return mMasterVolume;
1186}
1187
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001188float AudioFlinger::getMasterBalance_l() const
1189{
1190 return mMasterBalance;
1191}
1192
John Grossmand8f178d2012-07-20 14:51:35 -07001193bool AudioFlinger::masterMute_l() const
1194{
John Grossmanee578c02012-07-23 17:05:46 -07001195 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001196}
1197
Eric Laurent223fd5c2014-11-11 13:43:36 -08001198status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1199{
1200 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001201 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001202 return BAD_VALUE;
1203 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001204 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1205 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1206 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001207 return PERMISSION_DENIED;
1208 }
1209
1210 return NO_ERROR;
1211}
1212
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001213status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1214 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215{
1216 // check calling permissions
1217 if (!settingsAllowed()) {
1218 return PERMISSION_DENIED;
1219 }
1220
Eric Laurent223fd5c2014-11-11 13:43:36 -08001221 status_t status = checkStreamType(stream);
1222 if (status != NO_ERROR) {
1223 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 }
Eric Laurent98e38192018-02-15 18:31:53 -08001225 if (output == AUDIO_IO_HANDLE_NONE) {
1226 return BAD_VALUE;
1227 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001228 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229
1230 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001231 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1232 if (volumeInterface == NULL) {
1233 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 }
Eric Laurent98e38192018-02-15 18:31:53 -08001235 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236
1237 return NO_ERROR;
1238}
1239
Glenn Kastenfff6d712012-01-12 16:38:12 -08001240status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241{
1242 // check calling permissions
1243 if (!settingsAllowed()) {
1244 return PERMISSION_DENIED;
1245 }
1246
Eric Laurent223fd5c2014-11-11 13:43:36 -08001247 status_t status = checkStreamType(stream);
1248 if (status != NO_ERROR) {
1249 return status;
1250 }
1251 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1252
1253 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001254 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255 return BAD_VALUE;
1256 }
1257
Eric Laurent93575202011-01-18 18:39:02 -08001258 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001259 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001260 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1261 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1262 volumeInterfaces[i]->setStreamMute(stream, muted);
1263 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264
1265 return NO_ERROR;
1266}
1267
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001268float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001270 status_t status = checkStreamType(stream);
1271 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 return 0.0f;
1273 }
Eric Laurent98e38192018-02-15 18:31:53 -08001274 if (output == AUDIO_IO_HANDLE_NONE) {
1275 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276 }
1277
Eric Laurent98e38192018-02-15 18:31:53 -08001278 AutoMutex lock(mLock);
1279 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1280 if (volumeInterface == NULL) {
1281 return 0.0f;
1282 }
1283
1284 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285}
1286
Glenn Kastenfff6d712012-01-12 16:38:12 -08001287bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001289 status_t status = checkStreamType(stream);
1290 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291 return true;
1292 }
1293
Glenn Kasten6637baa2012-01-09 09:40:36 -08001294 AutoMutex lock(mLock);
1295 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296}
1297
Eric Laurent054d9d32015-04-24 08:48:48 -07001298
1299void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1300{
1301 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1302 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1303 }
1304}
1305
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001306// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1307void AudioFlinger::forwardParametersToDownstreamPatches_l(
1308 audio_io_handle_t upStream, const String8& keyValuePairs,
1309 std::function<bool(const sp<PlaybackThread>&)> useThread)
1310{
1311 std::vector<PatchPanel::SoftwarePatch> swPatches;
1312 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1313 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1314 __func__, swPatches.size(), upStream);
1315 for (const auto& swPatch : swPatches) {
1316 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1317 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1318 downStream->setParameters(keyValuePairs);
1319 }
1320 }
1321}
1322
Eric Laurentf1047e82018-04-16 19:18:20 -07001323// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1324// Some keys are used for audio routing and audio path configuration and should be reserved for use
1325// by audio policy and audio flinger for functional, privacy and security reasons.
1326void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1327{
1328 static const String8 kReservedParameters[] = {
1329 String8(AudioParameter::keyRouting),
1330 String8(AudioParameter::keySamplingRate),
1331 String8(AudioParameter::keyFormat),
1332 String8(AudioParameter::keyChannels),
1333 String8(AudioParameter::keyFrameCount),
1334 String8(AudioParameter::keyInputSource),
1335 String8(AudioParameter::keyMonoOutput),
1336 String8(AudioParameter::keyStreamConnect),
1337 String8(AudioParameter::keyStreamDisconnect),
1338 String8(AudioParameter::keyStreamSupportedFormats),
1339 String8(AudioParameter::keyStreamSupportedChannels),
1340 String8(AudioParameter::keyStreamSupportedSamplingRates),
1341 };
1342
Andy Hung4ef19fa2018-05-15 19:35:29 -07001343 if (isAudioServerUid(callingUid)) {
1344 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001345 }
1346
1347 AudioParameter param = AudioParameter(keyValuePairs);
1348 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001349 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001350 for (auto& key : kReservedParameters) {
1351 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001352 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001353 param.remove(key);
1354 }
1355 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001356 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1357 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001358 keyValuePairs = param.toString();
1359}
1360
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001361void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1362 size_t rejectedKVPSize, const String8& rejectedKVPs,
1363 uid_t callingUid) {
1364 auto prefix = String8::format("UID %5d", callingUid);
1365 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1366 if (rejectedKVPSize != 0) {
1367 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1368 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1369 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1370 } else {
1371 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1372 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1373 }
1374}
1375
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001376status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377{
Eric Laurentf1047e82018-04-16 19:18:20 -07001378 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1379 ioHandle, keyValuePairs.string(),
1380 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001381
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382 // check calling permissions
1383 if (!settingsAllowed()) {
1384 return PERMISSION_DENIED;
1385 }
1386
Eric Laurentf1047e82018-04-16 19:18:20 -07001387 String8 filteredKeyValuePairs = keyValuePairs;
1388 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1389
1390 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1391
Glenn Kasten142f5192014-03-25 17:44:59 -07001392 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1393 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001394 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001395 // result will remain NO_INIT if no audio device is present
1396 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001397 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001398 AutoMutex lock(mHardwareLock);
1399 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1400 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001401 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001402 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001403 // return success if at least one audio device accepts the parameters as not all
1404 // HALs are requested to support all parameters. If no audio device supports the
1405 // requested parameters, the last error is reported.
1406 if (final_result != NO_ERROR) {
1407 final_result = result;
1408 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001409 }
1410 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001411 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001412 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001413 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001414 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001415 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1416 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001417 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001418 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001419 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001420 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001421 }
1422 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001423 String8 screenState;
1424 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001425 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001426 if (isOff != (AudioFlinger::mScreenState & 1)) {
1427 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001428 }
1429 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001430 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 }
1432
1433 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1434 // and the thread is exited once the lock is released
1435 sp<ThreadBase> thread;
1436 {
1437 Mutex::Autolock _l(mLock);
1438 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001439 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001441 if (thread == 0) {
1442 thread = checkMmapThread_l(ioHandle);
1443 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001444 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001445 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001446 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001447 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001448 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1449 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001450 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452 }
1453 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001454 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001455 status_t result = thread->setParameters(filteredKeyValuePairs);
1456 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1457 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458 }
1459 return BAD_VALUE;
1460}
1461
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001462String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001464 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1465 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466
Eric Laurenta4c5a552012-03-29 10:12:40 -07001467 Mutex::Autolock _l(mLock);
1468
Glenn Kasten142f5192014-03-25 17:44:59 -07001469 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001470 String8 out_s8;
1471
Dima Zavin799a70e2011-04-18 16:57:27 -07001472 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001473 String8 s;
1474 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001475 {
1476 AutoMutex lock(mHardwareLock);
1477 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001478 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1479 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001480 mHardwareStatus = AUDIO_HW_IDLE;
1481 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001482 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001483 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001484 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 }
1486
Eric Laurent6acd1d42017-01-04 14:23:29 -08001487 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1488 if (thread == NULL) {
1489 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1490 if (thread == NULL) {
1491 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1492 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001493 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001494 }
1495 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001497 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498}
1499
Glenn Kastendd8104c2012-07-02 12:42:44 -07001500size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1501 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502{
Eric Laurenta1884f92011-08-23 08:25:03 -07001503 status_t ret = initCheck();
1504 if (ret != NO_ERROR) {
1505 return 0;
1506 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001507 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001508 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001509 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001510 return 0;
1511 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001512
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001513 AutoMutex lock(mHardwareLock);
1514 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001515 audio_config_t config, proposed;
1516 memset(&proposed, 0, sizeof(proposed));
1517 proposed.sample_rate = sampleRate;
1518 proposed.channel_mask = channelMask;
1519 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001520
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001521 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001522 size_t frames;
1523 for (;;) {
1524 // Note: config is currently a const parameter for get_input_buffer_size()
1525 // but we use a copy from proposed in case config changes from the call.
1526 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001527 status_t result = dev->getInputBufferSize(&config, &frames);
1528 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001529 break; // hal success, config is the result
1530 }
1531 // change one parameter of the configuration each iteration to a more "common" value
1532 // to see if the device will support it.
1533 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1534 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1535 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1536 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1537 } else {
1538 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1539 "format %#x, channelMask 0x%X",
1540 sampleRate, format, channelMask);
1541 break; // retries failed, break out of loop with frames == 0.
1542 }
1543 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001544 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001545 if (frames > 0 && config.sample_rate != sampleRate) {
1546 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1547 }
1548 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549}
1550
Glenn Kasten5f972c02014-01-13 09:59:31 -08001551uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 Mutex::Autolock _l(mLock);
1554
1555 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1556 if (recordThread != NULL) {
1557 return recordThread->getInputFramesLost();
1558 }
1559 return 0;
1560}
1561
1562status_t AudioFlinger::setVoiceVolume(float value)
1563{
Eric Laurenta1884f92011-08-23 08:25:03 -07001564 status_t ret = initCheck();
1565 if (ret != NO_ERROR) {
1566 return ret;
1567 }
1568
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 // check calling permissions
1570 if (!settingsAllowed()) {
1571 return PERMISSION_DENIED;
1572 }
1573
1574 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001575 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001576 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001577 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 mHardwareStatus = AUDIO_HW_IDLE;
1579
1580 return ret;
1581}
1582
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001583status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001584 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 Mutex::Autolock _l(mLock);
1587
1588 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1589 if (playbackThread != NULL) {
1590 return playbackThread->getRenderPosition(halFrames, dspFrames);
1591 }
1592
1593 return BAD_VALUE;
1594}
1595
1596void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1597{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001599 if (client == 0) {
1600 return;
1601 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001602 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001603 {
1604 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001605 if (mNotificationClients.indexOfKey(pid) < 0) {
1606 sp<NotificationClient> notificationClient = new NotificationClient(this,
1607 client,
1608 pid);
1609 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610
Eric Laurent021cf962014-05-13 10:18:14 -07001611 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612
Marco Nelissen06b46062014-11-14 07:58:25 -08001613 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001614 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001615 }
1616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617
Eric Laurent021cf962014-05-13 10:18:14 -07001618 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001619 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001620 // the config change is always sent from playback or record threads to avoid deadlock
1621 // with AudioSystem::gLock
1622 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001623 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001624 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001626 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001627 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 }
1629}
1630
1631void AudioFlinger::removeNotificationClient(pid_t pid)
1632{
1633 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001634 {
1635 Mutex::Autolock _cl(mClientLock);
1636 mNotificationClients.removeItem(pid);
1637 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001638
Steve Block3856b092011-10-20 11:56:00 +01001639 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001640 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001641 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001642 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001643 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001644 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001645 if (ref->mPid == pid) {
1646 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001647 mAudioSessionRefs.removeAt(i);
1648 delete ref;
1649 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001650 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001651 } else {
1652 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001653 }
1654 }
1655 if (removed) {
1656 purgeStaleEffects_l();
1657 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658}
1659
Eric Laurent73e26b62015-04-27 16:55:58 -07001660void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001661 const sp<AudioIoDescriptor>& ioDesc,
1662 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663{
Eric Laurent021cf962014-05-13 10:18:14 -07001664 Mutex::Autolock _l(mClientLock);
1665 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001667 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1668 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1669 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670 }
1671}
1672
Eric Laurent021cf962014-05-13 10:18:14 -07001673// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674void AudioFlinger::removeClient_l(pid_t pid)
1675{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001676 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001677 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 mClients.removeItem(pid);
1679}
1680
Eric Laurent717e1282012-06-29 16:36:52 -07001681// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001682sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1683 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001684{
1685 sp<PlaybackThread> thread;
1686
1687 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1688 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1689 ALOG_ASSERT(thread == 0);
1690 thread = mPlaybackThreads.valueAt(i);
1691 }
1692 }
1693
1694 return thread;
1695}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698
1699// ----------------------------------------------------------------------------
1700
1701AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1702 : RefBase(),
1703 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001704 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705{
Andy Hung6f248bb2018-01-23 14:04:37 -08001706 mMemoryDealer = new MemoryDealer(
1707 audioFlinger->getClientSharedHeapSize(),
1708 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709}
1710
Eric Laurent021cf962014-05-13 10:18:14 -07001711// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712AudioFlinger::Client::~Client()
1713{
1714 mAudioFlinger->removeClient_l(mPid);
1715}
1716
Glenn Kasten435dbe62012-01-30 10:15:48 -08001717sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718{
1719 return mMemoryDealer;
1720}
1721
1722// ----------------------------------------------------------------------------
1723
1724AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1725 const sp<IAudioFlingerClient>& client,
1726 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001727 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728{
1729}
1730
1731AudioFlinger::NotificationClient::~NotificationClient()
1732{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733}
1734
Glenn Kasten0f11b512014-01-31 16:18:54 -08001735void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736{
1737 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001738 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739}
1740
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001741// ----------------------------------------------------------------------------
1742AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1743 : mPendingRequests(false) {}
1744
1745
1746void AudioFlinger::MediaLogNotifier::requestMerge() {
1747 AutoMutex _l(mMutex);
1748 mPendingRequests = true;
1749 mCond.signal();
1750}
1751
1752bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001753 // Should already have been checked, but just in case
1754 if (sMediaLogService == 0) {
1755 return false;
1756 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001757 // Wait until there are pending requests
1758 {
1759 AutoMutex _l(mMutex);
1760 mPendingRequests = false; // to ignore past requests
1761 while (!mPendingRequests) {
1762 mCond.wait(mMutex);
1763 // TODO may also need an exitPending check
1764 }
1765 mPendingRequests = false;
1766 }
1767 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001768 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001769 usleep(kPostTriggerSleepPeriod);
1770 return true;
1771}
1772
1773void AudioFlinger::requestLogMerge() {
1774 mMediaLogNotifier->requestMerge();
1775}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776
1777// ----------------------------------------------------------------------------
1778
Eric Laurentf14db3c2017-12-08 14:20:36 -08001779sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1780 CreateRecordOutput& output,
1781 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782{
1783 sp<RecordThread::RecordTrack> recordTrack;
1784 sp<RecordHandle> recordHandle;
1785 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001787 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001788 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789
Eric Laurentf14db3c2017-12-08 14:20:36 -08001790 output.cblk.clear();
1791 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001792 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001793
Eric Laurentf14db3c2017-12-08 14:20:36 -08001794 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001795 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001796 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001797 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001798 ALOGW_IF(clientUid != callingUid,
1799 "%s uid %d tried to pass itself off as %d",
1800 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001801 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001802 updatePid = true;
1803 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001804 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001805 if (updatePid) {
1806 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001807 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001808 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001809 __func__, callingUid, callingPid, clientPid);
1810 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001811 }
1812
Andy Hung6770c6f2015-04-07 13:43:36 -07001813 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001814 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1815 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001816 lStatus = BAD_VALUE;
1817 goto Exit;
1818 }
1819
Glenn Kasten53b5d092014-02-05 10:00:23 -08001820 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001821 if (!audio_is_input_channel(input.config.channel_mask)) {
1822 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001823 lStatus = BAD_VALUE;
1824 goto Exit;
1825 }
1826
Eric Laurentf14db3c2017-12-08 14:20:36 -08001827 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1828 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1829 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1830 lStatus = BAD_VALUE;
1831 goto Exit;
1832 }
1833
1834 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001835 output.selectedDeviceId = input.selectedDeviceId;
1836 output.flags = input.flags;
1837
1838 client = registerPid(clientPid);
1839
1840 // Not a conventional loop, but a retry loop for at most two iterations total.
1841 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1842 // Exits loop via break on no error of got exit on error
1843 // The sp<> references will be dropped when re-entering scope.
1844 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1845 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001846 // release previously opened input if retrying.
1847 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1848 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001849 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001850 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001851 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001852 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001853 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001854 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1855 sessionId,
1856 // FIXME compare to AudioTrack
1857 clientPid,
1858 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001859 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001860 &input.config,
1861 output.flags, &output.selectedDeviceId, &portId);
1862
Glenn Kasten05997e22014-03-13 15:08:33 -07001863 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001865 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001867 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 lStatus = BAD_VALUE;
1869 goto Exit;
1870 }
1871
Eric Laurentf14db3c2017-12-08 14:20:36 -08001872 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873
Eric Laurentf14db3c2017-12-08 14:20:36 -08001874 output.sampleRate = input.config.sample_rate;
1875 output.frameCount = input.frameCount;
1876 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001877
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001878 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001879 input.config.format, input.config.channel_mask,
1880 &output.frameCount, sessionId,
1881 &output.notificationFrameCount,
1882 clientUid, &output.flags,
1883 input.clientInfo.clientTid,
1884 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001885 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001886
Eric Laurentf14db3c2017-12-08 14:20:36 -08001887 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1888 // audio policy manager without FAST constraint
1889 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001890 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001891 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001892
1893 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001894 goto Exit;
1895 }
1896
1897 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1898 // session and move it to this thread.
1899 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1900 if (chain != 0) {
1901 Mutex::Autolock _l(thread->mLock);
1902 thread->addEffectChain_l(chain);
1903 }
1904 break;
1905 }
1906 // End of retry loop.
1907 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908 }
Glenn Kastene198c362013-08-13 09:13:36 -07001909
Eric Laurentf14db3c2017-12-08 14:20:36 -08001910 output.cblk = recordTrack->getCblk();
1911 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001912 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001913
1914 // return handle to client
1915 recordHandle = new RecordHandle(recordTrack);
1916
1917Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001918 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001919 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001920 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001921 // Don't hold mClientLock when releasing the reference on the track as the
1922 // destructor will acquire it.
1923 {
1924 Mutex::Autolock _cl(mClientLock);
1925 client.clear();
1926 }
Eric Laurent896c9672017-12-08 14:08:45 -08001927 recordTrack.clear();
1928 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001929 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001930 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 }
1932
Glenn Kasten9156ef32013-08-06 15:39:08 -07001933 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 return recordHandle;
1935}
1936
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001937
1938
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939// ----------------------------------------------------------------------------
1940
Eric Laurenta4c5a552012-03-29 10:12:40 -07001941audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1942{
Eric Laurent44622db2014-08-01 19:00:33 -07001943 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001944 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001945 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001946 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001947 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001948 }
1949 Mutex::Autolock _l(mLock);
1950 return loadHwModule_l(name);
1951}
1952
1953// loadHwModule_l() must be called with AudioFlinger::mLock held
1954audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1955{
1956 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1957 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1958 ALOGW("loadHwModule() module %s already loaded", name);
1959 return mAudioHwDevs.keyAt(i);
1960 }
1961 }
1962
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001963 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001964
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001965 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001966 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001967 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001968 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001969 }
1970
1971 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001972 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001973 mHardwareStatus = AUDIO_HW_IDLE;
1974 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001975 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001976 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001977 }
1978
John Grossmanee578c02012-07-23 17:05:46 -07001979 // Check and cache this HAL's level of support for master mute and master
1980 // volume. If this is the first HAL opened, and it supports the get
1981 // methods, use the initial values provided by the HAL as the current
1982 // master mute and volume settings.
1983
1984 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1985 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001986 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001987
1988 if (0 == mAudioHwDevs.size()) {
1989 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001990 float mv;
1991 if (OK == dev->getMasterVolume(&mv)) {
1992 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001993 }
1994
1995 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001996 bool mm;
1997 if (OK == dev->getMasterMute(&mm)) {
1998 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001999 }
2000 }
2001
Eric Laurenta4c5a552012-03-29 10:12:40 -07002002 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002003 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002004 flags = static_cast<AudioHwDevice::Flags>(flags |
2005 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2006 }
2007
2008 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002009 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002010 flags = static_cast<AudioHwDevice::Flags>(flags |
2011 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2012 }
2013
Eric Laurenta4c5a552012-03-29 10:12:40 -07002014 mHardwareStatus = AUDIO_HW_IDLE;
2015 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002016 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002017 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2018 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2019 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002020
Glenn Kastena13cde92016-03-28 15:26:02 -07002021 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002022 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002023
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002024 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002025
2026 return handle;
2027
2028}
2029
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002030// ----------------------------------------------------------------------------
2031
Glenn Kasten3b16c762012-11-14 08:44:39 -08002032uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002033{
2034 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002035 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002036 return thread != NULL ? thread->sampleRate() : 0;
2037}
2038
Glenn Kastene33054e2012-11-14 12:54:39 -08002039size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002040{
2041 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002042 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002043 return thread != NULL ? thread->frameCountHAL() : 0;
2044}
2045
2046// ----------------------------------------------------------------------------
2047
Andy Hung6f248bb2018-01-23 14:04:37 -08002048status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002049{
2050 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002051 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002052 return PERMISSION_DENIED;
2053 }
2054 Mutex::Autolock _l(mLock);
2055 if (mIsDeviceTypeKnown) {
2056 return INVALID_OPERATION;
2057 }
2058 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002059 mTotalMemory = totalMemory;
2060 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2061 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2062 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2063 // though actual setting is determined through device configuration.
2064 constexpr int64_t GB = 1024 * 1024 * 1024;
2065 mClientSharedHeapSize =
2066 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2067 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2068 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2069 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2070 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002071 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002072
2073 // TODO: Cache the client shared heap size in a persistent property.
2074 // It's possible that a native process or Java service or app accesses audioserver
2075 // after it is registered by system server, but before AudioService updates
2076 // the memory info. This would occur immediately after boot or an audioserver
2077 // crash and restore. Before update from AudioService, the client would get the
2078 // minimum heap size.
2079
2080 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2081 (isLowRamDevice ? "true" : "false"),
2082 (long long)mTotalMemory,
2083 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002084 return NO_ERROR;
2085}
2086
Andy Hung6f248bb2018-01-23 14:04:37 -08002087size_t AudioFlinger::getClientSharedHeapSize() const
2088{
2089 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2090 if (heapSizeInBytes != 0) { // read-only property overrides all.
2091 return heapSizeInBytes;
2092 }
2093 return mClientSharedHeapSize;
2094}
2095
Mikhail Naganovdea53042018-04-26 13:10:21 -07002096status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2097{
2098 ALOGV(__func__);
2099
2100 audio_module_handle_t module;
2101 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2102 module = config->ext.device.hw_module;
2103 } else {
2104 module = config->ext.mix.hw_module;
2105 }
2106
2107 Mutex::Autolock _l(mLock);
2108 ssize_t index = mAudioHwDevs.indexOfKey(module);
2109 if (index < 0) {
2110 ALOGW("%s() bad hw module %d", __func__, module);
2111 return BAD_VALUE;
2112 }
2113
2114 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2115 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2116}
2117
Eric Laurent93c3d412014-08-01 14:48:35 -07002118audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2119{
2120 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002121
2122 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2123 if (index >= 0) {
2124 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2125 mHwAvSyncIds.valueAt(index), sessionId);
2126 return mHwAvSyncIds.valueAt(index);
2127 }
2128
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002129 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002130 if (dev == NULL) {
2131 return AUDIO_HW_SYNC_INVALID;
2132 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002133 String8 reply;
2134 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002135 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002136 param = AudioParameter(reply);
2137 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002138
2139 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002140 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002141 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2142 return AUDIO_HW_SYNC_INVALID;
2143 }
2144
2145 // allow only one session for a given HW A/V sync ID.
2146 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2147 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2148 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2149 value, mHwAvSyncIds.keyAt(i));
2150 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002151 break;
2152 }
2153 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002154
2155 mHwAvSyncIds.add(sessionId, value);
2156
2157 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2158 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2159 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002160 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002161 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002162 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002163 String8 keyValuePairs = param.toString();
2164 thread->setParameters(keyValuePairs);
2165 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2166 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002167 break;
2168 }
2169 }
2170
2171 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2172 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002173}
2174
Eric Laurent72e3f392015-05-20 14:43:50 -07002175status_t AudioFlinger::systemReady()
2176{
2177 Mutex::Autolock _l(mLock);
2178 ALOGI("%s", __FUNCTION__);
2179 if (mSystemReady) {
2180 ALOGW("%s called twice", __FUNCTION__);
2181 return NO_ERROR;
2182 }
2183 mSystemReady = true;
2184 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2185 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2186 thread->systemReady();
2187 }
2188 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2189 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2190 thread->systemReady();
2191 }
2192 return NO_ERROR;
2193}
2194
jiabin46a76fa2018-01-05 10:18:21 -08002195status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2196{
jiabin9ff780e2018-03-19 18:19:52 -07002197 AutoMutex lock(mHardwareLock);
2198 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2199 status_t status = dev->getMicrophones(microphones);
2200 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002201}
2202
Eric Laurentfa90e842014-10-17 18:12:31 -07002203// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2204void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2205{
2206 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2207 if (index >= 0) {
2208 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2209 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2210 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002211 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002212 String8 keyValuePairs = param.toString();
2213 thread->setParameters(keyValuePairs);
2214 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2215 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002216 }
2217}
2218
2219
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002220// ----------------------------------------------------------------------------
2221
Eric Laurent83b88082014-06-20 18:31:16 -07002222
Eric Laurent6acd1d42017-01-04 14:23:29 -08002223sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002224 audio_io_handle_t *output,
2225 audio_config_t *config,
2226 audio_devices_t devices,
2227 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002228 audio_output_flags_t flags)
2229{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002230 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002231 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002232 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002233 }
2234
Eric Laurentcf2c0212014-07-25 16:20:43 -07002235 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002236 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2237 } else {
2238 // Audio Policy does not currently request a specific output handle.
2239 // If this is ever needed, see openInput_l() for example code.
2240 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2241 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002242 }
Eric Laurent83b88082014-06-20 18:31:16 -07002243
2244 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2245
Eric Laurent83b88082014-06-20 18:31:16 -07002246 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002247 // This if statement allows overriding the audio policy settings
2248 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2249 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2250 // Check only for Normal Mixing mode
2251 if (kEnableExtendedPrecision) {
2252 // Specify format (uncomment one below to choose)
2253 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2254 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2255 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2256 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002257 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002258 }
2259 if (kEnableExtendedChannels) {
2260 // Specify channel mask (uncomment one below to choose)
2261 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2262 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2263 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2264 }
Eric Laurent83b88082014-06-20 18:31:16 -07002265 }
2266
Phil Burk062e67a2015-02-11 13:40:50 -08002267 AudioStreamOut *outputStream = NULL;
2268 status_t status = outHwDev->openOutputStream(
2269 &outputStream,
2270 *output,
2271 devices,
2272 flags,
2273 config,
2274 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002275
2276 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002277
Phil Burk062e67a2015-02-11 13:40:50 -08002278 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002279 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2280 sp<MmapPlaybackThread> thread =
2281 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2282 devices, AUDIO_DEVICE_NONE, mSystemReady);
2283 mMmapThreads.add(*output, thread);
2284 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2285 *output, thread.get());
2286 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002287 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002288 sp<PlaybackThread> thread;
2289 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2290 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2291 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2292 *output, thread.get());
2293 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2294 || !isValidPcmSinkFormat(config->format)
2295 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2296 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2297 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2298 *output, thread.get());
2299 } else {
2300 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2301 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2302 *output, thread.get());
2303 }
2304 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002305 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002306 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002307 }
Eric Laurent83b88082014-06-20 18:31:16 -07002308 }
2309
2310 return 0;
2311}
2312
Eric Laurentcf2c0212014-07-25 16:20:43 -07002313status_t AudioFlinger::openOutput(audio_module_handle_t module,
2314 audio_io_handle_t *output,
2315 audio_config_t *config,
2316 audio_devices_t *devices,
2317 const String8& address,
2318 uint32_t *latencyMs,
2319 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002321 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2322 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002323 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002324 (devices != NULL) ? *devices : 0,
2325 config->sample_rate,
2326 config->format,
2327 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002328 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002330 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002331 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002333
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 Mutex::Autolock _l(mLock);
2335
Eric Laurent6acd1d42017-01-04 14:23:29 -08002336 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002337 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002338 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2339 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2340 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341
Eric Laurent6acd1d42017-01-04 14:23:29 -08002342 // notify client processes of the new output creation
2343 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002344
Eric Laurent6acd1d42017-01-04 14:23:29 -08002345 // the first primary output opened designates the primary hw device
2346 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002347 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002348 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002349
Eric Laurent6acd1d42017-01-04 14:23:29 -08002350 AutoMutex lock(mHardwareLock);
2351 mHardwareStatus = AUDIO_HW_SET_MODE;
2352 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2353 mHardwareStatus = AUDIO_HW_IDLE;
2354 }
2355 } else {
2356 MmapThread *mmapThread = (MmapThread *)thread.get();
2357 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002358 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002359 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 }
2361
Eric Laurentcf2c0212014-07-25 16:20:43 -07002362 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363}
2364
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002365audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2366 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367{
2368 Mutex::Autolock _l(mLock);
2369 MixerThread *thread1 = checkMixerThread_l(output1);
2370 MixerThread *thread2 = checkMixerThread_l(output2);
2371
2372 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002373 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2374 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002375 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376 }
2377
Glenn Kasteneeecb982016-02-26 10:44:04 -08002378 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002379 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 thread->addOutputTrack(thread2);
2381 mPlaybackThreads.add(id, thread);
2382 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002383 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 return id;
2385}
2386
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002387status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388{
Glenn Kastend96c5722012-04-25 13:44:49 -07002389 return closeOutput_nonvirtual(output);
2390}
2391
2392status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2393{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394 // keep strong reference on the playback thread so that
2395 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002396 sp<PlaybackThread> playbackThread;
2397 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 {
2399 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002400 playbackThread = checkPlaybackThread_l(output);
2401 if (playbackThread != NULL) {
2402 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403
Andy Hungdc099c22018-09-18 13:46:39 -07002404 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002405
Eric Laurent6acd1d42017-01-04 14:23:29 -08002406 if (playbackThread->type() == ThreadBase::MIXER) {
2407 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2408 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2409 DuplicatingThread *dupThread =
2410 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2411 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2412 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002413 }
2414 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002415
2416
Eric Laurent6acd1d42017-01-04 14:23:29 -08002417 mPlaybackThreads.removeItem(output);
2418 // save all effects to the default thread
2419 if (mPlaybackThreads.size()) {
2420 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2421 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002422 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002423 Mutex::Autolock _dl(dstThread->mLock);
2424 Mutex::Autolock _sl(playbackThread->mLock);
2425 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2426 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002427 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2428 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002429 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 }
2431 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002432 } else {
2433 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2434 if (mmapThread == 0) {
2435 return BAD_VALUE;
2436 }
Andy Hungdc099c22018-09-18 13:46:39 -07002437 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002438 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002439 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002441 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2442 ioDesc->mIoHandle = output;
2443 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002444 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002446 // The thread entity (active unit of execution) is no longer running here,
2447 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448
Eric Laurent6acd1d42017-01-04 14:23:29 -08002449 if (playbackThread != 0) {
2450 playbackThread->exit();
2451 if (!playbackThread->isDuplicating()) {
2452 closeOutputFinish(playbackThread);
2453 }
2454 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002455 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002456 mmapThread->exit();
2457 AudioStreamOut *out = mmapThread->clearOutput();
2458 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2459 // from now on thread->mOutput is NULL
2460 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 }
2462 return NO_ERROR;
2463}
2464
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002465void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002466{
2467 AudioStreamOut *out = thread->clearOutput();
2468 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2469 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002470 delete out;
2471}
2472
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002473void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002474{
2475 mPlaybackThreads.removeItem(thread->mId);
2476 thread->exit();
2477 closeOutputFinish(thread);
2478}
2479
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002480status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481{
2482 Mutex::Autolock _l(mLock);
2483 PlaybackThread *thread = checkPlaybackThread_l(output);
2484
2485 if (thread == NULL) {
2486 return BAD_VALUE;
2487 }
2488
Steve Block3856b092011-10-20 11:56:00 +01002489 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 thread->suspend();
2491
2492 return NO_ERROR;
2493}
2494
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002495status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496{
2497 Mutex::Autolock _l(mLock);
2498 PlaybackThread *thread = checkPlaybackThread_l(output);
2499
2500 if (thread == NULL) {
2501 return BAD_VALUE;
2502 }
2503
Steve Block3856b092011-10-20 11:56:00 +01002504 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505
2506 thread->restore();
2507
2508 return NO_ERROR;
2509}
2510
Eric Laurentcf2c0212014-07-25 16:20:43 -07002511status_t AudioFlinger::openInput(audio_module_handle_t module,
2512 audio_io_handle_t *input,
2513 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002514 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002515 const String8& address,
2516 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002517 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518{
Eric Laurent83b88082014-06-20 18:31:16 -07002519 Mutex::Autolock _l(mLock);
2520
Glenn Kastene7d66712015-03-05 13:46:52 -08002521 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002522 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002523 }
2524
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002525 sp<ThreadBase> thread = openInput_l(
2526 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002527
2528 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002529 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002530 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002531 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002533 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002534}
Dima Zavin799a70e2011-04-18 16:57:27 -07002535
Eric Laurent6acd1d42017-01-04 14:23:29 -08002536sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002537 audio_io_handle_t *input,
2538 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002539 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002540 const String8& address,
2541 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002542 audio_input_flags_t flags,
2543 audio_devices_t outputDevice,
2544 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002545{
Glenn Kastene7d66712015-03-05 13:46:52 -08002546 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002547 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002548 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002549 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002550 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002551
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002552 // Some flags are specific to framework and must not leak to the HAL.
2553 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2554
Glenn Kasteneeecb982016-02-26 10:44:04 -08002555 // Audio Policy can request a specific handle for hardware hotword.
2556 // The goal here is not to re-open an already opened input.
2557 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002558 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002559 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2560 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2561 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2562 return 0;
2563 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2564 // This should not happen in a transient state with current design.
2565 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2566 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002567 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002568
Eric Laurentcf2c0212014-07-25 16:20:43 -07002569 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002570 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002571 sp<StreamInHalInterface> inStream;
2572 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002573 *input, devices, &halconfig, flags, address.string(), source,
2574 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002575 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2576 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002577 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002578 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002579 halconfig.sample_rate,
2580 halconfig.format,
2581 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002582 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002583 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002585 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002586 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002587 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002588 audio_is_linear_pcm(config->format) &&
2589 audio_is_linear_pcm(halconfig.format) &&
2590 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002591 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2592 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002593 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002594 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002595 inStream.clear();
2596 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002597 *input, devices, &halconfig, flags, address.string(), source,
2598 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002599 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 }
2601
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002602 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002603 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002604 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2605 sp<MmapCaptureThread> thread =
2606 new MmapCaptureThread(this, *input,
2607 inHwDev, inputStream,
2608 primaryOutputDevice_l(), devices, mSystemReady);
2609 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002610 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2611 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002612 return thread;
2613 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002614 // Start record thread
2615 // RecordThread requires both input and output device indication to forward to audio
2616 // pre processing modules
2617 sp<RecordThread> thread = new RecordThread(this,
2618 inputStream,
2619 *input,
2620 primaryOutputDevice_l(),
2621 devices,
2622 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002623 );
2624 mRecordThreads.add(*input, thread);
2625 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2626 return thread;
2627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 }
2629
Eric Laurentcf2c0212014-07-25 16:20:43 -07002630 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 return 0;
2632}
2633
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002634status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635{
Glenn Kastend96c5722012-04-25 13:44:49 -07002636 return closeInput_nonvirtual(input);
2637}
2638
2639status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2640{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 // keep strong reference on the record thread so that
2642 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002643 sp<RecordThread> recordThread;
2644 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645 {
2646 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002647 recordThread = checkRecordThread_l(input);
2648 if (recordThread != 0) {
2649 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650
Andy Hungdc099c22018-09-18 13:46:39 -07002651 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002652
Eric Laurent6acd1d42017-01-04 14:23:29 -08002653 // If we still have effect chains, it means that a client still holds a handle
2654 // on at least one effect. We must either move the chain to an existing thread with the
2655 // same session ID or put it aside in case a new record thread is opened for a
2656 // new capture on the same session
2657 sp<EffectChain> chain;
2658 {
2659 Mutex::Autolock _sl(recordThread->mLock);
2660 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2661 // Note: maximum one chain per record thread
2662 if (effectChains.size() != 0) {
2663 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002664 }
2665 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002666 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002667 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002668 // This should only happen in case of overlap between one thread tear down and the
2669 // creation of its replacement
2670 size_t i;
2671 for (i = 0; i < mRecordThreads.size(); i++) {
2672 sp<RecordThread> t = mRecordThreads.valueAt(i);
2673 if (t == recordThread) {
2674 continue;
2675 }
2676 if (t->hasAudioSession(chain->sessionId()) != 0) {
2677 Mutex::Autolock _l(t->mLock);
2678 ALOGV("closeInput() found thread %d for effect session %d",
2679 t->id(), chain->sessionId());
2680 t->addEffectChain_l(chain);
2681 break;
2682 }
2683 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002684 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002685 if (i == mRecordThreads.size()) {
2686 putOrphanEffectChain_l(chain);
2687 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002688 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002689 mRecordThreads.removeItem(input);
2690 } else {
2691 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2692 if (mmapThread == 0) {
2693 return BAD_VALUE;
2694 }
Andy Hungdc099c22018-09-18 13:46:39 -07002695 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002696 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002697 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002698 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2699 ioDesc->mIoHandle = input;
2700 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 }
Eric Laurent83b88082014-06-20 18:31:16 -07002702 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2703 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002704 if (recordThread != 0) {
2705 closeInputFinish(recordThread);
2706 } else if (mmapThread != 0) {
2707 mmapThread->exit();
2708 AudioStreamIn *in = mmapThread->clearInput();
2709 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2710 // from now on thread->mInput is NULL
2711 delete in;
2712 }
Eric Laurent83b88082014-06-20 18:31:16 -07002713 return NO_ERROR;
2714}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002716void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002717{
2718 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002719 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002720 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002721 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002722 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002723}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002724
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002725void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002726{
2727 mRecordThreads.removeItem(thread->mId);
2728 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729}
2730
Glenn Kastend2304db2014-02-03 07:40:31 -08002731status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732{
2733 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002734 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735
2736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2737 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002738 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002739 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002740 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2741 mMmapThreads[i]->invalidateTracks(stream);
2742 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 return NO_ERROR;
2744}
2745
2746
Glenn Kasteneeecb982016-02-26 10:44:04 -08002747audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748{
Glenn Kasten9d003132016-04-06 14:38:09 -07002749 // This is a binder API, so a malicious client could pass in a bad parameter.
2750 // Check for that before calling the internal API nextUniqueId().
2751 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2752 ALOGE("newAudioUniqueId invalid use %d", use);
2753 return AUDIO_UNIQUE_ID_ALLOCATE;
2754 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002755 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756}
2757
Glenn Kastend848eb42016-03-08 13:42:11 -08002758void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002759{
2760 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002761 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002762 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002763 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2764 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002765 caller = pid;
2766 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002767
Eric Laurent021cf962014-05-13 10:18:14 -07002768 {
2769 Mutex::Autolock _cl(mClientLock);
2770 // Ignore requests received from processes not known as notification client. The request
2771 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2772 // called from a different pid leaving a stale session reference. Also we don't know how
2773 // to clear this reference if the client process dies.
2774 if (mNotificationClients.indexOfKey(caller) < 0) {
2775 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2776 return;
2777 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002778 }
2779
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002780 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002781 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002782 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002783 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2784 ref->mCnt++;
2785 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002786 return;
2787 }
2788 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002789 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2790 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002791}
2792
Glenn Kastend848eb42016-03-08 13:42:11 -08002793void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002794{
2795 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002796 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002797 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002798 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2799 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002800 caller = pid;
2801 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002802 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002803 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002804 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002805 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2806 ref->mCnt--;
2807 ALOGV(" decremented refcount to %d", ref->mCnt);
2808 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002809 mAudioSessionRefs.removeAt(i);
2810 delete ref;
2811 purgeStaleEffects_l();
2812 }
2813 return;
2814 }
2815 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002816 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002817 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002818 ALOGW_IF(!isAudioServerUid(callerUid),
2819 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002820}
2821
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002822bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2823{
2824 size_t num = mAudioSessionRefs.size();
2825 for (size_t i = 0; i < num; i++) {
2826 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2827 if (ref->mSessionid == audioSession) {
2828 return true;
2829 }
2830 }
2831 return false;
2832}
2833
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002834void AudioFlinger::purgeStaleEffects_l() {
2835
Steve Block3856b092011-10-20 11:56:00 +01002836 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002837
2838 Vector< sp<EffectChain> > chains;
2839
2840 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2841 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002842 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002843 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2844 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002845 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2846 chains.push(ec);
2847 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002848 }
2849 }
2850 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2851 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002852 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002853 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2854 sp<EffectChain> ec = t->mEffectChains[j];
2855 chains.push(ec);
2856 }
2857 }
2858
2859 for (size_t i = 0; i < chains.size(); i++) {
2860 sp<EffectChain> ec = chains[i];
2861 int sessionid = ec->sessionId();
2862 sp<ThreadBase> t = ec->mThread.promote();
2863 if (t == 0) {
2864 continue;
2865 }
2866 size_t numsessionrefs = mAudioSessionRefs.size();
2867 bool found = false;
2868 for (size_t k = 0; k < numsessionrefs; k++) {
2869 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002870 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002871 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002872 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002873 found = true;
2874 break;
2875 }
2876 }
2877 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002878 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002879 // remove all effects from the chain
2880 while (ec->mEffects.size()) {
2881 sp<EffectModule> effect = ec->mEffects[0];
2882 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002883 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002884 if (effect->purgeHandles()) {
2885 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002886 }
2887 AudioSystem::unregisterEffect(effect->id());
2888 }
2889 }
2890 }
2891 return;
2892}
2893
Andy Hungdc099c22018-09-18 13:46:39 -07002894// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2895void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2896{
2897 audio_utils::FdToString fdToString;
2898 const int fd = fdToString.fd();
2899 if (fd >= 0) {
2900 thread->dump(fd, {} /* args */);
2901 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2902 }
2903}
2904
Glenn Kasteneeecb982016-02-26 10:44:04 -08002905// checkThread_l() must be called with AudioFlinger::mLock held
2906AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2907{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002908 ThreadBase *thread = checkMmapThread_l(ioHandle);
2909 if (thread == 0) {
2910 switch (audio_unique_id_get_use(ioHandle)) {
2911 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2912 thread = checkPlaybackThread_l(ioHandle);
2913 break;
2914 case AUDIO_UNIQUE_ID_USE_INPUT:
2915 thread = checkRecordThread_l(ioHandle);
2916 break;
2917 default:
2918 break;
2919 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002920 }
2921 return thread;
2922}
2923
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002925AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926{
Glenn Kastena1117922012-01-26 10:53:32 -08002927 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002928}
2929
2930// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002931AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932{
2933 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002934 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935}
2936
2937// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002938AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939{
Glenn Kastena1117922012-01-26 10:53:32 -08002940 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941}
2942
Eric Laurent6acd1d42017-01-04 14:23:29 -08002943// checkMmapThread_l() must be called with AudioFlinger::mLock held
2944AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2945{
2946 return mMmapThreads.valueFor(io).get();
2947}
2948
2949
2950// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2951AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2952{
Eric Laurent7459b902017-04-19 18:10:41 -07002953 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002954 if (volumeInterface == nullptr) {
2955 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2956 if (mmapThread != nullptr) {
2957 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002958 MmapPlaybackThread *mmapPlaybackThread =
2959 static_cast<MmapPlaybackThread *>(mmapThread);
2960 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002961 }
2962 }
2963 }
2964 return volumeInterface;
2965}
2966
2967Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2968{
2969 Vector <VolumeInterface *> volumeInterfaces;
2970 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002971 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002972 }
2973 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2974 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002975 MmapPlaybackThread *mmapPlaybackThread =
2976 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2977 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002978 }
2979 }
2980 return volumeInterfaces;
2981}
2982
Glenn Kasteneeecb982016-02-26 10:44:04 -08002983audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984{
Glenn Kasten9d003132016-04-06 14:38:09 -07002985 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002986 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002987 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2988 for (int retry = 0; retry < maxRetries; retry++) {
2989 // The cast allows wraparound from max positive to min negative instead of abort
2990 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2991 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2992 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2993 // allow wrap by skipping 0 and -1 for session ids
2994 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2995 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2996 return (audio_unique_id_t) (base | use);
2997 }
2998 }
2999 // We have no way of recovering from wraparound
3000 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3001 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002}
3003
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003004AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003005{
3006 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3007 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003008 if(thread->isDuplicating()) {
3009 continue;
3010 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003011 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003012 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003013 return thread;
3014 }
3015 }
3016 return NULL;
3017}
3018
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003019audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003020{
3021 PlaybackThread *thread = primaryPlaybackThread_l();
3022
3023 if (thread == NULL) {
3024 return 0;
3025 }
3026
Eric Laurentf1c04f92012-08-28 14:26:53 -07003027 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003028}
3029
Glenn Kastena7335632016-06-09 17:09:53 -07003030AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3031{
3032 size_t minFrameCount = 0;
3033 PlaybackThread *minThread = NULL;
3034 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3035 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3036 if (!thread->isDuplicating()) {
3037 size_t frameCount = thread->frameCountHAL();
3038 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3039 (frameCount == minFrameCount && thread->hasFastMixer() &&
3040 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3041 minFrameCount = frameCount;
3042 minThread = thread;
3043 }
3044 }
3045 }
3046 return minThread;
3047}
3048
Eric Laurenta011e352012-03-29 15:51:43 -07003049sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003050 audio_session_t triggerSession,
3051 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003052 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003053 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003054{
3055 Mutex::Autolock _l(mLock);
3056
3057 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3058 status_t playStatus = NAME_NOT_FOUND;
3059 status_t recStatus = NAME_NOT_FOUND;
3060 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3061 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3062 if (playStatus == NO_ERROR) {
3063 return event;
3064 }
3065 }
3066 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3067 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3068 if (recStatus == NO_ERROR) {
3069 return event;
3070 }
3071 }
3072 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3073 mPendingSyncEvents.add(event);
3074 } else {
3075 ALOGV("createSyncEvent() invalid event %d", event->type());
3076 event.clear();
3077 }
3078 return event;
3079}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003080
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081// ----------------------------------------------------------------------------
3082// Effect management
3083// ----------------------------------------------------------------------------
3084
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003085sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3086 return mEffectsFactoryHal;
3087}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088
Glenn Kastenf587ba52012-01-26 16:25:10 -08003089status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090{
3091 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003092 if (mEffectsFactoryHal.get()) {
3093 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3094 } else {
3095 return -ENODEV;
3096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097}
3098
Glenn Kastenf587ba52012-01-26 16:25:10 -08003099status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003100{
3101 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003102 if (mEffectsFactoryHal.get()) {
3103 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3104 } else {
3105 return -ENODEV;
3106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107}
3108
Glenn Kasten5e92a782012-01-30 07:40:52 -08003109status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003110 const effect_uuid_t *pTypeUuid,
3111 uint32_t preferredTypeFlag,
3112 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003114 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3115 return BAD_VALUE;
3116 }
3117
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003119
3120 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003121 return -ENODEV;
3122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003124 status_t status = NO_ERROR;
3125 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3126 // If uuid is specified, request effect descriptor from that.
3127 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3128 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3129 // If uuid is not specified, look for an available implementation
3130 // of the required type instead.
3131
3132 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3133 effect_descriptor_t desc;
3134 desc.flags = 0; // prevent compiler warning
3135
3136 uint32_t numEffects = 0;
3137 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3138 if (status < 0) {
3139 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3140 return status;
3141 }
3142
3143 bool found = false;
3144 for (uint32_t i = 0; i < numEffects; i++) {
3145 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3146 if (status < 0) {
3147 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3148 continue;
3149 }
3150 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3151 // If matching type found save effect descriptor.
3152 found = true;
3153 *descriptor = desc;
3154
3155 // If there's no preferred flag or this descriptor matches the preferred
3156 // flag, success! If this descriptor doesn't match the preferred
3157 // flag, continue enumeration in case a better matching version of this
3158 // effect type is available. Note that this means if no effect with a
3159 // correct flag is found, the descriptor returned will correspond to the
3160 // last effect that at least had a matching type uuid (if any).
3161 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3162 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3163 break;
3164 }
3165 }
3166 }
3167
3168 if (!found) {
3169 status = NAME_NOT_FOUND;
3170 ALOGW("getEffectDescriptor(): Effect not found by type.");
3171 }
3172 } else {
3173 status = BAD_VALUE;
3174 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3175 }
3176 return status;
3177}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003179sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 effect_descriptor_t *pDesc,
3181 const sp<IEffectClient>& effectClient,
3182 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003183 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003184 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003185 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003186 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 status_t *status,
3188 int *id,
3189 int *enabled)
3190{
3191 status_t lStatus = NO_ERROR;
3192 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194
Eric Laurentb6436272016-12-07 19:24:50 -08003195 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003196 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003197 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3198 ALOGW_IF(pid != -1 && pid != callingPid,
3199 "%s uid %d pid %d tried to pass itself off as pid %d",
3200 __func__, callingUid, callingPid, pid);
3201 pid = callingPid;
3202 }
3203
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003204 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3205 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206
3207 if (pDesc == NULL) {
3208 lStatus = BAD_VALUE;
3209 goto Exit;
3210 }
3211
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003212 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003213 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003214 lStatus = NO_INIT;
3215 goto Exit;
3216 }
3217
Andy Hung6096dcd2019-03-13 13:20:30 -07003218 // check audio settings permission for global effects
3219 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3220 if (!settingsAllowed()) {
3221 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3222 lStatus = PERMISSION_DENIED;
3223 goto Exit;
3224 }
3225 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3226 if (!isAudioServerUid(callingUid)) {
3227 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3228 lStatus = PERMISSION_DENIED;
3229 goto Exit;
3230 }
3231
3232 if (io == AUDIO_IO_HANDLE_NONE) {
3233 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3234 lStatus = BAD_VALUE;
3235 goto Exit;
3236 }
3237 } else {
3238 // general sessionId.
3239
3240 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3241 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3242 lStatus = BAD_VALUE;
3243 goto Exit;
3244 }
3245
3246 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3247 // to prevent creating an effect when one doesn't actually have track with that session?
3248 }
3249
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003251 // Get the full effect descriptor from the uuid/type.
3252 // If the session is the output mix, prefer an auxiliary effect,
3253 // otherwise no preference.
3254 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3255 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3256 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3257 if (lStatus < 0) {
3258 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3259 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 }
3261
3262 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003263 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3265 lStatus = INVALID_OPERATION;
3266 goto Exit;
3267 }
3268
Eric Laurent59255e42011-07-27 19:49:51 -07003269 // check recording permission for visualizer
3270 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003271 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003272 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003273 lStatus = PERMISSION_DENIED;
3274 goto Exit;
3275 }
3276
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003278 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003279 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003280 // if the output returned by getOutputForEffect() is removed before we lock the
3281 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3282 // and we will exit safely
3283 io = AudioSystem::getOutputForEffect(&desc);
3284 ALOGV("createEffect got output %d", io);
3285 }
3286
3287 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288
3289 // If output is not specified try to find a matching audio session ID in one of the
3290 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003291 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3292 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003293 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3294 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003295 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003296 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003297 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3298 if (io == AUDIO_IO_HANDLE_NONE) {
3299 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003301 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003302 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003303 }
Andy Hung444bb552019-03-14 17:06:39 -07003304
3305 // If you wish to create a Record preprocessing AudioEffect in Java,
3306 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3307 // Otherwise it will fail when created on a Playback thread by legacy
3308 // handling below. Ditto with Mmap, the associated Mmap track must be created
3309 // before creating the AudioEffect or the io handle must be specified.
3310 //
3311 // Detect if the effect is created after an AudioRecord is destroyed.
3312 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3313 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3314 " for session %d no longer exists",
3315 __func__, desc.name, sessionId);
3316 lStatus = PERMISSION_DENIED;
3317 goto Exit;
3318 }
3319
3320 // Legacy handling of creating an effect on an expired or made-up
3321 // session id. We think that it is a Playback effect.
3322 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003323 // If no output thread contains the requested session ID, default to
3324 // first output. The effect chain will be moved to the correct output
3325 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003326 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003327 io = mPlaybackThreads.keyAt(0);
3328 }
Steve Block3856b092011-10-20 11:56:00 +01003329 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003330 } else if (checkPlaybackThread_l(io) != nullptr) {
3331 // allow only one effect chain per sessionId on mPlaybackThreads.
3332 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3333 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3334 if (io == checkIo) continue;
3335 const uint32_t sessionType =
3336 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3337 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3338 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3339 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3340 android_errorWriteLog(0x534e4554, "123237974");
3341 lStatus = BAD_VALUE;
3342 goto Exit;
3343 }
3344 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003345 }
3346 ThreadBase *thread = checkRecordThread_l(io);
3347 if (thread == NULL) {
3348 thread = checkPlaybackThread_l(io);
3349 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003350 thread = checkMmapThread_l(io);
3351 if (thread == NULL) {
3352 ALOGE("createEffect() unknown output thread");
3353 lStatus = BAD_VALUE;
3354 goto Exit;
3355 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003356 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003357 } else {
3358 // Check if one effect chain was awaiting for an effect to be created on this
3359 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003360 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003361 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003362 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003363 thread->addEffectChain_l(chain);
3364 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003366
Eric Laurent021cf962014-05-13 10:18:14 -07003367 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003369 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003370 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003371 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003372 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003373 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003374 // remove local strong reference to Client with mClientLock held
3375 Mutex::Autolock _cl(mClientLock);
3376 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003377 } else {
3378 // handle must be valid here, but check again to be safe.
3379 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003380 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 }
3382
haobo101735295ff7b0d2017-03-17 17:44:03 +08003383 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3384 // handle must be cleared outside lock.
3385 handle.clear();
3386 }
3387
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003389 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 return handle;
3391}
3392
Glenn Kastend848eb42016-03-08 13:42:11 -08003393status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003394 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003395{
Steve Block3856b092011-10-20 11:56:00 +01003396 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003397 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003398 Mutex::Autolock _l(mLock);
3399 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003400 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003401 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 }
Eric Laurentde070132010-07-13 04:45:46 -07003403 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3404 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003405 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003406 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 }
Eric Laurentde070132010-07-13 04:45:46 -07003408 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3409 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003410 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003411 return BAD_VALUE;
3412 }
3413
3414 Mutex::Autolock _dl(dstThread->mLock);
3415 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003416 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417}
3418
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003419// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003420status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003421 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003422 AudioFlinger::PlaybackThread *dstThread,
3423 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003424{
Steve Block3856b092011-10-20 11:56:00 +01003425 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003426 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003427
Eric Laurent59255e42011-07-27 19:49:51 -07003428 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003429 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003430 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003431 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003432 return INVALID_OPERATION;
3433 }
3434
Eric Laurent4c415062016-06-17 16:14:16 -07003435 // Check whether the destination thread and all effects in the chain are compatible
3436 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003437 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003438 " destination thread %p is not compatible with effects in the chain",
3439 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003440 return INVALID_OPERATION;
3441 }
3442
Eric Laurent39e94f82010-07-28 01:32:47 -07003443 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003444 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003445 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003446 // removed.
3447 srcThread->removeEffectChain_l(chain);
3448
3449 // transfer all effects one by one so that new effect chain is created on new thread with
3450 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003451 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003452 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003453 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003454 Vector< sp<EffectModule> > removed;
3455 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003456 while (effect != 0) {
3457 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003458 removed.add(effect);
3459 status = dstThread->addEffect_l(effect);
3460 if (status != NO_ERROR) {
3461 break;
3462 }
Eric Laurentec35a142011-10-05 17:42:25 -07003463 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3464 if (effect->state() == EffectModule::ACTIVE ||
3465 effect->state() == EffectModule::STOPPING) {
3466 effect->start();
3467 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003468 // if the move request is not received from audio policy manager, the effect must be
3469 // re-registered with the new strategy and output
3470 if (dstChain == 0) {
3471 dstChain = effect->chain().promote();
3472 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003473 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003474 status = NO_INIT;
3475 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003476 }
3477 strategy = dstChain->strategy();
3478 }
3479 if (reRegister) {
3480 AudioSystem::unregisterEffect(effect->id());
3481 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003482 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003483 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003484 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003485 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003486 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003487 }
Eric Laurentde070132010-07-13 04:45:46 -07003488 effect = chain->getEffectFromId_l(0);
3489 }
3490
Eric Laurent5baf2af2013-09-12 17:37:00 -07003491 if (status != NO_ERROR) {
3492 for (size_t i = 0; i < removed.size(); i++) {
3493 srcThread->addEffect_l(removed[i]);
3494 if (dstChain != 0 && reRegister) {
3495 AudioSystem::unregisterEffect(removed[i]->id());
3496 AudioSystem::registerEffect(&removed[i]->desc(),
3497 srcThread->id(),
3498 strategy,
3499 sessionId,
3500 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003501 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003502 }
3503 }
3504 }
3505
3506 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507}
3508
Eric Laurent5baf2af2013-09-12 17:37:00 -07003509bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003510{
3511 if (mGlobalEffectEnableTime != 0 &&
3512 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3513 return true;
3514 }
3515
3516 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3517 sp<EffectChain> ec =
3518 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003519 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003520 return true;
3521 }
3522 }
3523 return false;
3524}
3525
Eric Laurent5baf2af2013-09-12 17:37:00 -07003526void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003527{
3528 Mutex::Autolock _l(mLock);
3529
3530 mGlobalEffectEnableTime = systemTime();
3531
3532 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3533 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3534 if (t->mType == ThreadBase::OFFLOAD) {
3535 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3536 }
3537 }
3538
3539}
3540
Eric Laurentaaa44472014-09-12 17:41:50 -07003541status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3542{
Eric Laurentd8365c52017-07-16 15:27:05 -07003543 // clear possible suspended state before parking the chain so that it starts in default state
3544 // when attached to a new record thread
3545 chain->setEffectSuspended_l(FX_IID_AEC, false);
3546 chain->setEffectSuspended_l(FX_IID_NS, false);
3547
Glenn Kastend848eb42016-03-08 13:42:11 -08003548 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003549 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003550 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003551 if (index >= 0) {
3552 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3553 return ALREADY_EXISTS;
3554 }
3555 mOrphanEffectChains.add(session, chain);
3556 return NO_ERROR;
3557}
3558
3559sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3560{
3561 sp<EffectChain> chain;
3562 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003563 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003564 if (index >= 0) {
3565 chain = mOrphanEffectChains.valueAt(index);
3566 mOrphanEffectChains.removeItemsAt(index);
3567 }
3568 return chain;
3569}
3570
3571bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3572{
3573 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003574 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003575 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003576 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003577 if (index >= 0) {
3578 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003579 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003580 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003581 mOrphanEffectChains.removeItemsAt(index);
3582 }
3583 return true;
3584 }
3585 return false;
3586}
3587
3588
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589// ----------------------------------------------------------------------------
3590
3591status_t AudioFlinger::onTransact(
3592 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3593{
3594 return BnAudioFlinger::onTransact(code, data, reply, flags);
3595}
3596
Glenn Kasten63238ef2015-03-02 15:50:29 -08003597} // namespace android