blob: e13e7aa06f0ec1b5ce41b912dc5080a39dd33cd3 [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{
469 bool locked = false;
470 for (int i = 0; i < kDumpLockRetries; ++i) {
471 if (mutex.tryLock() == NO_ERROR) {
472 locked = true;
473 break;
474 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800475 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476 }
477 return locked;
478}
479
480status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
481{
Glenn Kasten44deb052012-02-05 18:09:08 -0800482 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 dumpPermissionDenial(fd, args);
484 } else {
485 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800486 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 if (!hardwareLocked) {
488 String8 result(kHardwareLockedString);
489 write(fd, result.string(), result.size());
490 } else {
491 mHardwareLock.unlock();
492 }
493
Eric Tan7b651152018-07-13 10:17:19 -0700494 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495
496 // failed to lock - AudioFlinger is probably deadlocked
497 if (!locked) {
498 String8 result(kDeadlockedString);
499 write(fd, result.string(), result.size());
500 }
501
Eric Laurent021cf962014-05-13 10:18:14 -0700502 bool clientLocked = dumpTryLock(mClientLock);
503 if (!clientLocked) {
504 String8 result(kClientLockedString);
505 write(fd, result.string(), result.size());
506 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700507
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700508 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700509 mEffectsFactoryHal->dumpEffects(fd);
510 } else {
511 String8 result(kNoEffectsFactory);
512 write(fd, result.string(), result.size());
513 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700514
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700516 if (clientLocked) {
517 mClientLock.unlock();
518 }
519
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 dumpInternals(fd, args);
521
522 // dump playback threads
523 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
524 mPlaybackThreads.valueAt(i)->dump(fd, args);
525 }
526
527 // dump record threads
528 for (size_t i = 0; i < mRecordThreads.size(); i++) {
529 mRecordThreads.valueAt(i)->dump(fd, args);
530 }
531
Eric Laurent6acd1d42017-01-04 14:23:29 -0800532 // dump mmap threads
533 for (size_t i = 0; i < mMmapThreads.size(); i++) {
534 mMmapThreads.valueAt(i)->dump(fd, args);
535 }
536
Eric Laurentaaa44472014-09-12 17:41:50 -0700537 // dump orphan effect chains
538 if (mOrphanEffectChains.size() != 0) {
539 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
540 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
541 mOrphanEffectChains.valueAt(i)->dump(fd, args);
542 }
543 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700544 // dump all hardware devs
545 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700546 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
547 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700549
Mikhail Naganov201369b2018-05-16 16:52:32 -0700550 mPatchPanel.dump(fd);
551
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700552 // dump external setParameters
553 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
554 dprintf(fd, "\n%s setParameters:\n", name);
555 logger.dump(fd, " " /* prefix */);
556 };
557 dumpLogger(mRejectedSetParameterLog, "Rejected");
558 dumpLogger(mAppSetParameterLog, "App");
559 dumpLogger(mSystemSetParameterLog, "System");
560
Andy Hunga8115dc2018-08-24 15:51:59 -0700561 // dump historical threads in the last 10 seconds
562 const std::string threadLog = mThreadLog.dumpToString(
563 "Historical Thread Log ", 0 /* lines */,
564 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
565 write(fd, threadLog.c_str(), threadLog.size());
566
rago3bd1c872016-09-26 12:58:14 -0700567 BUFLOG_RESET;
568
Glenn Kastend65d73c2012-06-22 17:21:07 -0700569 if (locked) {
570 mLock.unlock();
571 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800572
Andy Hung8946a282018-04-19 20:04:56 -0700573#ifdef TEE_SINK
574 // NBAIO_Tee dump is safe to call outside of AF lock.
575 NBAIO_Tee::dumpAll(fd, "_DUMP");
576#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800577 // append a copy of media.log here by forwarding fd to it, but don't attempt
578 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700579 if (sMediaLogServiceAsBinder != 0) {
580 dprintf(fd, "\nmedia.log:\n");
581 Vector<String16> args;
582 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800583 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700584
585 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700586 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700587 bool unreachableMemory = false;
588 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700589 if (arg == String16("-m")) {
590 dumpMem = true;
591 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700592 unreachableMemory = true;
593 }
594 }
595
Andy Hung07b745e2016-05-23 16:21:07 -0700596 if (dumpMem) {
597 dprintf(fd, "\nDumping memory:\n");
598 std::string s = dumpMemoryAddresses(100 /* limit */);
599 write(fd, s.c_str(), s.size());
600 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700601 if (unreachableMemory) {
602 dprintf(fd, "\nDumping unreachable memory:\n");
603 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700604 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700605 write(fd, s.c_str(), s.size());
606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 }
608 return NO_ERROR;
609}
610
Eric Laurent021cf962014-05-13 10:18:14 -0700611sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800612{
Eric Laurent021cf962014-05-13 10:18:14 -0700613 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800614 // If pid is already in the mClients wp<> map, then use that entry
615 // (for which promote() is always != 0), otherwise create a new entry and Client.
616 sp<Client> client = mClients.valueFor(pid).promote();
617 if (client == 0) {
618 client = new Client(this, pid);
619 mClients.add(pid, client);
620 }
621
622 return client;
623}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
Glenn Kasten9e58b552013-01-18 15:09:48 -0800625sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
626{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700627 // If there is no memory allocated for logs, return a dummy writer that does nothing.
628 // Similarly if we can't contact the media.log service, also return a dummy writer.
629 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800630 return new NBLog::Writer();
631 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700632 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
633 // If allocation fails, consult the vector of previously unregistered writers
634 // and garbage-collect one or more them until an allocation succeeds
635 if (shared == 0) {
636 Mutex::Autolock _l(mUnregisteredWritersLock);
637 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
638 {
639 // Pick the oldest stale writer to garbage-collect
640 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
641 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700642 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700643 // Now the media.log remote reference to IMemory is gone. When our last local
644 // reference to IMemory also drops to zero at end of this block,
645 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
646 }
647 // Re-attempt the allocation
648 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
649 if (shared != 0) {
650 goto success;
651 }
652 }
653 // Even after garbage-collecting all old writers, there is still not enough memory,
654 // so return a dummy writer
655 return new NBLog::Writer();
656 }
657success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800658 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
659 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
660 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700661 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800662 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800663}
664
665void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
666{
Glenn Kasten685ef092013-02-04 08:15:34 -0800667 if (writer == 0) {
668 return;
669 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800670 sp<IMemory> iMemory(writer->getIMemory());
671 if (iMemory == 0) {
672 return;
673 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700674 // Rather than removing the writer immediately, append it to a queue of old writers to
675 // be garbage-collected later. This allows us to continue to view old logs for a while.
676 Mutex::Autolock _l(mUnregisteredWritersLock);
677 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800678}
679
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680// IAudioFlinger interface
681
Eric Laurent21da6472017-11-09 16:29:26 -0800682sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
683 CreateTrackOutput& output,
684 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685{
686 sp<PlaybackThread::Track> track;
687 sp<TrackHandle> trackHandle;
688 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800690 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800691 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800692 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693
Eric Laurent21da6472017-11-09 16:29:26 -0800694 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700695 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800696 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700697 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800698 ALOGW_IF(clientUid != callingUid,
699 "%s uid %d tried to pass itself off as %d",
700 __FUNCTION__, callingUid, clientUid);
701 clientUid = callingUid;
702 updatePid = true;
703 }
704 pid_t clientPid = input.clientInfo.clientPid;
705 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700706 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800707 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700708 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800709 __func__, callingUid, callingPid, clientPid);
710 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700711 }
712
Eric Laurent21da6472017-11-09 16:29:26 -0800713 audio_session_t sessionId = input.sessionId;
714 if (sessionId == AUDIO_SESSION_ALLOCATE) {
715 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800716 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
717 lStatus = BAD_VALUE;
718 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800719 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800720
Eric Laurent21da6472017-11-09 16:29:26 -0800721 output.sessionId = sessionId;
722 output.outputId = AUDIO_IO_HANDLE_NONE;
723 output.selectedDeviceId = input.selectedDeviceId;
724
725 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200726 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800727 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800728
729 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
730 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
731 goto Exit;
732 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800733 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
734 // but if someone uses binder directly they could bypass that and cause us to crash
735 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000736 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 lStatus = BAD_VALUE;
738 goto Exit;
739 }
740
Glenn Kasten53b5d092014-02-05 10:00:23 -0800741 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800742 if (!audio_is_output_channel(input.config.channel_mask)) {
743 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800744 lStatus = BAD_VALUE;
745 goto Exit;
746 }
747
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700748 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800749 if (!audio_is_valid_format(input.config.format)) {
750 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700751 lStatus = BAD_VALUE;
752 goto Exit;
753 }
754
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 {
756 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800757 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800759 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 lStatus = BAD_VALUE;
761 goto Exit;
762 }
763
Eric Laurent21da6472017-11-09 16:29:26 -0800764 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765
Glenn Kastene848bd92014-03-13 15:00:32 -0700766 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800767 // check if an effect chain with the same session ID is present on another
768 // output thread and move it here.
769 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
770 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
771 if (mPlaybackThreads.keyAt(i) != output.outputId) {
772 uint32_t sessions = t->hasAudioSession(sessionId);
773 if (sessions & ThreadBase::EFFECT_SESSION) {
774 effectThread = t.get();
775 break;
Eric Laurentde070132010-07-13 04:45:46 -0700776 }
777 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778 }
Eric Laurent21da6472017-11-09 16:29:26 -0800779 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780
Eric Laurent21da6472017-11-09 16:29:26 -0800781 output.sampleRate = input.config.sample_rate;
782 output.frameCount = input.frameCount;
783 output.notificationFrameCount = input.notificationFrameCount;
784 output.flags = input.flags;
785
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700786 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
787 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800788 &output.frameCount, &output.notificationFrameCount,
789 input.notificationsPerBuffer, input.speed,
790 input.sharedBuffer, sessionId, &output.flags,
791 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800792 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700793 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700794
Eric Laurent21da6472017-11-09 16:29:26 -0800795 output.afFrameCount = thread->frameCount();
796 output.afSampleRate = thread->sampleRate();
797 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800798 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800799
Kevin Rocard153f92d2018-12-18 18:33:28 -0800800 if (lStatus == NO_ERROR) {
801 // Connect secondary outputs. Failure on a secondary output must not imped the primary
802 // Any secondary output setup failure will lead to a desync between the AP and AF until
803 // the track is destroyed.
804 TeePatches teePatches;
805 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
806 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
807 if (secondaryThread == NULL) {
808 ALOGE("no playback thread found for secondary output %d", output.outputId);
809 continue;
810 }
811
812 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
813
814 using namespace std::chrono_literals;
815 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
816 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
817 output.sampleRate,
818 inChannelMask,
819 input.config.format,
820 frameCount,
821 NULL /* buffer */,
822 (size_t)0 /* bufferSize */,
823 AUDIO_INPUT_FLAG_DIRECT,
824 0ns /* timeout */);
825 status_t status = patchRecord->initCheck();
826 if (status != NO_ERROR) {
827 ALOGE("Secondary output patchRecord init failed: %d", status);
828 continue;
829 }
830 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
831 streamType,
832 output.sampleRate,
833 input.config.channel_mask,
834 input.config.format,
835 frameCount,
836 patchRecord->buffer(),
837 patchRecord->bufferSize(),
838 output.flags,
839 0ns /* timeout */);
840 status = patchTrack->initCheck();
841 if (status != NO_ERROR) {
842 ALOGE("Secondary output patchTrack init failed: %d", status);
843 continue;
844 }
845 teePatches.push_back({patchRecord, patchTrack});
846 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800847 // In case the downstream patchTrack on the secondaryThread temporarily outlives
848 // our created track, ensure the corresponding patchRecord is still alive.
849 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
850 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800851 }
852 track->setTeePatches(std::move(teePatches));
853 }
854
Eric Laurent39e94f82010-07-28 01:32:47 -0700855 // move effect chain to this output thread if an effect on same session was waiting
856 // for a track to be created
857 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700858 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700859 Mutex::Autolock _dl(thread->mLock);
860 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800861 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700862 }
Eric Laurenta011e352012-03-29 15:51:43 -0700863
864 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700865 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800866 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700867 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700868 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700869 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700870 } else {
871 mPendingSyncEvents[i]->cancel();
872 }
Eric Laurenta011e352012-03-29 15:51:43 -0700873 mPendingSyncEvents.removeAt(i);
874 i--;
875 }
876 }
877 }
Glenn Kastene198c362013-08-13 09:13:36 -0700878
Eric Laurent21da6472017-11-09 16:29:26 -0800879 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 }
Glenn Kastene198c362013-08-13 09:13:36 -0700881
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700882 if (lStatus != NO_ERROR) {
883 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700884 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700885 // Don't hold mClientLock when releasing the reference on the track as the
886 // destructor will acquire it.
887 {
888 Mutex::Autolock _cl(mClientLock);
889 client.clear();
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700892 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
894
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700895 // return handle to client
896 trackHandle = new TrackHandle(track);
897
Mathias Agopian65ab4712010-07-14 17:59:35 -0700898Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800899 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700900 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800901 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700902 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 return trackHandle;
904}
905
Glenn Kasten2c073da2016-02-26 09:14:08 -0800906uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907{
908 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800909 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700910 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800911 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 return 0;
913 }
914 return thread->sampleRate();
915}
916
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800917audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918{
919 Mutex::Autolock _l(mLock);
920 PlaybackThread *thread = checkPlaybackThread_l(output);
921 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000922 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800923 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924 }
925 return thread->format();
926}
927
Glenn Kasten2c073da2016-02-26 09:14:08 -0800928size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929{
930 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800931 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800933 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934 return 0;
935 }
Glenn Kasten58912562012-04-03 10:45:00 -0700936 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
937 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 return thread->frameCount();
939}
940
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700941size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
942{
943 Mutex::Autolock _l(mLock);
944 ThreadBase *thread = checkThread_l(ioHandle);
945 if (thread == NULL) {
946 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
947 return 0;
948 }
949 return thread->frameCountHAL();
950}
951
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800952uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953{
954 Mutex::Autolock _l(mLock);
955 PlaybackThread *thread = checkPlaybackThread_l(output);
956 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800957 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958 return 0;
959 }
960 return thread->latency();
961}
962
963status_t AudioFlinger::setMasterVolume(float value)
964{
Eric Laurenta1884f92011-08-23 08:25:03 -0700965 status_t ret = initCheck();
966 if (ret != NO_ERROR) {
967 return ret;
968 }
969
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970 // check calling permissions
971 if (!settingsAllowed()) {
972 return PERMISSION_DENIED;
973 }
974
Eric Laurenta4c5a552012-03-29 10:12:40 -0700975 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700976 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700977
John Grossmanee578c02012-07-23 17:05:46 -0700978 // Set master volume in the HALs which support it.
979 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
980 AutoMutex lock(mHardwareLock);
981 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800982
John Grossmanee578c02012-07-23 17:05:46 -0700983 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
984 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700985 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800986 }
John Grossmanee578c02012-07-23 17:05:46 -0700987 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989
John Grossmanee578c02012-07-23 17:05:46 -0700990 // Now set the master volume in each playback thread. Playback threads
991 // assigned to HALs which do not have master volume support will apply
992 // master volume during the mix operation. Threads with HALs which do
993 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700994 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
995 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
996 continue;
997 }
John Grossmanee578c02012-07-23 17:05:46 -0700998 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000
1001 return NO_ERROR;
1002}
1003
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001004status_t AudioFlinger::setMasterBalance(float balance)
1005{
1006 status_t ret = initCheck();
1007 if (ret != NO_ERROR) {
1008 return ret;
1009 }
1010
1011 // check calling permissions
1012 if (!settingsAllowed()) {
1013 return PERMISSION_DENIED;
1014 }
1015
1016 // check range
1017 if (isnan(balance) || fabs(balance) > 1.f) {
1018 return BAD_VALUE;
1019 }
1020
1021 Mutex::Autolock _l(mLock);
1022
1023 // short cut.
1024 if (mMasterBalance == balance) return NO_ERROR;
1025
1026 mMasterBalance = balance;
1027
1028 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1029 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1030 continue;
1031 }
1032 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1033 }
1034
1035 return NO_ERROR;
1036}
1037
Glenn Kastenf78aee72012-01-04 11:00:47 -08001038status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039{
Eric Laurenta1884f92011-08-23 08:25:03 -07001040 status_t ret = initCheck();
1041 if (ret != NO_ERROR) {
1042 return ret;
1043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044
1045 // check calling permissions
1046 if (!settingsAllowed()) {
1047 return PERMISSION_DENIED;
1048 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001049 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001050 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 return BAD_VALUE;
1052 }
1053
1054 { // scope for the lock
1055 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001056 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001058 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001059 mHardwareStatus = AUDIO_HW_IDLE;
1060 }
1061
1062 if (NO_ERROR == ret) {
1063 Mutex::Autolock _l(mLock);
1064 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001065 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001066 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068
1069 return ret;
1070}
1071
1072status_t AudioFlinger::setMicMute(bool state)
1073{
Eric Laurenta1884f92011-08-23 08:25:03 -07001074 status_t ret = initCheck();
1075 if (ret != NO_ERROR) {
1076 return ret;
1077 }
1078
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 // check calling permissions
1080 if (!settingsAllowed()) {
1081 return PERMISSION_DENIED;
1082 }
1083
1084 AutoMutex lock(mHardwareLock);
1085 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001086 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001087 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1088 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001089 if (result != NO_ERROR) {
1090 ret = result;
1091 }
1092 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 mHardwareStatus = AUDIO_HW_IDLE;
1094 return ret;
1095}
1096
1097bool AudioFlinger::getMicMute() const
1098{
Eric Laurenta1884f92011-08-23 08:25:03 -07001099 status_t ret = initCheck();
1100 if (ret != NO_ERROR) {
1101 return false;
1102 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001103 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001104 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001105 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001107 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001108 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1109 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001110 if (result == NO_ERROR) {
1111 mute = mute && state;
1112 }
1113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001115
1116 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117}
1118
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001119void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1120{
1121 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1122
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001123 AutoMutex lock(mLock);
1124 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001125 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1126 }
1127 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1128 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001129 }
1130}
1131
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132status_t AudioFlinger::setMasterMute(bool muted)
1133{
John Grossmand8f178d2012-07-20 14:51:35 -07001134 status_t ret = initCheck();
1135 if (ret != NO_ERROR) {
1136 return ret;
1137 }
1138
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 // check calling permissions
1140 if (!settingsAllowed()) {
1141 return PERMISSION_DENIED;
1142 }
1143
John Grossmanee578c02012-07-23 17:05:46 -07001144 Mutex::Autolock _l(mLock);
1145 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001146
John Grossmanee578c02012-07-23 17:05:46 -07001147 // Set master mute in the HALs which support it.
1148 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1149 AutoMutex lock(mHardwareLock);
1150 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001151
John Grossmanee578c02012-07-23 17:05:46 -07001152 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1153 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001154 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001155 }
John Grossmanee578c02012-07-23 17:05:46 -07001156 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001157 }
1158
John Grossmanee578c02012-07-23 17:05:46 -07001159 // Now set the master mute in each playback thread. Playback threads
1160 // assigned to HALs which do not have master mute support will apply master
1161 // mute during the mix operation. Threads with HALs which do support master
1162 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001163 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1164 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1165 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167
1168 return NO_ERROR;
1169}
1170
1171float AudioFlinger::masterVolume() const
1172{
Glenn Kasten98067102011-12-13 11:47:54 -08001173 Mutex::Autolock _l(mLock);
1174 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175}
1176
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001177status_t AudioFlinger::getMasterBalance(float *balance) const
1178{
1179 Mutex::Autolock _l(mLock);
1180 *balance = getMasterBalance_l();
1181 return NO_ERROR; // if called through binder, may return a transactional error
1182}
1183
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184bool AudioFlinger::masterMute() const
1185{
Glenn Kasten98067102011-12-13 11:47:54 -08001186 Mutex::Autolock _l(mLock);
1187 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188}
1189
John Grossman4ff14ba2012-02-08 16:37:41 -08001190float AudioFlinger::masterVolume_l() const
1191{
John Grossman4ff14ba2012-02-08 16:37:41 -08001192 return mMasterVolume;
1193}
1194
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001195float AudioFlinger::getMasterBalance_l() const
1196{
1197 return mMasterBalance;
1198}
1199
John Grossmand8f178d2012-07-20 14:51:35 -07001200bool AudioFlinger::masterMute_l() const
1201{
John Grossmanee578c02012-07-23 17:05:46 -07001202 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001203}
1204
Eric Laurent223fd5c2014-11-11 13:43:36 -08001205status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1206{
1207 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001208 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001209 return BAD_VALUE;
1210 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001211 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1212 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1213 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001214 return PERMISSION_DENIED;
1215 }
1216
1217 return NO_ERROR;
1218}
1219
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001220status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1221 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222{
1223 // check calling permissions
1224 if (!settingsAllowed()) {
1225 return PERMISSION_DENIED;
1226 }
1227
Eric Laurent223fd5c2014-11-11 13:43:36 -08001228 status_t status = checkStreamType(stream);
1229 if (status != NO_ERROR) {
1230 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 }
Eric Laurent98e38192018-02-15 18:31:53 -08001232 if (output == AUDIO_IO_HANDLE_NONE) {
1233 return BAD_VALUE;
1234 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001235 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236
1237 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001238 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1239 if (volumeInterface == NULL) {
1240 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 }
Eric Laurent98e38192018-02-15 18:31:53 -08001242 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243
1244 return NO_ERROR;
1245}
1246
Glenn Kastenfff6d712012-01-12 16:38:12 -08001247status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248{
1249 // check calling permissions
1250 if (!settingsAllowed()) {
1251 return PERMISSION_DENIED;
1252 }
1253
Eric Laurent223fd5c2014-11-11 13:43:36 -08001254 status_t status = checkStreamType(stream);
1255 if (status != NO_ERROR) {
1256 return status;
1257 }
1258 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1259
1260 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001261 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262 return BAD_VALUE;
1263 }
1264
Eric Laurent93575202011-01-18 18:39:02 -08001265 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001267 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1268 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1269 volumeInterfaces[i]->setStreamMute(stream, muted);
1270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271
1272 return NO_ERROR;
1273}
1274
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001275float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001277 status_t status = checkStreamType(stream);
1278 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279 return 0.0f;
1280 }
Eric Laurent98e38192018-02-15 18:31:53 -08001281 if (output == AUDIO_IO_HANDLE_NONE) {
1282 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 }
1284
Eric Laurent98e38192018-02-15 18:31:53 -08001285 AutoMutex lock(mLock);
1286 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1287 if (volumeInterface == NULL) {
1288 return 0.0f;
1289 }
1290
1291 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292}
1293
Glenn Kastenfff6d712012-01-12 16:38:12 -08001294bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001296 status_t status = checkStreamType(stream);
1297 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298 return true;
1299 }
1300
Glenn Kasten6637baa2012-01-09 09:40:36 -08001301 AutoMutex lock(mLock);
1302 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303}
1304
Eric Laurent054d9d32015-04-24 08:48:48 -07001305
1306void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1307{
1308 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1309 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1310 }
1311}
1312
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001313// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1314void AudioFlinger::forwardParametersToDownstreamPatches_l(
1315 audio_io_handle_t upStream, const String8& keyValuePairs,
1316 std::function<bool(const sp<PlaybackThread>&)> useThread)
1317{
1318 std::vector<PatchPanel::SoftwarePatch> swPatches;
1319 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1320 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1321 __func__, swPatches.size(), upStream);
1322 for (const auto& swPatch : swPatches) {
1323 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1324 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1325 downStream->setParameters(keyValuePairs);
1326 }
1327 }
1328}
1329
Eric Laurentf1047e82018-04-16 19:18:20 -07001330// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1331// Some keys are used for audio routing and audio path configuration and should be reserved for use
1332// by audio policy and audio flinger for functional, privacy and security reasons.
1333void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1334{
1335 static const String8 kReservedParameters[] = {
1336 String8(AudioParameter::keyRouting),
1337 String8(AudioParameter::keySamplingRate),
1338 String8(AudioParameter::keyFormat),
1339 String8(AudioParameter::keyChannels),
1340 String8(AudioParameter::keyFrameCount),
1341 String8(AudioParameter::keyInputSource),
1342 String8(AudioParameter::keyMonoOutput),
1343 String8(AudioParameter::keyStreamConnect),
1344 String8(AudioParameter::keyStreamDisconnect),
1345 String8(AudioParameter::keyStreamSupportedFormats),
1346 String8(AudioParameter::keyStreamSupportedChannels),
1347 String8(AudioParameter::keyStreamSupportedSamplingRates),
1348 };
1349
Andy Hung4ef19fa2018-05-15 19:35:29 -07001350 if (isAudioServerUid(callingUid)) {
1351 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001352 }
1353
1354 AudioParameter param = AudioParameter(keyValuePairs);
1355 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001356 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001357 for (auto& key : kReservedParameters) {
1358 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001359 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001360 param.remove(key);
1361 }
1362 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001363 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1364 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001365 keyValuePairs = param.toString();
1366}
1367
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001368void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1369 size_t rejectedKVPSize, const String8& rejectedKVPs,
1370 uid_t callingUid) {
1371 auto prefix = String8::format("UID %5d", callingUid);
1372 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1373 if (rejectedKVPSize != 0) {
1374 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1375 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1376 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1377 } else {
1378 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1379 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1380 }
1381}
1382
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001383status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384{
Eric Laurentf1047e82018-04-16 19:18:20 -07001385 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1386 ioHandle, keyValuePairs.string(),
1387 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001388
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389 // check calling permissions
1390 if (!settingsAllowed()) {
1391 return PERMISSION_DENIED;
1392 }
1393
Eric Laurentf1047e82018-04-16 19:18:20 -07001394 String8 filteredKeyValuePairs = keyValuePairs;
1395 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1396
1397 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1398
Glenn Kasten142f5192014-03-25 17:44:59 -07001399 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1400 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001401 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001402 // result will remain NO_INIT if no audio device is present
1403 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001404 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001405 AutoMutex lock(mHardwareLock);
1406 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1407 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001408 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001409 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001410 // return success if at least one audio device accepts the parameters as not all
1411 // HALs are requested to support all parameters. If no audio device supports the
1412 // requested parameters, the last error is reported.
1413 if (final_result != NO_ERROR) {
1414 final_result = result;
1415 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001416 }
1417 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001418 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001419 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001420 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001421 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001422 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1423 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001424 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001425 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001426 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001427 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001428 }
1429 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001430 String8 screenState;
1431 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001432 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001433 if (isOff != (AudioFlinger::mScreenState & 1)) {
1434 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001435 }
1436 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001437 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438 }
1439
1440 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1441 // and the thread is exited once the lock is released
1442 sp<ThreadBase> thread;
1443 {
1444 Mutex::Autolock _l(mLock);
1445 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001446 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001448 if (thread == 0) {
1449 thread = checkMmapThread_l(ioHandle);
1450 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001451 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001452 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001453 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001454 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001455 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1456 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001457 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459 }
1460 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001461 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001462 status_t result = thread->setParameters(filteredKeyValuePairs);
1463 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1464 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001465 }
1466 return BAD_VALUE;
1467}
1468
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001469String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001471 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1472 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473
Eric Laurenta4c5a552012-03-29 10:12:40 -07001474 Mutex::Autolock _l(mLock);
1475
Glenn Kasten142f5192014-03-25 17:44:59 -07001476 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001477 String8 out_s8;
1478
Dima Zavin799a70e2011-04-18 16:57:27 -07001479 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001480 String8 s;
1481 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001482 {
1483 AutoMutex lock(mHardwareLock);
1484 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001485 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1486 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001487 mHardwareStatus = AUDIO_HW_IDLE;
1488 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001489 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001490 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001491 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492 }
1493
Eric Laurent6acd1d42017-01-04 14:23:29 -08001494 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1495 if (thread == NULL) {
1496 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1497 if (thread == NULL) {
1498 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1499 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001500 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001501 }
1502 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001504 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505}
1506
Glenn Kastendd8104c2012-07-02 12:42:44 -07001507size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1508 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509{
Eric Laurenta1884f92011-08-23 08:25:03 -07001510 status_t ret = initCheck();
1511 if (ret != NO_ERROR) {
1512 return 0;
1513 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001514 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001515 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001516 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001517 return 0;
1518 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001519
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001520 AutoMutex lock(mHardwareLock);
1521 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001522 audio_config_t config, proposed;
1523 memset(&proposed, 0, sizeof(proposed));
1524 proposed.sample_rate = sampleRate;
1525 proposed.channel_mask = channelMask;
1526 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001527
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001528 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001529 size_t frames;
1530 for (;;) {
1531 // Note: config is currently a const parameter for get_input_buffer_size()
1532 // but we use a copy from proposed in case config changes from the call.
1533 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001534 status_t result = dev->getInputBufferSize(&config, &frames);
1535 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001536 break; // hal success, config is the result
1537 }
1538 // change one parameter of the configuration each iteration to a more "common" value
1539 // to see if the device will support it.
1540 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1541 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1542 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1543 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1544 } else {
1545 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1546 "format %#x, channelMask 0x%X",
1547 sampleRate, format, channelMask);
1548 break; // retries failed, break out of loop with frames == 0.
1549 }
1550 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001551 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001552 if (frames > 0 && config.sample_rate != sampleRate) {
1553 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1554 }
1555 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556}
1557
Glenn Kasten5f972c02014-01-13 09:59:31 -08001558uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 Mutex::Autolock _l(mLock);
1561
1562 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1563 if (recordThread != NULL) {
1564 return recordThread->getInputFramesLost();
1565 }
1566 return 0;
1567}
1568
1569status_t AudioFlinger::setVoiceVolume(float value)
1570{
Eric Laurenta1884f92011-08-23 08:25:03 -07001571 status_t ret = initCheck();
1572 if (ret != NO_ERROR) {
1573 return ret;
1574 }
1575
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 // check calling permissions
1577 if (!settingsAllowed()) {
1578 return PERMISSION_DENIED;
1579 }
1580
1581 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001582 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001583 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001584 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 mHardwareStatus = AUDIO_HW_IDLE;
1586
1587 return ret;
1588}
1589
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001590status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001591 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 Mutex::Autolock _l(mLock);
1594
1595 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1596 if (playbackThread != NULL) {
1597 return playbackThread->getRenderPosition(halFrames, dspFrames);
1598 }
1599
1600 return BAD_VALUE;
1601}
1602
1603void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1604{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001606 if (client == 0) {
1607 return;
1608 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001609 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001610 {
1611 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001612 if (mNotificationClients.indexOfKey(pid) < 0) {
1613 sp<NotificationClient> notificationClient = new NotificationClient(this,
1614 client,
1615 pid);
1616 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617
Eric Laurent021cf962014-05-13 10:18:14 -07001618 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619
Marco Nelissen06b46062014-11-14 07:58:25 -08001620 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001621 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001622 }
1623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624
Eric Laurent021cf962014-05-13 10:18:14 -07001625 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001626 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001627 // the config change is always sent from playback or record threads to avoid deadlock
1628 // with AudioSystem::gLock
1629 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001630 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001631 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001633 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001634 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 }
1636}
1637
1638void AudioFlinger::removeNotificationClient(pid_t pid)
1639{
1640 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001641 {
1642 Mutex::Autolock _cl(mClientLock);
1643 mNotificationClients.removeItem(pid);
1644 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001645
Steve Block3856b092011-10-20 11:56:00 +01001646 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001647 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001648 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001649 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001650 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001651 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001652 if (ref->mPid == pid) {
1653 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001654 mAudioSessionRefs.removeAt(i);
1655 delete ref;
1656 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001657 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001658 } else {
1659 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001660 }
1661 }
1662 if (removed) {
1663 purgeStaleEffects_l();
1664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665}
1666
Eric Laurent73e26b62015-04-27 16:55:58 -07001667void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001668 const sp<AudioIoDescriptor>& ioDesc,
1669 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670{
Eric Laurent021cf962014-05-13 10:18:14 -07001671 Mutex::Autolock _l(mClientLock);
1672 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001674 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1675 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1676 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677 }
1678}
1679
Eric Laurent021cf962014-05-13 10:18:14 -07001680// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681void AudioFlinger::removeClient_l(pid_t pid)
1682{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001683 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001684 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 mClients.removeItem(pid);
1686}
1687
Eric Laurent717e1282012-06-29 16:36:52 -07001688// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001689sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1690 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001691{
1692 sp<PlaybackThread> thread;
1693
1694 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1695 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1696 ALOG_ASSERT(thread == 0);
1697 thread = mPlaybackThreads.valueAt(i);
1698 }
1699 }
1700
1701 return thread;
1702}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705
1706// ----------------------------------------------------------------------------
1707
1708AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1709 : RefBase(),
1710 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001711 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712{
Andy Hung6f248bb2018-01-23 14:04:37 -08001713 mMemoryDealer = new MemoryDealer(
1714 audioFlinger->getClientSharedHeapSize(),
1715 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716}
1717
Eric Laurent021cf962014-05-13 10:18:14 -07001718// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719AudioFlinger::Client::~Client()
1720{
1721 mAudioFlinger->removeClient_l(mPid);
1722}
1723
Glenn Kasten435dbe62012-01-30 10:15:48 -08001724sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725{
1726 return mMemoryDealer;
1727}
1728
1729// ----------------------------------------------------------------------------
1730
1731AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1732 const sp<IAudioFlingerClient>& client,
1733 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001734 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735{
1736}
1737
1738AudioFlinger::NotificationClient::~NotificationClient()
1739{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740}
1741
Glenn Kasten0f11b512014-01-31 16:18:54 -08001742void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743{
1744 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001745 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746}
1747
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001748// ----------------------------------------------------------------------------
1749AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1750 : mPendingRequests(false) {}
1751
1752
1753void AudioFlinger::MediaLogNotifier::requestMerge() {
1754 AutoMutex _l(mMutex);
1755 mPendingRequests = true;
1756 mCond.signal();
1757}
1758
1759bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001760 // Should already have been checked, but just in case
1761 if (sMediaLogService == 0) {
1762 return false;
1763 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001764 // Wait until there are pending requests
1765 {
1766 AutoMutex _l(mMutex);
1767 mPendingRequests = false; // to ignore past requests
1768 while (!mPendingRequests) {
1769 mCond.wait(mMutex);
1770 // TODO may also need an exitPending check
1771 }
1772 mPendingRequests = false;
1773 }
1774 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001775 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001776 usleep(kPostTriggerSleepPeriod);
1777 return true;
1778}
1779
1780void AudioFlinger::requestLogMerge() {
1781 mMediaLogNotifier->requestMerge();
1782}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783
1784// ----------------------------------------------------------------------------
1785
Eric Laurentf14db3c2017-12-08 14:20:36 -08001786sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1787 CreateRecordOutput& output,
1788 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789{
1790 sp<RecordThread::RecordTrack> recordTrack;
1791 sp<RecordHandle> recordHandle;
1792 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001794 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001795 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796
Eric Laurentf14db3c2017-12-08 14:20:36 -08001797 output.cblk.clear();
1798 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001799 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001800
Eric Laurentf14db3c2017-12-08 14:20:36 -08001801 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001802 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001803 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001804 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001805 ALOGW_IF(clientUid != callingUid,
1806 "%s uid %d tried to pass itself off as %d",
1807 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001808 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001809 updatePid = true;
1810 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001811 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001812 if (updatePid) {
1813 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001814 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001815 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001816 __func__, callingUid, callingPid, clientPid);
1817 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001818 }
1819
Andy Hung6770c6f2015-04-07 13:43:36 -07001820 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001821 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1822 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001823 lStatus = BAD_VALUE;
1824 goto Exit;
1825 }
1826
Glenn Kasten53b5d092014-02-05 10:00:23 -08001827 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001828 if (!audio_is_input_channel(input.config.channel_mask)) {
1829 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001830 lStatus = BAD_VALUE;
1831 goto Exit;
1832 }
1833
Eric Laurentf14db3c2017-12-08 14:20:36 -08001834 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1835 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1836 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1837 lStatus = BAD_VALUE;
1838 goto Exit;
1839 }
1840
1841 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001842 output.selectedDeviceId = input.selectedDeviceId;
1843 output.flags = input.flags;
1844
1845 client = registerPid(clientPid);
1846
1847 // Not a conventional loop, but a retry loop for at most two iterations total.
1848 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1849 // Exits loop via break on no error of got exit on error
1850 // The sp<> references will be dropped when re-entering scope.
1851 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1852 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001853 // release previously opened input if retrying.
1854 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1855 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001856 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001857 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001858 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001859 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001860 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001861 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1862 sessionId,
1863 // FIXME compare to AudioTrack
1864 clientPid,
1865 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001866 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001867 &input.config,
1868 output.flags, &output.selectedDeviceId, &portId);
1869
Glenn Kasten05997e22014-03-13 15:08:33 -07001870 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001872 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001874 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 lStatus = BAD_VALUE;
1876 goto Exit;
1877 }
1878
Eric Laurentf14db3c2017-12-08 14:20:36 -08001879 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880
Eric Laurentf14db3c2017-12-08 14:20:36 -08001881 output.sampleRate = input.config.sample_rate;
1882 output.frameCount = input.frameCount;
1883 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001884
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001885 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001886 input.config.format, input.config.channel_mask,
1887 &output.frameCount, sessionId,
1888 &output.notificationFrameCount,
1889 clientUid, &output.flags,
1890 input.clientInfo.clientTid,
1891 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001892 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001893
Eric Laurentf14db3c2017-12-08 14:20:36 -08001894 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1895 // audio policy manager without FAST constraint
1896 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001897 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001898 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001899
1900 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001901 goto Exit;
1902 }
1903
1904 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1905 // session and move it to this thread.
1906 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1907 if (chain != 0) {
1908 Mutex::Autolock _l(thread->mLock);
1909 thread->addEffectChain_l(chain);
1910 }
1911 break;
1912 }
1913 // End of retry loop.
1914 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915 }
Glenn Kastene198c362013-08-13 09:13:36 -07001916
Eric Laurentf14db3c2017-12-08 14:20:36 -08001917 output.cblk = recordTrack->getCblk();
1918 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001919 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001920
1921 // return handle to client
1922 recordHandle = new RecordHandle(recordTrack);
1923
1924Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001925 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001926 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001927 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001928 // Don't hold mClientLock when releasing the reference on the track as the
1929 // destructor will acquire it.
1930 {
1931 Mutex::Autolock _cl(mClientLock);
1932 client.clear();
1933 }
Eric Laurent896c9672017-12-08 14:08:45 -08001934 recordTrack.clear();
1935 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001936 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 }
1939
Glenn Kasten9156ef32013-08-06 15:39:08 -07001940 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 return recordHandle;
1942}
1943
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001944
1945
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946// ----------------------------------------------------------------------------
1947
Eric Laurenta4c5a552012-03-29 10:12:40 -07001948audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1949{
Eric Laurent44622db2014-08-01 19:00:33 -07001950 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001951 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001952 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001953 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001954 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001955 }
1956 Mutex::Autolock _l(mLock);
1957 return loadHwModule_l(name);
1958}
1959
1960// loadHwModule_l() must be called with AudioFlinger::mLock held
1961audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1962{
1963 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1964 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1965 ALOGW("loadHwModule() module %s already loaded", name);
1966 return mAudioHwDevs.keyAt(i);
1967 }
1968 }
1969
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001970 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001971
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001972 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001973 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001974 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001975 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001976 }
1977
1978 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001979 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001980 mHardwareStatus = AUDIO_HW_IDLE;
1981 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001982 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001983 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001984 }
1985
John Grossmanee578c02012-07-23 17:05:46 -07001986 // Check and cache this HAL's level of support for master mute and master
1987 // volume. If this is the first HAL opened, and it supports the get
1988 // methods, use the initial values provided by the HAL as the current
1989 // master mute and volume settings.
1990
1991 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1992 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001993 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001994
1995 if (0 == mAudioHwDevs.size()) {
1996 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001997 float mv;
1998 if (OK == dev->getMasterVolume(&mv)) {
1999 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002000 }
2001
2002 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002003 bool mm;
2004 if (OK == dev->getMasterMute(&mm)) {
2005 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002006 }
2007 }
2008
Eric Laurenta4c5a552012-03-29 10:12:40 -07002009 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002010 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002011 flags = static_cast<AudioHwDevice::Flags>(flags |
2012 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2013 }
2014
2015 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002016 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002017 flags = static_cast<AudioHwDevice::Flags>(flags |
2018 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2019 }
2020
Eric Laurenta4c5a552012-03-29 10:12:40 -07002021 mHardwareStatus = AUDIO_HW_IDLE;
2022 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002023 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002024 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2025 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2026 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002027
Glenn Kastena13cde92016-03-28 15:26:02 -07002028 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002029 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002030
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002031 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002032
2033 return handle;
2034
2035}
2036
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002037// ----------------------------------------------------------------------------
2038
Glenn Kasten3b16c762012-11-14 08:44:39 -08002039uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
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->sampleRate() : 0;
2044}
2045
Glenn Kastene33054e2012-11-14 12:54:39 -08002046size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002047{
2048 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002049 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002050 return thread != NULL ? thread->frameCountHAL() : 0;
2051}
2052
2053// ----------------------------------------------------------------------------
2054
Andy Hung6f248bb2018-01-23 14:04:37 -08002055status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002056{
2057 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002058 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002059 return PERMISSION_DENIED;
2060 }
2061 Mutex::Autolock _l(mLock);
2062 if (mIsDeviceTypeKnown) {
2063 return INVALID_OPERATION;
2064 }
2065 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002066 mTotalMemory = totalMemory;
2067 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2068 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2069 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2070 // though actual setting is determined through device configuration.
2071 constexpr int64_t GB = 1024 * 1024 * 1024;
2072 mClientSharedHeapSize =
2073 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2074 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2075 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2076 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2077 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002078 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002079
2080 // TODO: Cache the client shared heap size in a persistent property.
2081 // It's possible that a native process or Java service or app accesses audioserver
2082 // after it is registered by system server, but before AudioService updates
2083 // the memory info. This would occur immediately after boot or an audioserver
2084 // crash and restore. Before update from AudioService, the client would get the
2085 // minimum heap size.
2086
2087 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2088 (isLowRamDevice ? "true" : "false"),
2089 (long long)mTotalMemory,
2090 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002091 return NO_ERROR;
2092}
2093
Andy Hung6f248bb2018-01-23 14:04:37 -08002094size_t AudioFlinger::getClientSharedHeapSize() const
2095{
2096 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2097 if (heapSizeInBytes != 0) { // read-only property overrides all.
2098 return heapSizeInBytes;
2099 }
2100 return mClientSharedHeapSize;
2101}
2102
Mikhail Naganovdea53042018-04-26 13:10:21 -07002103status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2104{
2105 ALOGV(__func__);
2106
2107 audio_module_handle_t module;
2108 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2109 module = config->ext.device.hw_module;
2110 } else {
2111 module = config->ext.mix.hw_module;
2112 }
2113
2114 Mutex::Autolock _l(mLock);
2115 ssize_t index = mAudioHwDevs.indexOfKey(module);
2116 if (index < 0) {
2117 ALOGW("%s() bad hw module %d", __func__, module);
2118 return BAD_VALUE;
2119 }
2120
2121 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2122 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2123}
2124
Eric Laurent93c3d412014-08-01 14:48:35 -07002125audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2126{
2127 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002128
2129 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2130 if (index >= 0) {
2131 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2132 mHwAvSyncIds.valueAt(index), sessionId);
2133 return mHwAvSyncIds.valueAt(index);
2134 }
2135
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002136 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002137 if (dev == NULL) {
2138 return AUDIO_HW_SYNC_INVALID;
2139 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002140 String8 reply;
2141 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002142 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002143 param = AudioParameter(reply);
2144 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002145
2146 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002147 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002148 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2149 return AUDIO_HW_SYNC_INVALID;
2150 }
2151
2152 // allow only one session for a given HW A/V sync ID.
2153 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2154 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2155 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2156 value, mHwAvSyncIds.keyAt(i));
2157 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002158 break;
2159 }
2160 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002161
2162 mHwAvSyncIds.add(sessionId, value);
2163
2164 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2165 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2166 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002167 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002168 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002169 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002170 String8 keyValuePairs = param.toString();
2171 thread->setParameters(keyValuePairs);
2172 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2173 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002174 break;
2175 }
2176 }
2177
2178 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2179 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002180}
2181
Eric Laurent72e3f392015-05-20 14:43:50 -07002182status_t AudioFlinger::systemReady()
2183{
2184 Mutex::Autolock _l(mLock);
2185 ALOGI("%s", __FUNCTION__);
2186 if (mSystemReady) {
2187 ALOGW("%s called twice", __FUNCTION__);
2188 return NO_ERROR;
2189 }
2190 mSystemReady = true;
2191 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2192 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2193 thread->systemReady();
2194 }
2195 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2196 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2197 thread->systemReady();
2198 }
2199 return NO_ERROR;
2200}
2201
jiabin46a76fa2018-01-05 10:18:21 -08002202status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2203{
jiabin9ff780e2018-03-19 18:19:52 -07002204 AutoMutex lock(mHardwareLock);
2205 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2206 status_t status = dev->getMicrophones(microphones);
2207 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002208}
2209
Eric Laurentfa90e842014-10-17 18:12:31 -07002210// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2211void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2212{
2213 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2214 if (index >= 0) {
2215 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2216 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2217 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002218 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002219 String8 keyValuePairs = param.toString();
2220 thread->setParameters(keyValuePairs);
2221 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2222 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002223 }
2224}
2225
2226
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002227// ----------------------------------------------------------------------------
2228
Eric Laurent83b88082014-06-20 18:31:16 -07002229
Eric Laurent6acd1d42017-01-04 14:23:29 -08002230sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002231 audio_io_handle_t *output,
2232 audio_config_t *config,
2233 audio_devices_t devices,
2234 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002235 audio_output_flags_t flags)
2236{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002237 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002238 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002239 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002240 }
2241
Eric Laurentcf2c0212014-07-25 16:20:43 -07002242 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002243 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2244 } else {
2245 // Audio Policy does not currently request a specific output handle.
2246 // If this is ever needed, see openInput_l() for example code.
2247 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2248 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002249 }
Eric Laurent83b88082014-06-20 18:31:16 -07002250
2251 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2252
Eric Laurent83b88082014-06-20 18:31:16 -07002253 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002254 // This if statement allows overriding the audio policy settings
2255 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2256 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2257 // Check only for Normal Mixing mode
2258 if (kEnableExtendedPrecision) {
2259 // Specify format (uncomment one below to choose)
2260 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2261 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2262 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2263 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002264 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002265 }
2266 if (kEnableExtendedChannels) {
2267 // Specify channel mask (uncomment one below to choose)
2268 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2269 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2270 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2271 }
Eric Laurent83b88082014-06-20 18:31:16 -07002272 }
2273
Phil Burk062e67a2015-02-11 13:40:50 -08002274 AudioStreamOut *outputStream = NULL;
2275 status_t status = outHwDev->openOutputStream(
2276 &outputStream,
2277 *output,
2278 devices,
2279 flags,
2280 config,
2281 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002282
2283 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002284
Phil Burk062e67a2015-02-11 13:40:50 -08002285 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002286 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2287 sp<MmapPlaybackThread> thread =
2288 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2289 devices, AUDIO_DEVICE_NONE, mSystemReady);
2290 mMmapThreads.add(*output, thread);
2291 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2292 *output, thread.get());
2293 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002294 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002295 sp<PlaybackThread> thread;
2296 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2297 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2298 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2299 *output, thread.get());
2300 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2301 || !isValidPcmSinkFormat(config->format)
2302 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2303 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2304 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2305 *output, thread.get());
2306 } else {
2307 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2308 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2309 *output, thread.get());
2310 }
2311 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002312 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002313 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002314 }
Eric Laurent83b88082014-06-20 18:31:16 -07002315 }
2316
2317 return 0;
2318}
2319
Eric Laurentcf2c0212014-07-25 16:20:43 -07002320status_t AudioFlinger::openOutput(audio_module_handle_t module,
2321 audio_io_handle_t *output,
2322 audio_config_t *config,
2323 audio_devices_t *devices,
2324 const String8& address,
2325 uint32_t *latencyMs,
2326 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002328 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2329 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002330 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002331 (devices != NULL) ? *devices : 0,
2332 config->sample_rate,
2333 config->format,
2334 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002335 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002337 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002338 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002340
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341 Mutex::Autolock _l(mLock);
2342
Eric Laurent6acd1d42017-01-04 14:23:29 -08002343 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002344 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002345 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2346 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2347 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348
Eric Laurent6acd1d42017-01-04 14:23:29 -08002349 // notify client processes of the new output creation
2350 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002351
Eric Laurent6acd1d42017-01-04 14:23:29 -08002352 // the first primary output opened designates the primary hw device
2353 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002354 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002355 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002356
Eric Laurent6acd1d42017-01-04 14:23:29 -08002357 AutoMutex lock(mHardwareLock);
2358 mHardwareStatus = AUDIO_HW_SET_MODE;
2359 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2360 mHardwareStatus = AUDIO_HW_IDLE;
2361 }
2362 } else {
2363 MmapThread *mmapThread = (MmapThread *)thread.get();
2364 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002365 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002366 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 }
2368
Eric Laurentcf2c0212014-07-25 16:20:43 -07002369 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370}
2371
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002372audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2373 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374{
2375 Mutex::Autolock _l(mLock);
2376 MixerThread *thread1 = checkMixerThread_l(output1);
2377 MixerThread *thread2 = checkMixerThread_l(output2);
2378
2379 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002380 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2381 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002382 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383 }
2384
Glenn Kasteneeecb982016-02-26 10:44:04 -08002385 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002386 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 thread->addOutputTrack(thread2);
2388 mPlaybackThreads.add(id, thread);
2389 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002390 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 return id;
2392}
2393
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002394status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395{
Glenn Kastend96c5722012-04-25 13:44:49 -07002396 return closeOutput_nonvirtual(output);
2397}
2398
2399status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2400{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 // keep strong reference on the playback thread so that
2402 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002403 sp<PlaybackThread> playbackThread;
2404 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 {
2406 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002407 playbackThread = checkPlaybackThread_l(output);
2408 if (playbackThread != NULL) {
2409 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410
Andy Hungdc099c22018-09-18 13:46:39 -07002411 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002412
Eric Laurent6acd1d42017-01-04 14:23:29 -08002413 if (playbackThread->type() == ThreadBase::MIXER) {
2414 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2415 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2416 DuplicatingThread *dupThread =
2417 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2418 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2419 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002420 }
2421 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002422
2423
Eric Laurent6acd1d42017-01-04 14:23:29 -08002424 mPlaybackThreads.removeItem(output);
2425 // save all effects to the default thread
2426 if (mPlaybackThreads.size()) {
2427 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2428 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002429 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002430 Mutex::Autolock _dl(dstThread->mLock);
2431 Mutex::Autolock _sl(playbackThread->mLock);
2432 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2433 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002434 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2435 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 }
2438 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002439 } else {
2440 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2441 if (mmapThread == 0) {
2442 return BAD_VALUE;
2443 }
Andy Hungdc099c22018-09-18 13:46:39 -07002444 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002445 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002446 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002448 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2449 ioDesc->mIoHandle = output;
2450 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002451 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002453 // The thread entity (active unit of execution) is no longer running here,
2454 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002455
Eric Laurent6acd1d42017-01-04 14:23:29 -08002456 if (playbackThread != 0) {
2457 playbackThread->exit();
2458 if (!playbackThread->isDuplicating()) {
2459 closeOutputFinish(playbackThread);
2460 }
2461 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002462 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002463 mmapThread->exit();
2464 AudioStreamOut *out = mmapThread->clearOutput();
2465 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2466 // from now on thread->mOutput is NULL
2467 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 }
2469 return NO_ERROR;
2470}
2471
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002472void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002473{
2474 AudioStreamOut *out = thread->clearOutput();
2475 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2476 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002477 delete out;
2478}
2479
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002480void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002481{
2482 mPlaybackThreads.removeItem(thread->mId);
2483 thread->exit();
2484 closeOutputFinish(thread);
2485}
2486
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002487status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488{
2489 Mutex::Autolock _l(mLock);
2490 PlaybackThread *thread = checkPlaybackThread_l(output);
2491
2492 if (thread == NULL) {
2493 return BAD_VALUE;
2494 }
2495
Steve Block3856b092011-10-20 11:56:00 +01002496 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497 thread->suspend();
2498
2499 return NO_ERROR;
2500}
2501
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002502status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503{
2504 Mutex::Autolock _l(mLock);
2505 PlaybackThread *thread = checkPlaybackThread_l(output);
2506
2507 if (thread == NULL) {
2508 return BAD_VALUE;
2509 }
2510
Steve Block3856b092011-10-20 11:56:00 +01002511 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512
2513 thread->restore();
2514
2515 return NO_ERROR;
2516}
2517
Eric Laurentcf2c0212014-07-25 16:20:43 -07002518status_t AudioFlinger::openInput(audio_module_handle_t module,
2519 audio_io_handle_t *input,
2520 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002521 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002522 const String8& address,
2523 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002524 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525{
Eric Laurent83b88082014-06-20 18:31:16 -07002526 Mutex::Autolock _l(mLock);
2527
Glenn Kastene7d66712015-03-05 13:46:52 -08002528 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002529 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002530 }
2531
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002532 sp<ThreadBase> thread = openInput_l(
2533 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002534
2535 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002536 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002537 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002538 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002540 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002541}
Dima Zavin799a70e2011-04-18 16:57:27 -07002542
Eric Laurent6acd1d42017-01-04 14:23:29 -08002543sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002544 audio_io_handle_t *input,
2545 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002546 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002547 const String8& address,
2548 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002549 audio_input_flags_t flags,
2550 audio_devices_t outputDevice,
2551 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002552{
Glenn Kastene7d66712015-03-05 13:46:52 -08002553 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002554 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002555 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002556 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002557 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002558
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002559 // Some flags are specific to framework and must not leak to the HAL.
2560 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2561
Glenn Kasteneeecb982016-02-26 10:44:04 -08002562 // Audio Policy can request a specific handle for hardware hotword.
2563 // The goal here is not to re-open an already opened input.
2564 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002565 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002566 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2567 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2568 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2569 return 0;
2570 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2571 // This should not happen in a transient state with current design.
2572 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2573 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002574 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002575
Eric Laurentcf2c0212014-07-25 16:20:43 -07002576 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002577 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002578 sp<StreamInHalInterface> inStream;
2579 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002580 *input, devices, &halconfig, flags, address.string(), source,
2581 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002582 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2583 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002584 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002585 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002586 halconfig.sample_rate,
2587 halconfig.format,
2588 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002589 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002590 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002592 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002593 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002594 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002595 audio_is_linear_pcm(config->format) &&
2596 audio_is_linear_pcm(halconfig.format) &&
2597 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002598 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2599 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002600 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002601 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002602 inStream.clear();
2603 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002604 *input, devices, &halconfig, flags, address.string(), source,
2605 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002606 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 }
2608
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002609 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002610 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002611 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2612 sp<MmapCaptureThread> thread =
2613 new MmapCaptureThread(this, *input,
2614 inHwDev, inputStream,
2615 primaryOutputDevice_l(), devices, mSystemReady);
2616 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002617 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2618 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002619 return thread;
2620 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002621 // Start record thread
2622 // RecordThread requires both input and output device indication to forward to audio
2623 // pre processing modules
2624 sp<RecordThread> thread = new RecordThread(this,
2625 inputStream,
2626 *input,
2627 primaryOutputDevice_l(),
2628 devices,
2629 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002630 );
2631 mRecordThreads.add(*input, thread);
2632 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2633 return thread;
2634 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 }
2636
Eric Laurentcf2c0212014-07-25 16:20:43 -07002637 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 return 0;
2639}
2640
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002641status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642{
Glenn Kastend96c5722012-04-25 13:44:49 -07002643 return closeInput_nonvirtual(input);
2644}
2645
2646status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2647{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 // keep strong reference on the record thread so that
2649 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002650 sp<RecordThread> recordThread;
2651 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 {
2653 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002654 recordThread = checkRecordThread_l(input);
2655 if (recordThread != 0) {
2656 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
Andy Hungdc099c22018-09-18 13:46:39 -07002658 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002659
Eric Laurent6acd1d42017-01-04 14:23:29 -08002660 // If we still have effect chains, it means that a client still holds a handle
2661 // on at least one effect. We must either move the chain to an existing thread with the
2662 // same session ID or put it aside in case a new record thread is opened for a
2663 // new capture on the same session
2664 sp<EffectChain> chain;
2665 {
2666 Mutex::Autolock _sl(recordThread->mLock);
2667 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2668 // Note: maximum one chain per record thread
2669 if (effectChains.size() != 0) {
2670 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002671 }
2672 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002673 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002674 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002675 // This should only happen in case of overlap between one thread tear down and the
2676 // creation of its replacement
2677 size_t i;
2678 for (i = 0; i < mRecordThreads.size(); i++) {
2679 sp<RecordThread> t = mRecordThreads.valueAt(i);
2680 if (t == recordThread) {
2681 continue;
2682 }
2683 if (t->hasAudioSession(chain->sessionId()) != 0) {
2684 Mutex::Autolock _l(t->mLock);
2685 ALOGV("closeInput() found thread %d for effect session %d",
2686 t->id(), chain->sessionId());
2687 t->addEffectChain_l(chain);
2688 break;
2689 }
2690 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002691 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002692 if (i == mRecordThreads.size()) {
2693 putOrphanEffectChain_l(chain);
2694 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002695 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002696 mRecordThreads.removeItem(input);
2697 } else {
2698 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2699 if (mmapThread == 0) {
2700 return BAD_VALUE;
2701 }
Andy Hungdc099c22018-09-18 13:46:39 -07002702 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002703 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002704 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002705 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2706 ioDesc->mIoHandle = input;
2707 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 }
Eric Laurent83b88082014-06-20 18:31:16 -07002709 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2710 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002711 if (recordThread != 0) {
2712 closeInputFinish(recordThread);
2713 } else if (mmapThread != 0) {
2714 mmapThread->exit();
2715 AudioStreamIn *in = mmapThread->clearInput();
2716 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2717 // from now on thread->mInput is NULL
2718 delete in;
2719 }
Eric Laurent83b88082014-06-20 18:31:16 -07002720 return NO_ERROR;
2721}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002723void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002724{
2725 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002726 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002727 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002728 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002729 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002730}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002732void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002733{
2734 mRecordThreads.removeItem(thread->mId);
2735 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736}
2737
Glenn Kastend2304db2014-02-03 07:40:31 -08002738status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739{
2740 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002741 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742
2743 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2744 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002745 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002746 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002747 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2748 mMmapThreads[i]->invalidateTracks(stream);
2749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002750 return NO_ERROR;
2751}
2752
2753
Glenn Kasteneeecb982016-02-26 10:44:04 -08002754audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755{
Glenn Kasten9d003132016-04-06 14:38:09 -07002756 // This is a binder API, so a malicious client could pass in a bad parameter.
2757 // Check for that before calling the internal API nextUniqueId().
2758 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2759 ALOGE("newAudioUniqueId invalid use %d", use);
2760 return AUDIO_UNIQUE_ID_ALLOCATE;
2761 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002762 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763}
2764
Glenn Kastend848eb42016-03-08 13:42:11 -08002765void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002766{
2767 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002768 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002769 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002770 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2771 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002772 caller = pid;
2773 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002774
Eric Laurent021cf962014-05-13 10:18:14 -07002775 {
2776 Mutex::Autolock _cl(mClientLock);
2777 // Ignore requests received from processes not known as notification client. The request
2778 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2779 // called from a different pid leaving a stale session reference. Also we don't know how
2780 // to clear this reference if the client process dies.
2781 if (mNotificationClients.indexOfKey(caller) < 0) {
2782 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2783 return;
2784 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002785 }
2786
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002787 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002788 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002789 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002790 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2791 ref->mCnt++;
2792 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002793 return;
2794 }
2795 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002796 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2797 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002798}
2799
Glenn Kastend848eb42016-03-08 13:42:11 -08002800void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002801{
2802 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002803 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002804 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002805 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2806 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002807 caller = pid;
2808 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002809 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002810 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002811 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002812 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2813 ref->mCnt--;
2814 ALOGV(" decremented refcount to %d", ref->mCnt);
2815 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002816 mAudioSessionRefs.removeAt(i);
2817 delete ref;
2818 purgeStaleEffects_l();
2819 }
2820 return;
2821 }
2822 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002823 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002824 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002825 ALOGW_IF(!isAudioServerUid(callerUid),
2826 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002827}
2828
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002829bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2830{
2831 size_t num = mAudioSessionRefs.size();
2832 for (size_t i = 0; i < num; i++) {
2833 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2834 if (ref->mSessionid == audioSession) {
2835 return true;
2836 }
2837 }
2838 return false;
2839}
2840
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002841void AudioFlinger::purgeStaleEffects_l() {
2842
Steve Block3856b092011-10-20 11:56:00 +01002843 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002844
2845 Vector< sp<EffectChain> > chains;
2846
2847 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2848 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002849 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002850 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2851 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002852 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2853 chains.push(ec);
2854 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002855 }
2856 }
2857 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2858 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002859 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002860 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2861 sp<EffectChain> ec = t->mEffectChains[j];
2862 chains.push(ec);
2863 }
2864 }
2865
2866 for (size_t i = 0; i < chains.size(); i++) {
2867 sp<EffectChain> ec = chains[i];
2868 int sessionid = ec->sessionId();
2869 sp<ThreadBase> t = ec->mThread.promote();
2870 if (t == 0) {
2871 continue;
2872 }
2873 size_t numsessionrefs = mAudioSessionRefs.size();
2874 bool found = false;
2875 for (size_t k = 0; k < numsessionrefs; k++) {
2876 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002877 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002878 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002879 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002880 found = true;
2881 break;
2882 }
2883 }
2884 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002885 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002886 // remove all effects from the chain
2887 while (ec->mEffects.size()) {
2888 sp<EffectModule> effect = ec->mEffects[0];
2889 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002890 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002891 if (effect->purgeHandles()) {
2892 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002893 }
2894 AudioSystem::unregisterEffect(effect->id());
2895 }
2896 }
2897 }
2898 return;
2899}
2900
Andy Hungdc099c22018-09-18 13:46:39 -07002901// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2902void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2903{
2904 audio_utils::FdToString fdToString;
2905 const int fd = fdToString.fd();
2906 if (fd >= 0) {
2907 thread->dump(fd, {} /* args */);
2908 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2909 }
2910}
2911
Glenn Kasteneeecb982016-02-26 10:44:04 -08002912// checkThread_l() must be called with AudioFlinger::mLock held
2913AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2914{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002915 ThreadBase *thread = checkMmapThread_l(ioHandle);
2916 if (thread == 0) {
2917 switch (audio_unique_id_get_use(ioHandle)) {
2918 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2919 thread = checkPlaybackThread_l(ioHandle);
2920 break;
2921 case AUDIO_UNIQUE_ID_USE_INPUT:
2922 thread = checkRecordThread_l(ioHandle);
2923 break;
2924 default:
2925 break;
2926 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002927 }
2928 return thread;
2929}
2930
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002932AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933{
Glenn Kastena1117922012-01-26 10:53:32 -08002934 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935}
2936
2937// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002938AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939{
2940 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002941 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942}
2943
2944// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002945AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946{
Glenn Kastena1117922012-01-26 10:53:32 -08002947 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948}
2949
Eric Laurent6acd1d42017-01-04 14:23:29 -08002950// checkMmapThread_l() must be called with AudioFlinger::mLock held
2951AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2952{
2953 return mMmapThreads.valueFor(io).get();
2954}
2955
2956
2957// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2958AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2959{
Eric Laurent7459b902017-04-19 18:10:41 -07002960 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002961 if (volumeInterface == nullptr) {
2962 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2963 if (mmapThread != nullptr) {
2964 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002965 MmapPlaybackThread *mmapPlaybackThread =
2966 static_cast<MmapPlaybackThread *>(mmapThread);
2967 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002968 }
2969 }
2970 }
2971 return volumeInterface;
2972}
2973
2974Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2975{
2976 Vector <VolumeInterface *> volumeInterfaces;
2977 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002978 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002979 }
2980 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2981 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002982 MmapPlaybackThread *mmapPlaybackThread =
2983 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2984 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002985 }
2986 }
2987 return volumeInterfaces;
2988}
2989
Glenn Kasteneeecb982016-02-26 10:44:04 -08002990audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991{
Glenn Kasten9d003132016-04-06 14:38:09 -07002992 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002993 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002994 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2995 for (int retry = 0; retry < maxRetries; retry++) {
2996 // The cast allows wraparound from max positive to min negative instead of abort
2997 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2998 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2999 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3000 // allow wrap by skipping 0 and -1 for session ids
3001 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3002 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3003 return (audio_unique_id_t) (base | use);
3004 }
3005 }
3006 // We have no way of recovering from wraparound
3007 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3008 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009}
3010
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003011AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003012{
3013 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3014 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003015 if(thread->isDuplicating()) {
3016 continue;
3017 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003018 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003019 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003020 return thread;
3021 }
3022 }
3023 return NULL;
3024}
3025
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003026audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003027{
3028 PlaybackThread *thread = primaryPlaybackThread_l();
3029
3030 if (thread == NULL) {
3031 return 0;
3032 }
3033
Eric Laurentf1c04f92012-08-28 14:26:53 -07003034 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003035}
3036
Glenn Kastena7335632016-06-09 17:09:53 -07003037AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3038{
3039 size_t minFrameCount = 0;
3040 PlaybackThread *minThread = NULL;
3041 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3042 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3043 if (!thread->isDuplicating()) {
3044 size_t frameCount = thread->frameCountHAL();
3045 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3046 (frameCount == minFrameCount && thread->hasFastMixer() &&
3047 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3048 minFrameCount = frameCount;
3049 minThread = thread;
3050 }
3051 }
3052 }
3053 return minThread;
3054}
3055
Eric Laurenta011e352012-03-29 15:51:43 -07003056sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003057 audio_session_t triggerSession,
3058 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003059 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003060 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003061{
3062 Mutex::Autolock _l(mLock);
3063
3064 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3065 status_t playStatus = NAME_NOT_FOUND;
3066 status_t recStatus = NAME_NOT_FOUND;
3067 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3068 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3069 if (playStatus == NO_ERROR) {
3070 return event;
3071 }
3072 }
3073 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3074 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3075 if (recStatus == NO_ERROR) {
3076 return event;
3077 }
3078 }
3079 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3080 mPendingSyncEvents.add(event);
3081 } else {
3082 ALOGV("createSyncEvent() invalid event %d", event->type());
3083 event.clear();
3084 }
3085 return event;
3086}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003087
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088// ----------------------------------------------------------------------------
3089// Effect management
3090// ----------------------------------------------------------------------------
3091
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003092sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3093 return mEffectsFactoryHal;
3094}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095
Glenn Kastenf587ba52012-01-26 16:25:10 -08003096status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097{
3098 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003099 if (mEffectsFactoryHal.get()) {
3100 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3101 } else {
3102 return -ENODEV;
3103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104}
3105
Glenn Kastenf587ba52012-01-26 16:25:10 -08003106status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107{
3108 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003109 if (mEffectsFactoryHal.get()) {
3110 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3111 } else {
3112 return -ENODEV;
3113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114}
3115
Glenn Kasten5e92a782012-01-30 07:40:52 -08003116status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003117 const effect_uuid_t *pTypeUuid,
3118 uint32_t preferredTypeFlag,
3119 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003121 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3122 return BAD_VALUE;
3123 }
3124
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003126
3127 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003128 return -ENODEV;
3129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003131 status_t status = NO_ERROR;
3132 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3133 // If uuid is specified, request effect descriptor from that.
3134 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3135 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3136 // If uuid is not specified, look for an available implementation
3137 // of the required type instead.
3138
3139 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3140 effect_descriptor_t desc;
3141 desc.flags = 0; // prevent compiler warning
3142
3143 uint32_t numEffects = 0;
3144 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3145 if (status < 0) {
3146 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3147 return status;
3148 }
3149
3150 bool found = false;
3151 for (uint32_t i = 0; i < numEffects; i++) {
3152 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3153 if (status < 0) {
3154 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3155 continue;
3156 }
3157 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3158 // If matching type found save effect descriptor.
3159 found = true;
3160 *descriptor = desc;
3161
3162 // If there's no preferred flag or this descriptor matches the preferred
3163 // flag, success! If this descriptor doesn't match the preferred
3164 // flag, continue enumeration in case a better matching version of this
3165 // effect type is available. Note that this means if no effect with a
3166 // correct flag is found, the descriptor returned will correspond to the
3167 // last effect that at least had a matching type uuid (if any).
3168 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3169 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3170 break;
3171 }
3172 }
3173 }
3174
3175 if (!found) {
3176 status = NAME_NOT_FOUND;
3177 ALOGW("getEffectDescriptor(): Effect not found by type.");
3178 }
3179 } else {
3180 status = BAD_VALUE;
3181 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3182 }
3183 return status;
3184}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003186sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 effect_descriptor_t *pDesc,
3188 const sp<IEffectClient>& effectClient,
3189 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003190 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003191 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003192 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003193 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 status_t *status,
3195 int *id,
3196 int *enabled)
3197{
3198 status_t lStatus = NO_ERROR;
3199 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201
Eric Laurentb6436272016-12-07 19:24:50 -08003202 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003203 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003204 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3205 ALOGW_IF(pid != -1 && pid != callingPid,
3206 "%s uid %d pid %d tried to pass itself off as pid %d",
3207 __func__, callingUid, callingPid, pid);
3208 pid = callingPid;
3209 }
3210
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003211 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3212 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213
3214 if (pDesc == NULL) {
3215 lStatus = BAD_VALUE;
3216 goto Exit;
3217 }
3218
Eric Laurent84e9a102010-09-23 16:10:16 -07003219 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003220 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003221 lStatus = PERMISSION_DENIED;
3222 goto Exit;
3223 }
3224
Dima Zavinfce7a472011-04-19 22:30:36 -07003225 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003226 // that can only be created by audio policy manager
3227 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003228 lStatus = PERMISSION_DENIED;
3229 goto Exit;
3230 }
3231
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003232 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003233 lStatus = NO_INIT;
3234 goto Exit;
3235 }
3236
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003238 // Get the full effect descriptor from the uuid/type.
3239 // If the session is the output mix, prefer an auxiliary effect,
3240 // otherwise no preference.
3241 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3242 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3243 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3244 if (lStatus < 0) {
3245 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3246 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 }
3248
3249 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003250 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3252 lStatus = INVALID_OPERATION;
3253 goto Exit;
3254 }
3255
Eric Laurent59255e42011-07-27 19:49:51 -07003256 // check recording permission for visualizer
3257 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003258 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003259 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003260 lStatus = PERMISSION_DENIED;
3261 goto Exit;
3262 }
3263
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003265 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003266 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003267 // if the output returned by getOutputForEffect() is removed before we lock the
3268 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3269 // and we will exit safely
3270 io = AudioSystem::getOutputForEffect(&desc);
3271 ALOGV("createEffect got output %d", io);
3272 }
3273
3274 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275
3276 // If output is not specified try to find a matching audio session ID in one of the
3277 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003278 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3279 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003280 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003281 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003282 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3283 // output must be specified by AudioPolicyManager when using session
3284 // AUDIO_SESSION_OUTPUT_STAGE
3285 lStatus = BAD_VALUE;
3286 goto Exit;
3287 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003288 // look for the thread where the specified audio session is present
3289 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Weiyin Jiang9aeb1772018-04-27 00:39:29 +08003290 uint32_t sessionType = mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3291 if (sessionType != 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003292 io = mPlaybackThreads.keyAt(i);
Weiyin Jiang9aeb1772018-04-27 00:39:29 +08003293 // thread with same effect session is preferable
3294 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3295 break;
3296 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003297 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003299 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003300 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3301 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3302 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003303 break;
3304 }
3305 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003306 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003307 if (io == AUDIO_IO_HANDLE_NONE) {
3308 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3309 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3310 io = mMmapThreads.keyAt(i);
3311 break;
3312 }
3313 }
3314 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003315 // If no output thread contains the requested session ID, default to
3316 // first output. The effect chain will be moved to the correct output
3317 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003318 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003319 io = mPlaybackThreads.keyAt(0);
3320 }
Steve Block3856b092011-10-20 11:56:00 +01003321 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003322 } else if (checkPlaybackThread_l(io) != nullptr) {
3323 // allow only one effect chain per sessionId on mPlaybackThreads.
3324 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3325 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3326 if (io == checkIo) continue;
3327 const uint32_t sessionType =
3328 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3329 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3330 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3331 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3332 android_errorWriteLog(0x534e4554, "123237974");
3333 lStatus = BAD_VALUE;
3334 goto Exit;
3335 }
3336 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003337 }
3338 ThreadBase *thread = checkRecordThread_l(io);
3339 if (thread == NULL) {
3340 thread = checkPlaybackThread_l(io);
3341 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003342 thread = checkMmapThread_l(io);
3343 if (thread == NULL) {
3344 ALOGE("createEffect() unknown output thread");
3345 lStatus = BAD_VALUE;
3346 goto Exit;
3347 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003348 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003349 } else {
3350 // Check if one effect chain was awaiting for an effect to be created on this
3351 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003352 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003353 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003354 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003355 thread->addEffectChain_l(chain);
3356 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003358
Eric Laurent021cf962014-05-13 10:18:14 -07003359 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003361 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003362 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003363 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003364 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003365 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003366 // remove local strong reference to Client with mClientLock held
3367 Mutex::Autolock _cl(mClientLock);
3368 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003369 } else {
3370 // handle must be valid here, but check again to be safe.
3371 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003372 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 }
3374
haobo101735295ff7b0d2017-03-17 17:44:03 +08003375 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3376 // handle must be cleared outside lock.
3377 handle.clear();
3378 }
3379
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003381 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 return handle;
3383}
3384
Glenn Kastend848eb42016-03-08 13:42:11 -08003385status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003386 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003387{
Steve Block3856b092011-10-20 11:56:00 +01003388 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003389 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003390 Mutex::Autolock _l(mLock);
3391 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003392 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003393 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 }
Eric Laurentde070132010-07-13 04:45:46 -07003395 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3396 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003397 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003398 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 }
Eric Laurentde070132010-07-13 04:45:46 -07003400 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3401 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003402 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003403 return BAD_VALUE;
3404 }
3405
3406 Mutex::Autolock _dl(dstThread->mLock);
3407 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003408 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409}
3410
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003411// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003412status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003413 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003414 AudioFlinger::PlaybackThread *dstThread,
3415 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003416{
Steve Block3856b092011-10-20 11:56:00 +01003417 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003418 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003419
Eric Laurent59255e42011-07-27 19:49:51 -07003420 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003421 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003422 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003423 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003424 return INVALID_OPERATION;
3425 }
3426
Eric Laurent4c415062016-06-17 16:14:16 -07003427 // Check whether the destination thread and all effects in the chain are compatible
3428 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003429 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003430 " destination thread %p is not compatible with effects in the chain",
3431 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003432 return INVALID_OPERATION;
3433 }
3434
Eric Laurent39e94f82010-07-28 01:32:47 -07003435 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003436 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003437 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003438 // removed.
3439 srcThread->removeEffectChain_l(chain);
3440
3441 // transfer all effects one by one so that new effect chain is created on new thread with
3442 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003443 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003444 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003445 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003446 Vector< sp<EffectModule> > removed;
3447 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003448 while (effect != 0) {
3449 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003450 removed.add(effect);
3451 status = dstThread->addEffect_l(effect);
3452 if (status != NO_ERROR) {
3453 break;
3454 }
Eric Laurentec35a142011-10-05 17:42:25 -07003455 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3456 if (effect->state() == EffectModule::ACTIVE ||
3457 effect->state() == EffectModule::STOPPING) {
3458 effect->start();
3459 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003460 // if the move request is not received from audio policy manager, the effect must be
3461 // re-registered with the new strategy and output
3462 if (dstChain == 0) {
3463 dstChain = effect->chain().promote();
3464 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003465 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003466 status = NO_INIT;
3467 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003468 }
3469 strategy = dstChain->strategy();
3470 }
3471 if (reRegister) {
3472 AudioSystem::unregisterEffect(effect->id());
3473 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003474 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003475 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003476 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003477 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003478 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003479 }
Eric Laurentde070132010-07-13 04:45:46 -07003480 effect = chain->getEffectFromId_l(0);
3481 }
3482
Eric Laurent5baf2af2013-09-12 17:37:00 -07003483 if (status != NO_ERROR) {
3484 for (size_t i = 0; i < removed.size(); i++) {
3485 srcThread->addEffect_l(removed[i]);
3486 if (dstChain != 0 && reRegister) {
3487 AudioSystem::unregisterEffect(removed[i]->id());
3488 AudioSystem::registerEffect(&removed[i]->desc(),
3489 srcThread->id(),
3490 strategy,
3491 sessionId,
3492 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003493 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003494 }
3495 }
3496 }
3497
3498 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499}
3500
Eric Laurent5baf2af2013-09-12 17:37:00 -07003501bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003502{
3503 if (mGlobalEffectEnableTime != 0 &&
3504 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3505 return true;
3506 }
3507
3508 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3509 sp<EffectChain> ec =
3510 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003511 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003512 return true;
3513 }
3514 }
3515 return false;
3516}
3517
Eric Laurent5baf2af2013-09-12 17:37:00 -07003518void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003519{
3520 Mutex::Autolock _l(mLock);
3521
3522 mGlobalEffectEnableTime = systemTime();
3523
3524 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3525 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3526 if (t->mType == ThreadBase::OFFLOAD) {
3527 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3528 }
3529 }
3530
3531}
3532
Eric Laurentaaa44472014-09-12 17:41:50 -07003533status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3534{
Eric Laurentd8365c52017-07-16 15:27:05 -07003535 // clear possible suspended state before parking the chain so that it starts in default state
3536 // when attached to a new record thread
3537 chain->setEffectSuspended_l(FX_IID_AEC, false);
3538 chain->setEffectSuspended_l(FX_IID_NS, false);
3539
Glenn Kastend848eb42016-03-08 13:42:11 -08003540 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003541 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003542 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003543 if (index >= 0) {
3544 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3545 return ALREADY_EXISTS;
3546 }
3547 mOrphanEffectChains.add(session, chain);
3548 return NO_ERROR;
3549}
3550
3551sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3552{
3553 sp<EffectChain> chain;
3554 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003555 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003556 if (index >= 0) {
3557 chain = mOrphanEffectChains.valueAt(index);
3558 mOrphanEffectChains.removeItemsAt(index);
3559 }
3560 return chain;
3561}
3562
3563bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3564{
3565 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003566 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003567 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003568 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003569 if (index >= 0) {
3570 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003571 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003572 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003573 mOrphanEffectChains.removeItemsAt(index);
3574 }
3575 return true;
3576 }
3577 return false;
3578}
3579
3580
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581// ----------------------------------------------------------------------------
3582
3583status_t AudioFlinger::onTransact(
3584 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3585{
3586 return BnAudioFlinger::onTransact(code, data, reply, flags);
3587}
3588
Glenn Kasten63238ef2015-03-02 15:50:29 -08003589} // namespace android