blob: 4b318166cbe55f135d1a5a1d79cd5580e8f8ad68 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/time.h>
28#include <sys/resource.h>
29
jiabin57303cc2018-12-18 15:45:57 -080030#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070036#include <media/audiohal/DeviceHalInterface.h>
37#include <media/audiohal/DevicesFactoryHalInterface.h>
38#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070039#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070041#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <utils/String16.h>
43#include <utils/threads.h>
44
Steven Morelandf0c02ce2018-02-23 14:53:55 -080045#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/properties.h>
47
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070051#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Andy Hung6770c6f2015-04-07 13:43:36 -070053#include <media/AudioResamplerPublic.h>
54
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_visualizer.h>
56#include <system/audio_effects/effect_ns.h>
57#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070068#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080074#include "TypedLogger.h"
75
Mathias Agopian65ab4712010-07-14 17:59:35 -070076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
John Grossman1c345192012-03-27 14:00:17 -070078// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
Eric Laurentde070132010-07-13 04:45:46 -070090
Mathias Agopian65ab4712010-07-14 17:59:35 -070091namespace android {
92
Glenn Kastenec1d6b52011-12-12 09:04:45 -080093static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
94static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070095static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070096static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten58912562012-04-03 10:45:00 -070098
John Grossman4ff14ba2012-02-08 16:37:41 -080099nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700102
Eric Laurent813e2a72013-08-31 12:59:48 -0700103// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
104// we define a minimum time during which a global effect is considered enabled.
105static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
106
Eric Laurentfc235202016-12-20 18:48:17 -0800107Mutex gLock;
108wp<AudioFlinger> gAudioFlinger;
109
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700110// Keep a strong reference to media.log service around forever.
111// The service is within our parent process so it can never die in a way that we could observe.
112// These two variables are const after initialization.
113static sp<IBinder> sMediaLogServiceAsBinder;
114static sp<IMediaLogService> sMediaLogService;
115
116static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
117
118static void sMediaLogInit()
119{
120 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
121 if (sMediaLogServiceAsBinder != 0) {
122 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
123 }
124}
125
jiabin57303cc2018-12-18 15:45:57 -0800126// Keep a strong reference to external vibrator service
127static sp<os::IExternalVibratorService> sExternalVibratorService;
128
129static sp<os::IExternalVibratorService> getExternalVibratorService() {
130 if (sExternalVibratorService == 0) {
131 sp <IBinder> binder = defaultServiceManager()->getService(
132 String16("external_vibrator_service"));
133 if (binder != 0) {
134 sExternalVibratorService =
135 interface_cast<os::IExternalVibratorService>(binder);
136 }
137 }
138 return sExternalVibratorService;
139}
140
Mathias Agopian65ab4712010-07-14 17:59:35 -0700141// ----------------------------------------------------------------------------
142
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700143std::string formatToString(audio_format_t format) {
144 std::string result;
145 FormatConverter::toString(format, result);
146 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800147}
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800153 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800155 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700156 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700159 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800160 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700161 mBtNrecIsOff(false),
162 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700163 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800164 mTotalMemory(0),
165 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700166 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700167 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700168 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700170 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
171 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
172 // zero ID has a special meaning, so unavailable
173 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
174 }
175
Glenn Kastenae0cff12016-02-24 13:57:49 -0800176 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800177 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800178 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
179 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700180 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800181 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700182
Wei Jia3f273d12015-11-24 09:06:49 -0800183 // reset battery stats.
184 // if the audio service has crashed, battery stats could be left
185 // in bad state, reset the state upon service start.
186 BatteryNotifier::getInstance().noteResetAudio();
187
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700188 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700189 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
190
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800191 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192}
193
194void AudioFlinger::onFirstRef()
195{
Eric Laurent93575202011-01-18 18:39:02 -0800196 Mutex::Autolock _l(mLock);
197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800199 char val_str[PROPERTY_VALUE_MAX] = { 0 };
200 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
201 uint32_t int_val;
202 if (1 == sscanf(val_str, "%u", &int_val)) {
203 mStandbyTimeInNsecs = milliseconds(int_val);
204 ALOGI("Using %u mSec as standby time.", int_val);
205 } else {
206 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
207 ALOGI("Using default %u mSec as standby time.",
208 (uint32_t)(mStandbyTimeInNsecs / 1000000));
209 }
210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211
Eric Laurenta4c5a552012-03-29 10:12:40 -0700212 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800213
214 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215}
216
217AudioFlinger::~AudioFlinger()
218{
219 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700220 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700221 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700222 }
223 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700224 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700225 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226 }
Andy Hungb4946b62019-03-14 11:19:28 -0700227 while (!mMmapThreads.isEmpty()) {
228 const audio_io_handle_t io = mMmapThreads.keyAt(0);
229 if (mMmapThreads.valueAt(0)->isOutput()) {
230 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
231 } else {
232 closeInput_nonvirtual(io); // removes entry from mMmapThreads
233 }
234 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700235
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800236 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
237 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700238 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700240
241 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700242 if (sMediaLogService != 0) {
243 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
244 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
245 mUnregisteredWriters.pop();
246 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700247 }
248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Eric Laurentfc235202016-12-20 18:48:17 -0800251//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800252__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800253status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
254 const audio_attributes_t *attr,
255 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700256 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800257 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800258 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800259 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700260 sp<MmapStreamInterface>& interface,
261 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800262{
263 sp<AudioFlinger> af;
264 {
265 Mutex::Autolock _l(gLock);
266 af = gAudioFlinger.promote();
267 }
268 status_t ret = NO_INIT;
269 if (af != 0) {
270 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800271 direction, attr, config, client, deviceId,
272 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800273 }
274 return ret;
275}
276
Eric Laurent6acd1d42017-01-04 14:23:29 -0800277status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
278 const audio_attributes_t *attr,
279 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700280 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800281 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800282 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800283 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700284 sp<MmapStreamInterface>& interface,
285 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800286{
287 status_t ret = initCheck();
288 if (ret != NO_ERROR) {
289 return ret;
290 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800291 audio_session_t actualSessionId = *sessionId;
292 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
293 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
294 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800295 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700296 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800297 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
298 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
299 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
300 fullConfig.sample_rate = config->sample_rate;
301 fullConfig.channel_mask = config->channel_mask;
302 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800303 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800304 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800305 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200306 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800307 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800308 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
309 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800310 deviceId, &portId, &secondaryOutputs);
311 ALOGW_IF(!secondaryOutputs.empty(),
312 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800313 } else {
314 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800315 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800316 client.clientPid,
317 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800318 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800319 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700320 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800321 }
322 if (ret != NO_ERROR) {
323 return ret;
324 }
325
326 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
327 // audio policy manager and we can retrieve it
328 sp<MmapThread> thread = mMmapThreads.valueFor(io);
329 if (thread != 0) {
330 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800331 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700332 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800333 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800334 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700335 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700336 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700337 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800338 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700339 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800340 ret = NO_INIT;
341 }
342
343 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
344
Eric Laurentfc235202016-12-20 18:48:17 -0800345 return ret;
346}
347
jiabin57303cc2018-12-18 15:45:57 -0800348/* static */
349int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
350 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
351 if (evs != 0) {
352 int32_t ret;
353 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
354 if (status.isOk()) {
355 return ret;
356 }
357 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800358 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800359}
360
361/* static */
362void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
363 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
364 if (evs != 0) {
365 evs->onExternalVibrationStop(*externalVibration);
366 }
367}
368
Eric Laurenta4c5a552012-03-29 10:12:40 -0700369static const char * const audio_interfaces[] = {
370 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
371 AUDIO_HARDWARE_MODULE_ID_A2DP,
372 AUDIO_HARDWARE_MODULE_ID_USB,
373};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700374
Phil Burk062e67a2015-02-11 13:40:50 -0800375AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700376 audio_module_handle_t module,
377 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700378{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700379 // if module is 0, the request comes from an old policy manager and we should load
380 // well known modules
381 if (module == 0) {
382 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700383 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700384 loadHwModule_l(audio_interfaces[i]);
385 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700386 // then try to find a module supporting the requested device.
387 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
388 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700389 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
390 uint32_t supportedDevices;
391 if (dev->getSupportedDevices(&supportedDevices) == OK &&
392 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700393 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700394 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700395 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700396 } else {
397 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700398 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
399 if (audioHwDevice != NULL) {
400 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700401 }
402 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700403
Dima Zavin799a70e2011-04-18 16:57:27 -0700404 return NULL;
405}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406
Glenn Kasten0f11b512014-01-31 16:18:54 -0800407void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408{
409 const size_t SIZE = 256;
410 char buffer[SIZE];
411 String8 result;
412
413 result.append("Clients:\n");
414 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800415 sp<Client> client = mClients.valueAt(i).promote();
416 if (client != 0) {
417 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
418 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 }
420 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700421
Eric Laurentd1b28d42013-09-18 18:47:13 -0700422 result.append("Notification Clients:\n");
423 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
424 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
425 result.append(buffer);
426 }
427
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700428 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800429 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700430 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
431 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800432 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700433 result.append(buffer);
434 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436}
437
438
Glenn Kasten0f11b512014-01-31 16:18:54 -0800439void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440{
441 const size_t SIZE = 256;
442 char buffer[SIZE];
443 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800444 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445
John Grossman4ff14ba2012-02-08 16:37:41 -0800446 snprintf(buffer, SIZE, "Hardware status: %d\n"
447 "Standby Time mSec: %u\n",
448 hardwareStatus,
449 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 result.append(buffer);
451 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452}
453
Glenn Kasten0f11b512014-01-31 16:18:54 -0800454void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455{
456 const size_t SIZE = 256;
457 char buffer[SIZE];
458 String8 result;
459 snprintf(buffer, SIZE, "Permission Denial: "
460 "can't dump AudioFlinger from pid=%d, uid=%d\n",
461 IPCThreadState::self()->getCallingPid(),
462 IPCThreadState::self()->getCallingUid());
463 result.append(buffer);
464 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465}
466
Eric Laurent81784c32012-11-19 14:55:58 -0800467bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700469 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
470 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471}
472
473status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
474{
Glenn Kasten44deb052012-02-05 18:09:08 -0800475 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476 dumpPermissionDenial(fd, args);
477 } else {
478 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800479 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480 if (!hardwareLocked) {
481 String8 result(kHardwareLockedString);
482 write(fd, result.string(), result.size());
483 } else {
484 mHardwareLock.unlock();
485 }
486
Eric Tan7b651152018-07-13 10:17:19 -0700487 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488
489 // failed to lock - AudioFlinger is probably deadlocked
490 if (!locked) {
491 String8 result(kDeadlockedString);
492 write(fd, result.string(), result.size());
493 }
494
Eric Laurent021cf962014-05-13 10:18:14 -0700495 bool clientLocked = dumpTryLock(mClientLock);
496 if (!clientLocked) {
497 String8 result(kClientLockedString);
498 write(fd, result.string(), result.size());
499 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700500
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700501 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700502 mEffectsFactoryHal->dumpEffects(fd);
503 } else {
504 String8 result(kNoEffectsFactory);
505 write(fd, result.string(), result.size());
506 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700507
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700509 if (clientLocked) {
510 mClientLock.unlock();
511 }
512
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513 dumpInternals(fd, args);
514
515 // dump playback threads
516 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
517 mPlaybackThreads.valueAt(i)->dump(fd, args);
518 }
519
520 // dump record threads
521 for (size_t i = 0; i < mRecordThreads.size(); i++) {
522 mRecordThreads.valueAt(i)->dump(fd, args);
523 }
524
Eric Laurent6acd1d42017-01-04 14:23:29 -0800525 // dump mmap threads
526 for (size_t i = 0; i < mMmapThreads.size(); i++) {
527 mMmapThreads.valueAt(i)->dump(fd, args);
528 }
529
Eric Laurentaaa44472014-09-12 17:41:50 -0700530 // dump orphan effect chains
531 if (mOrphanEffectChains.size() != 0) {
532 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
533 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
534 mOrphanEffectChains.valueAt(i)->dump(fd, args);
535 }
536 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700537 // dump all hardware devs
538 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700539 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
540 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700542
Mikhail Naganov201369b2018-05-16 16:52:32 -0700543 mPatchPanel.dump(fd);
544
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700545 // dump external setParameters
546 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
547 dprintf(fd, "\n%s setParameters:\n", name);
548 logger.dump(fd, " " /* prefix */);
549 };
550 dumpLogger(mRejectedSetParameterLog, "Rejected");
551 dumpLogger(mAppSetParameterLog, "App");
552 dumpLogger(mSystemSetParameterLog, "System");
553
Andy Hunga8115dc2018-08-24 15:51:59 -0700554 // dump historical threads in the last 10 seconds
555 const std::string threadLog = mThreadLog.dumpToString(
556 "Historical Thread Log ", 0 /* lines */,
557 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
558 write(fd, threadLog.c_str(), threadLog.size());
559
rago3bd1c872016-09-26 12:58:14 -0700560 BUFLOG_RESET;
561
Glenn Kastend65d73c2012-06-22 17:21:07 -0700562 if (locked) {
563 mLock.unlock();
564 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800565
Andy Hung8946a282018-04-19 20:04:56 -0700566#ifdef TEE_SINK
567 // NBAIO_Tee dump is safe to call outside of AF lock.
568 NBAIO_Tee::dumpAll(fd, "_DUMP");
569#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800570 // append a copy of media.log here by forwarding fd to it, but don't attempt
571 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700572 if (sMediaLogServiceAsBinder != 0) {
573 dprintf(fd, "\nmedia.log:\n");
574 Vector<String16> args;
575 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800576 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700577
578 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700579 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700580 bool unreachableMemory = false;
581 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700582 if (arg == String16("-m")) {
583 dumpMem = true;
584 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700585 unreachableMemory = true;
586 }
587 }
588
Andy Hung07b745e2016-05-23 16:21:07 -0700589 if (dumpMem) {
590 dprintf(fd, "\nDumping memory:\n");
591 std::string s = dumpMemoryAddresses(100 /* limit */);
592 write(fd, s.c_str(), s.size());
593 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700594 if (unreachableMemory) {
595 dprintf(fd, "\nDumping unreachable memory:\n");
596 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700597 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700598 write(fd, s.c_str(), s.size());
599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 }
601 return NO_ERROR;
602}
603
Eric Laurent021cf962014-05-13 10:18:14 -0700604sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800605{
Eric Laurent021cf962014-05-13 10:18:14 -0700606 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800607 // If pid is already in the mClients wp<> map, then use that entry
608 // (for which promote() is always != 0), otherwise create a new entry and Client.
609 sp<Client> client = mClients.valueFor(pid).promote();
610 if (client == 0) {
611 client = new Client(this, pid);
612 mClients.add(pid, client);
613 }
614
615 return client;
616}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617
Glenn Kasten9e58b552013-01-18 15:09:48 -0800618sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
619{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700620 // If there is no memory allocated for logs, return a dummy writer that does nothing.
621 // Similarly if we can't contact the media.log service, also return a dummy writer.
622 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800623 return new NBLog::Writer();
624 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700625 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
626 // If allocation fails, consult the vector of previously unregistered writers
627 // and garbage-collect one or more them until an allocation succeeds
628 if (shared == 0) {
629 Mutex::Autolock _l(mUnregisteredWritersLock);
630 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
631 {
632 // Pick the oldest stale writer to garbage-collect
633 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
634 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700635 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700636 // Now the media.log remote reference to IMemory is gone. When our last local
637 // reference to IMemory also drops to zero at end of this block,
638 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
639 }
640 // Re-attempt the allocation
641 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
642 if (shared != 0) {
643 goto success;
644 }
645 }
646 // Even after garbage-collecting all old writers, there is still not enough memory,
647 // so return a dummy writer
648 return new NBLog::Writer();
649 }
650success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800651 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
652 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
653 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700654 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800655 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800656}
657
658void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
659{
Glenn Kasten685ef092013-02-04 08:15:34 -0800660 if (writer == 0) {
661 return;
662 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800663 sp<IMemory> iMemory(writer->getIMemory());
664 if (iMemory == 0) {
665 return;
666 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700667 // Rather than removing the writer immediately, append it to a queue of old writers to
668 // be garbage-collected later. This allows us to continue to view old logs for a while.
669 Mutex::Autolock _l(mUnregisteredWritersLock);
670 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800671}
672
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673// IAudioFlinger interface
674
Eric Laurent21da6472017-11-09 16:29:26 -0800675sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
676 CreateTrackOutput& output,
677 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678{
679 sp<PlaybackThread::Track> track;
680 sp<TrackHandle> trackHandle;
681 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800683 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800684 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800685 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686
Eric Laurent21da6472017-11-09 16:29:26 -0800687 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700688 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800689 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700690 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
691 std::vector<int> effectIds;
692
693
Andy Hung4ef19fa2018-05-15 19:35:29 -0700694 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800695 ALOGW_IF(clientUid != callingUid,
696 "%s uid %d tried to pass itself off as %d",
697 __FUNCTION__, callingUid, clientUid);
698 clientUid = callingUid;
699 updatePid = true;
700 }
701 pid_t clientPid = input.clientInfo.clientPid;
702 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700703 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800704 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700705 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800706 __func__, callingUid, callingPid, clientPid);
707 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700708 }
709
Eric Laurent21da6472017-11-09 16:29:26 -0800710 audio_session_t sessionId = input.sessionId;
711 if (sessionId == AUDIO_SESSION_ALLOCATE) {
712 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800713 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
714 lStatus = BAD_VALUE;
715 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800716 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800717
Eric Laurent21da6472017-11-09 16:29:26 -0800718 output.sessionId = sessionId;
719 output.outputId = AUDIO_IO_HANDLE_NONE;
720 output.selectedDeviceId = input.selectedDeviceId;
721
722 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200723 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800724 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800725
726 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
727 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
728 goto Exit;
729 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800730 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
731 // but if someone uses binder directly they could bypass that and cause us to crash
732 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000733 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734 lStatus = BAD_VALUE;
735 goto Exit;
736 }
737
Glenn Kasten53b5d092014-02-05 10:00:23 -0800738 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800739 if (!audio_is_output_channel(input.config.channel_mask)) {
740 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800741 lStatus = BAD_VALUE;
742 goto Exit;
743 }
744
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700745 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800746 if (!audio_is_valid_format(input.config.format)) {
747 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700748 lStatus = BAD_VALUE;
749 goto Exit;
750 }
751
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 {
753 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800754 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800756 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757 lStatus = BAD_VALUE;
758 goto Exit;
759 }
760
Eric Laurent21da6472017-11-09 16:29:26 -0800761 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762
Glenn Kastene848bd92014-03-13 15:00:32 -0700763 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800764 // check if an effect chain with the same session ID is present on another
765 // output thread and move it here.
766 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
767 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
768 if (mPlaybackThreads.keyAt(i) != output.outputId) {
769 uint32_t sessions = t->hasAudioSession(sessionId);
770 if (sessions & ThreadBase::EFFECT_SESSION) {
771 effectThread = t.get();
772 break;
Eric Laurentde070132010-07-13 04:45:46 -0700773 }
774 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700775 }
Eric Laurent21da6472017-11-09 16:29:26 -0800776 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777
Eric Laurent21da6472017-11-09 16:29:26 -0800778 output.sampleRate = input.config.sample_rate;
779 output.frameCount = input.frameCount;
780 output.notificationFrameCount = input.notificationFrameCount;
781 output.flags = input.flags;
782
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700783 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
784 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800785 &output.frameCount, &output.notificationFrameCount,
786 input.notificationsPerBuffer, input.speed,
787 input.sharedBuffer, sessionId, &output.flags,
788 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800789 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700790 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700791
Eric Laurent21da6472017-11-09 16:29:26 -0800792 output.afFrameCount = thread->frameCount();
793 output.afSampleRate = thread->sampleRate();
794 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800795 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800796
Kevin Rocard153f92d2018-12-18 18:33:28 -0800797 if (lStatus == NO_ERROR) {
798 // Connect secondary outputs. Failure on a secondary output must not imped the primary
799 // Any secondary output setup failure will lead to a desync between the AP and AF until
800 // the track is destroyed.
801 TeePatches teePatches;
802 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
803 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
804 if (secondaryThread == NULL) {
805 ALOGE("no playback thread found for secondary output %d", output.outputId);
806 continue;
807 }
808
809 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
810
811 using namespace std::chrono_literals;
812 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
813 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
814 output.sampleRate,
815 inChannelMask,
816 input.config.format,
817 frameCount,
818 NULL /* buffer */,
819 (size_t)0 /* bufferSize */,
820 AUDIO_INPUT_FLAG_DIRECT,
821 0ns /* timeout */);
822 status_t status = patchRecord->initCheck();
823 if (status != NO_ERROR) {
824 ALOGE("Secondary output patchRecord init failed: %d", status);
825 continue;
826 }
827 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
828 streamType,
829 output.sampleRate,
830 input.config.channel_mask,
831 input.config.format,
832 frameCount,
833 patchRecord->buffer(),
834 patchRecord->bufferSize(),
835 output.flags,
836 0ns /* timeout */);
837 status = patchTrack->initCheck();
838 if (status != NO_ERROR) {
839 ALOGE("Secondary output patchTrack init failed: %d", status);
840 continue;
841 }
842 teePatches.push_back({patchRecord, patchTrack});
843 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800844 // In case the downstream patchTrack on the secondaryThread temporarily outlives
845 // our created track, ensure the corresponding patchRecord is still alive.
846 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
847 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800848 }
849 track->setTeePatches(std::move(teePatches));
850 }
851
Eric Laurent39e94f82010-07-28 01:32:47 -0700852 // move effect chain to this output thread if an effect on same session was waiting
853 // for a track to be created
854 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700855 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700856 Mutex::Autolock _dl(thread->mLock);
857 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700858 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
859 effectThreadId = thread->id();
860 effectIds = thread->getEffectIds_l(sessionId);
861 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700862 }
Eric Laurenta011e352012-03-29 15:51:43 -0700863
864 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700865 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800866 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700867 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700868 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700869 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700870 } else {
871 mPendingSyncEvents[i]->cancel();
872 }
Eric Laurenta011e352012-03-29 15:51:43 -0700873 mPendingSyncEvents.removeAt(i);
874 i--;
875 }
876 }
877 }
Glenn Kastene198c362013-08-13 09:13:36 -0700878
Eric Laurent21da6472017-11-09 16:29:26 -0800879 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 }
Glenn Kastene198c362013-08-13 09:13:36 -0700881
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700882 if (lStatus != NO_ERROR) {
883 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700884 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700885 // Don't hold mClientLock when releasing the reference on the track as the
886 // destructor will acquire it.
887 {
888 Mutex::Autolock _cl(mClientLock);
889 client.clear();
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700892 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
894
Eric Laurent6c796322019-04-09 14:13:17 -0700895 // effectThreadId is not NONE if an effect chain corresponding to the track session
896 // was found on another thread and must be moved on this thread
897 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
898 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
899 }
900
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700901 // return handle to client
902 trackHandle = new TrackHandle(track);
903
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800905 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700906 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800907 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700908 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909 return trackHandle;
910}
911
Glenn Kasten2c073da2016-02-26 09:14:08 -0800912uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913{
914 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800915 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800917 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 return 0;
919 }
920 return thread->sampleRate();
921}
922
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800923audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924{
925 Mutex::Autolock _l(mLock);
926 PlaybackThread *thread = checkPlaybackThread_l(output);
927 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000928 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800929 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 }
931 return thread->format();
932}
933
Glenn Kasten2c073da2016-02-26 09:14:08 -0800934size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935{
936 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800937 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800939 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 return 0;
941 }
Glenn Kasten58912562012-04-03 10:45:00 -0700942 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
943 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 return thread->frameCount();
945}
946
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700947size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
948{
949 Mutex::Autolock _l(mLock);
950 ThreadBase *thread = checkThread_l(ioHandle);
951 if (thread == NULL) {
952 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
953 return 0;
954 }
955 return thread->frameCountHAL();
956}
957
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800958uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959{
960 Mutex::Autolock _l(mLock);
961 PlaybackThread *thread = checkPlaybackThread_l(output);
962 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800963 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 return 0;
965 }
966 return thread->latency();
967}
968
969status_t AudioFlinger::setMasterVolume(float value)
970{
Eric Laurenta1884f92011-08-23 08:25:03 -0700971 status_t ret = initCheck();
972 if (ret != NO_ERROR) {
973 return ret;
974 }
975
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 // check calling permissions
977 if (!settingsAllowed()) {
978 return PERMISSION_DENIED;
979 }
980
Eric Laurenta4c5a552012-03-29 10:12:40 -0700981 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700982 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700983
John Grossmanee578c02012-07-23 17:05:46 -0700984 // Set master volume in the HALs which support it.
985 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
986 AutoMutex lock(mHardwareLock);
987 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800988
John Grossmanee578c02012-07-23 17:05:46 -0700989 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
990 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700991 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800992 }
John Grossmanee578c02012-07-23 17:05:46 -0700993 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995
John Grossmanee578c02012-07-23 17:05:46 -0700996 // Now set the master volume in each playback thread. Playback threads
997 // assigned to HALs which do not have master volume support will apply
998 // master volume during the mix operation. Threads with HALs which do
999 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001000 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1001 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1002 continue;
1003 }
John Grossmanee578c02012-07-23 17:05:46 -07001004 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006
1007 return NO_ERROR;
1008}
1009
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001010status_t AudioFlinger::setMasterBalance(float balance)
1011{
1012 status_t ret = initCheck();
1013 if (ret != NO_ERROR) {
1014 return ret;
1015 }
1016
1017 // check calling permissions
1018 if (!settingsAllowed()) {
1019 return PERMISSION_DENIED;
1020 }
1021
1022 // check range
1023 if (isnan(balance) || fabs(balance) > 1.f) {
1024 return BAD_VALUE;
1025 }
1026
1027 Mutex::Autolock _l(mLock);
1028
1029 // short cut.
1030 if (mMasterBalance == balance) return NO_ERROR;
1031
1032 mMasterBalance = balance;
1033
1034 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1035 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1036 continue;
1037 }
1038 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1039 }
1040
1041 return NO_ERROR;
1042}
1043
Glenn Kastenf78aee72012-01-04 11:00:47 -08001044status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045{
Eric Laurenta1884f92011-08-23 08:25:03 -07001046 status_t ret = initCheck();
1047 if (ret != NO_ERROR) {
1048 return ret;
1049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050
1051 // check calling permissions
1052 if (!settingsAllowed()) {
1053 return PERMISSION_DENIED;
1054 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001055 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001056 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 return BAD_VALUE;
1058 }
1059
1060 { // scope for the lock
1061 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001062 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001064 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 mHardwareStatus = AUDIO_HW_IDLE;
1066 }
1067
1068 if (NO_ERROR == ret) {
1069 Mutex::Autolock _l(mLock);
1070 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001071 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001072 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 }
1074
1075 return ret;
1076}
1077
1078status_t AudioFlinger::setMicMute(bool state)
1079{
Eric Laurenta1884f92011-08-23 08:25:03 -07001080 status_t ret = initCheck();
1081 if (ret != NO_ERROR) {
1082 return ret;
1083 }
1084
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 // check calling permissions
1086 if (!settingsAllowed()) {
1087 return PERMISSION_DENIED;
1088 }
1089
1090 AutoMutex lock(mHardwareLock);
1091 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001092 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001093 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1094 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001095 if (result != NO_ERROR) {
1096 ret = result;
1097 }
1098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 mHardwareStatus = AUDIO_HW_IDLE;
1100 return ret;
1101}
1102
1103bool AudioFlinger::getMicMute() const
1104{
Eric Laurenta1884f92011-08-23 08:25:03 -07001105 status_t ret = initCheck();
1106 if (ret != NO_ERROR) {
1107 return false;
1108 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001109 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001110 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001111 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001113 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001114 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1115 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001116 if (result == NO_ERROR) {
1117 mute = mute && state;
1118 }
1119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001121
1122 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123}
1124
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001125void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1126{
1127 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1128
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001129 AutoMutex lock(mLock);
1130 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001131 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1132 }
1133 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1134 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001135 }
1136}
1137
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138status_t AudioFlinger::setMasterMute(bool muted)
1139{
John Grossmand8f178d2012-07-20 14:51:35 -07001140 status_t ret = initCheck();
1141 if (ret != NO_ERROR) {
1142 return ret;
1143 }
1144
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 // check calling permissions
1146 if (!settingsAllowed()) {
1147 return PERMISSION_DENIED;
1148 }
1149
John Grossmanee578c02012-07-23 17:05:46 -07001150 Mutex::Autolock _l(mLock);
1151 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001152
John Grossmanee578c02012-07-23 17:05:46 -07001153 // Set master mute in the HALs which support it.
1154 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1155 AutoMutex lock(mHardwareLock);
1156 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001157
John Grossmanee578c02012-07-23 17:05:46 -07001158 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1159 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001160 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001161 }
John Grossmanee578c02012-07-23 17:05:46 -07001162 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001163 }
1164
John Grossmanee578c02012-07-23 17:05:46 -07001165 // Now set the master mute in each playback thread. Playback threads
1166 // assigned to HALs which do not have master mute support will apply master
1167 // mute during the mix operation. Threads with HALs which do support master
1168 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001169 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1170 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1171 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173
1174 return NO_ERROR;
1175}
1176
1177float AudioFlinger::masterVolume() const
1178{
Glenn Kasten98067102011-12-13 11:47:54 -08001179 Mutex::Autolock _l(mLock);
1180 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181}
1182
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001183status_t AudioFlinger::getMasterBalance(float *balance) const
1184{
1185 Mutex::Autolock _l(mLock);
1186 *balance = getMasterBalance_l();
1187 return NO_ERROR; // if called through binder, may return a transactional error
1188}
1189
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190bool AudioFlinger::masterMute() const
1191{
Glenn Kasten98067102011-12-13 11:47:54 -08001192 Mutex::Autolock _l(mLock);
1193 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194}
1195
John Grossman4ff14ba2012-02-08 16:37:41 -08001196float AudioFlinger::masterVolume_l() const
1197{
John Grossman4ff14ba2012-02-08 16:37:41 -08001198 return mMasterVolume;
1199}
1200
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001201float AudioFlinger::getMasterBalance_l() const
1202{
1203 return mMasterBalance;
1204}
1205
John Grossmand8f178d2012-07-20 14:51:35 -07001206bool AudioFlinger::masterMute_l() const
1207{
John Grossmanee578c02012-07-23 17:05:46 -07001208 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001209}
1210
Eric Laurent223fd5c2014-11-11 13:43:36 -08001211status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1212{
1213 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001214 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001215 return BAD_VALUE;
1216 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001217 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1218 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1219 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001220 return PERMISSION_DENIED;
1221 }
1222
1223 return NO_ERROR;
1224}
1225
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001226status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1227 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228{
1229 // check calling permissions
1230 if (!settingsAllowed()) {
1231 return PERMISSION_DENIED;
1232 }
1233
Eric Laurent223fd5c2014-11-11 13:43:36 -08001234 status_t status = checkStreamType(stream);
1235 if (status != NO_ERROR) {
1236 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 }
Eric Laurent98e38192018-02-15 18:31:53 -08001238 if (output == AUDIO_IO_HANDLE_NONE) {
1239 return BAD_VALUE;
1240 }
Eric Laurent6c796322019-04-09 14:13:17 -07001241 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH || value == 1.0,
1242 "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243
1244 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001245 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1246 if (volumeInterface == NULL) {
1247 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 }
Eric Laurent98e38192018-02-15 18:31:53 -08001249 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250
1251 return NO_ERROR;
1252}
1253
Glenn Kastenfff6d712012-01-12 16:38:12 -08001254status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255{
1256 // check calling permissions
1257 if (!settingsAllowed()) {
1258 return PERMISSION_DENIED;
1259 }
1260
Eric Laurent223fd5c2014-11-11 13:43:36 -08001261 status_t status = checkStreamType(stream);
1262 if (status != NO_ERROR) {
1263 return status;
1264 }
1265 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1266
1267 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001268 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 return BAD_VALUE;
1270 }
1271
Eric Laurent93575202011-01-18 18:39:02 -08001272 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001274 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1275 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1276 volumeInterfaces[i]->setStreamMute(stream, muted);
1277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001278
1279 return NO_ERROR;
1280}
1281
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001282float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001284 status_t status = checkStreamType(stream);
1285 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 return 0.0f;
1287 }
Eric Laurent98e38192018-02-15 18:31:53 -08001288 if (output == AUDIO_IO_HANDLE_NONE) {
1289 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290 }
1291
Eric Laurent98e38192018-02-15 18:31:53 -08001292 AutoMutex lock(mLock);
1293 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1294 if (volumeInterface == NULL) {
1295 return 0.0f;
1296 }
1297
1298 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299}
1300
Glenn Kastenfff6d712012-01-12 16:38:12 -08001301bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001303 status_t status = checkStreamType(stream);
1304 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 return true;
1306 }
1307
Glenn Kasten6637baa2012-01-09 09:40:36 -08001308 AutoMutex lock(mLock);
1309 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310}
1311
Eric Laurent054d9d32015-04-24 08:48:48 -07001312
1313void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1314{
1315 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1316 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1317 }
1318}
1319
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001320// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1321void AudioFlinger::forwardParametersToDownstreamPatches_l(
1322 audio_io_handle_t upStream, const String8& keyValuePairs,
1323 std::function<bool(const sp<PlaybackThread>&)> useThread)
1324{
1325 std::vector<PatchPanel::SoftwarePatch> swPatches;
1326 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1327 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1328 __func__, swPatches.size(), upStream);
1329 for (const auto& swPatch : swPatches) {
1330 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1331 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1332 downStream->setParameters(keyValuePairs);
1333 }
1334 }
1335}
1336
Eric Laurentf1047e82018-04-16 19:18:20 -07001337// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1338// Some keys are used for audio routing and audio path configuration and should be reserved for use
1339// by audio policy and audio flinger for functional, privacy and security reasons.
1340void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1341{
1342 static const String8 kReservedParameters[] = {
1343 String8(AudioParameter::keyRouting),
1344 String8(AudioParameter::keySamplingRate),
1345 String8(AudioParameter::keyFormat),
1346 String8(AudioParameter::keyChannels),
1347 String8(AudioParameter::keyFrameCount),
1348 String8(AudioParameter::keyInputSource),
1349 String8(AudioParameter::keyMonoOutput),
1350 String8(AudioParameter::keyStreamConnect),
1351 String8(AudioParameter::keyStreamDisconnect),
1352 String8(AudioParameter::keyStreamSupportedFormats),
1353 String8(AudioParameter::keyStreamSupportedChannels),
1354 String8(AudioParameter::keyStreamSupportedSamplingRates),
1355 };
1356
Andy Hung4ef19fa2018-05-15 19:35:29 -07001357 if (isAudioServerUid(callingUid)) {
1358 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001359 }
1360
1361 AudioParameter param = AudioParameter(keyValuePairs);
1362 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001363 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001364 for (auto& key : kReservedParameters) {
1365 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001366 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001367 param.remove(key);
1368 }
1369 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001370 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1371 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001372 keyValuePairs = param.toString();
1373}
1374
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001375void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1376 size_t rejectedKVPSize, const String8& rejectedKVPs,
1377 uid_t callingUid) {
1378 auto prefix = String8::format("UID %5d", callingUid);
1379 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1380 if (rejectedKVPSize != 0) {
1381 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1382 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1383 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1384 } else {
1385 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1386 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1387 }
1388}
1389
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001390status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391{
Eric Laurentf1047e82018-04-16 19:18:20 -07001392 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1393 ioHandle, keyValuePairs.string(),
1394 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001395
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 // check calling permissions
1397 if (!settingsAllowed()) {
1398 return PERMISSION_DENIED;
1399 }
1400
Eric Laurentf1047e82018-04-16 19:18:20 -07001401 String8 filteredKeyValuePairs = keyValuePairs;
1402 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1403
1404 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1405
Glenn Kasten142f5192014-03-25 17:44:59 -07001406 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1407 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001408 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001409 // result will remain NO_INIT if no audio device is present
1410 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001411 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001412 AutoMutex lock(mHardwareLock);
1413 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1414 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001415 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001416 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001417 // return success if at least one audio device accepts the parameters as not all
1418 // HALs are requested to support all parameters. If no audio device supports the
1419 // requested parameters, the last error is reported.
1420 if (final_result != NO_ERROR) {
1421 final_result = result;
1422 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001423 }
1424 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001425 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001426 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001427 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001428 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001429 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1430 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001431 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001432 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001433 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001434 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001435 }
1436 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001437 String8 screenState;
1438 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001439 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001440 if (isOff != (AudioFlinger::mScreenState & 1)) {
1441 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001442 }
1443 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001444 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445 }
1446
1447 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1448 // and the thread is exited once the lock is released
1449 sp<ThreadBase> thread;
1450 {
1451 Mutex::Autolock _l(mLock);
1452 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001453 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001455 if (thread == 0) {
1456 thread = checkMmapThread_l(ioHandle);
1457 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001458 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001459 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001460 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001461 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001462 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1463 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001464 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 }
1467 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001468 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001469 status_t result = thread->setParameters(filteredKeyValuePairs);
1470 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1471 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 }
1473 return BAD_VALUE;
1474}
1475
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001476String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001478 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1479 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480
Eric Laurenta4c5a552012-03-29 10:12:40 -07001481 Mutex::Autolock _l(mLock);
1482
Glenn Kasten142f5192014-03-25 17:44:59 -07001483 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001484 String8 out_s8;
1485
Dima Zavin799a70e2011-04-18 16:57:27 -07001486 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001487 String8 s;
1488 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001489 {
1490 AutoMutex lock(mHardwareLock);
1491 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001492 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1493 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001494 mHardwareStatus = AUDIO_HW_IDLE;
1495 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001496 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001497 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001498 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 }
1500
Eric Laurent6acd1d42017-01-04 14:23:29 -08001501 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1502 if (thread == NULL) {
1503 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1504 if (thread == NULL) {
1505 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1506 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001507 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001508 }
1509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001511 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512}
1513
Glenn Kastendd8104c2012-07-02 12:42:44 -07001514size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1515 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516{
Eric Laurenta1884f92011-08-23 08:25:03 -07001517 status_t ret = initCheck();
1518 if (ret != NO_ERROR) {
1519 return 0;
1520 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001521 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001522 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001523 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001524 return 0;
1525 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001526
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001527 AutoMutex lock(mHardwareLock);
1528 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001529 audio_config_t config, proposed;
1530 memset(&proposed, 0, sizeof(proposed));
1531 proposed.sample_rate = sampleRate;
1532 proposed.channel_mask = channelMask;
1533 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001534
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001535 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001536 size_t frames;
1537 for (;;) {
1538 // Note: config is currently a const parameter for get_input_buffer_size()
1539 // but we use a copy from proposed in case config changes from the call.
1540 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001541 status_t result = dev->getInputBufferSize(&config, &frames);
1542 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001543 break; // hal success, config is the result
1544 }
1545 // change one parameter of the configuration each iteration to a more "common" value
1546 // to see if the device will support it.
1547 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1548 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1549 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1550 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1551 } else {
1552 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1553 "format %#x, channelMask 0x%X",
1554 sampleRate, format, channelMask);
1555 break; // retries failed, break out of loop with frames == 0.
1556 }
1557 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001558 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001559 if (frames > 0 && config.sample_rate != sampleRate) {
1560 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1561 }
1562 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563}
1564
Glenn Kasten5f972c02014-01-13 09:59:31 -08001565uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 Mutex::Autolock _l(mLock);
1568
1569 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1570 if (recordThread != NULL) {
1571 return recordThread->getInputFramesLost();
1572 }
1573 return 0;
1574}
1575
1576status_t AudioFlinger::setVoiceVolume(float value)
1577{
Eric Laurenta1884f92011-08-23 08:25:03 -07001578 status_t ret = initCheck();
1579 if (ret != NO_ERROR) {
1580 return ret;
1581 }
1582
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 // check calling permissions
1584 if (!settingsAllowed()) {
1585 return PERMISSION_DENIED;
1586 }
1587
1588 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001589 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001590 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001591 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 mHardwareStatus = AUDIO_HW_IDLE;
1593
1594 return ret;
1595}
1596
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001597status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001598 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 Mutex::Autolock _l(mLock);
1601
1602 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1603 if (playbackThread != NULL) {
1604 return playbackThread->getRenderPosition(halFrames, dspFrames);
1605 }
1606
1607 return BAD_VALUE;
1608}
1609
1610void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1611{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001613 if (client == 0) {
1614 return;
1615 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001616 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001617 {
1618 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001619 if (mNotificationClients.indexOfKey(pid) < 0) {
1620 sp<NotificationClient> notificationClient = new NotificationClient(this,
1621 client,
1622 pid);
1623 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624
Eric Laurent021cf962014-05-13 10:18:14 -07001625 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626
Marco Nelissen06b46062014-11-14 07:58:25 -08001627 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001628 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001629 }
1630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631
Eric Laurent021cf962014-05-13 10:18:14 -07001632 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001633 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001634 // the config change is always sent from playback or record threads to avoid deadlock
1635 // with AudioSystem::gLock
1636 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001637 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001640 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001641 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642 }
1643}
1644
1645void AudioFlinger::removeNotificationClient(pid_t pid)
1646{
Eric Laurent6c796322019-04-09 14:13:17 -07001647 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001648 {
Eric Laurent6c796322019-04-09 14:13:17 -07001649 Mutex::Autolock _l(mLock);
1650 {
1651 Mutex::Autolock _cl(mClientLock);
1652 mNotificationClients.removeItem(pid);
1653 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001654
Eric Laurent6c796322019-04-09 14:13:17 -07001655 ALOGV("%d died, releasing its sessions", pid);
1656 size_t num = mAudioSessionRefs.size();
1657 bool removed = false;
1658 for (size_t i = 0; i < num; ) {
1659 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1660 ALOGV(" pid %d @ %zu", ref->mPid, i);
1661 if (ref->mPid == pid) {
1662 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1663 mAudioSessionRefs.removeAt(i);
1664 delete ref;
1665 removed = true;
1666 num--;
1667 } else {
1668 i++;
1669 }
1670 }
1671 if (removed) {
1672 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001673 }
1674 }
Eric Laurent6c796322019-04-09 14:13:17 -07001675 for (auto& effect : removedEffects) {
1676 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678}
1679
Eric Laurent73e26b62015-04-27 16:55:58 -07001680void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001681 const sp<AudioIoDescriptor>& ioDesc,
1682 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683{
Eric Laurent021cf962014-05-13 10:18:14 -07001684 Mutex::Autolock _l(mClientLock);
1685 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001687 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1688 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1689 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 }
1691}
1692
Eric Laurent021cf962014-05-13 10:18:14 -07001693// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694void AudioFlinger::removeClient_l(pid_t pid)
1695{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001696 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001697 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 mClients.removeItem(pid);
1699}
1700
Eric Laurent717e1282012-06-29 16:36:52 -07001701// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001702sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1703 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001704{
1705 sp<PlaybackThread> thread;
1706
1707 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1708 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1709 ALOG_ASSERT(thread == 0);
1710 thread = mPlaybackThreads.valueAt(i);
1711 }
1712 }
1713
1714 return thread;
1715}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718
1719// ----------------------------------------------------------------------------
1720
1721AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1722 : RefBase(),
1723 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001724 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725{
Andy Hung6f248bb2018-01-23 14:04:37 -08001726 mMemoryDealer = new MemoryDealer(
1727 audioFlinger->getClientSharedHeapSize(),
1728 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729}
1730
Eric Laurent021cf962014-05-13 10:18:14 -07001731// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732AudioFlinger::Client::~Client()
1733{
1734 mAudioFlinger->removeClient_l(mPid);
1735}
1736
Glenn Kasten435dbe62012-01-30 10:15:48 -08001737sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738{
1739 return mMemoryDealer;
1740}
1741
1742// ----------------------------------------------------------------------------
1743
1744AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1745 const sp<IAudioFlingerClient>& client,
1746 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001747 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748{
1749}
1750
1751AudioFlinger::NotificationClient::~NotificationClient()
1752{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753}
1754
Glenn Kasten0f11b512014-01-31 16:18:54 -08001755void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756{
1757 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001758 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759}
1760
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001761// ----------------------------------------------------------------------------
1762AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1763 : mPendingRequests(false) {}
1764
1765
1766void AudioFlinger::MediaLogNotifier::requestMerge() {
1767 AutoMutex _l(mMutex);
1768 mPendingRequests = true;
1769 mCond.signal();
1770}
1771
1772bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001773 // Should already have been checked, but just in case
1774 if (sMediaLogService == 0) {
1775 return false;
1776 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001777 // Wait until there are pending requests
1778 {
1779 AutoMutex _l(mMutex);
1780 mPendingRequests = false; // to ignore past requests
1781 while (!mPendingRequests) {
1782 mCond.wait(mMutex);
1783 // TODO may also need an exitPending check
1784 }
1785 mPendingRequests = false;
1786 }
1787 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001788 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001789 usleep(kPostTriggerSleepPeriod);
1790 return true;
1791}
1792
1793void AudioFlinger::requestLogMerge() {
1794 mMediaLogNotifier->requestMerge();
1795}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796
1797// ----------------------------------------------------------------------------
1798
Eric Laurentf14db3c2017-12-08 14:20:36 -08001799sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1800 CreateRecordOutput& output,
1801 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802{
1803 sp<RecordThread::RecordTrack> recordTrack;
1804 sp<RecordHandle> recordHandle;
1805 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001807 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001808 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809
Eric Laurentf14db3c2017-12-08 14:20:36 -08001810 output.cblk.clear();
1811 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001812 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001813
Eric Laurentf14db3c2017-12-08 14:20:36 -08001814 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001815 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001816 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001817 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001818 ALOGW_IF(clientUid != callingUid,
1819 "%s uid %d tried to pass itself off as %d",
1820 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001821 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001822 updatePid = true;
1823 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001824 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001825 if (updatePid) {
1826 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001827 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001828 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001829 __func__, callingUid, callingPid, clientPid);
1830 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001831 }
1832
Andy Hung6770c6f2015-04-07 13:43:36 -07001833 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001834 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1835 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001836 lStatus = BAD_VALUE;
1837 goto Exit;
1838 }
1839
Glenn Kasten53b5d092014-02-05 10:00:23 -08001840 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001841 if (!audio_is_input_channel(input.config.channel_mask)) {
1842 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001843 lStatus = BAD_VALUE;
1844 goto Exit;
1845 }
1846
Eric Laurentf14db3c2017-12-08 14:20:36 -08001847 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1848 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1849 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1850 lStatus = BAD_VALUE;
1851 goto Exit;
1852 }
1853
1854 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001855 output.selectedDeviceId = input.selectedDeviceId;
1856 output.flags = input.flags;
1857
1858 client = registerPid(clientPid);
1859
1860 // Not a conventional loop, but a retry loop for at most two iterations total.
1861 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1862 // Exits loop via break on no error of got exit on error
1863 // The sp<> references will be dropped when re-entering scope.
1864 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1865 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001866 // release previously opened input if retrying.
1867 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1868 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001869 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001870 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001871 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001872 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001873 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001874 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1875 sessionId,
1876 // FIXME compare to AudioTrack
1877 clientPid,
1878 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001879 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001880 &input.config,
1881 output.flags, &output.selectedDeviceId, &portId);
1882
Glenn Kasten05997e22014-03-13 15:08:33 -07001883 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001885 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001887 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888 lStatus = BAD_VALUE;
1889 goto Exit;
1890 }
1891
Eric Laurentf14db3c2017-12-08 14:20:36 -08001892 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893
Eric Laurentf14db3c2017-12-08 14:20:36 -08001894 output.sampleRate = input.config.sample_rate;
1895 output.frameCount = input.frameCount;
1896 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001897
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001898 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001899 input.config.format, input.config.channel_mask,
1900 &output.frameCount, sessionId,
1901 &output.notificationFrameCount,
1902 clientUid, &output.flags,
1903 input.clientInfo.clientTid,
1904 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001905 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001906
Eric Laurentf14db3c2017-12-08 14:20:36 -08001907 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1908 // audio policy manager without FAST constraint
1909 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001910 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001911 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001912
1913 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001914 goto Exit;
1915 }
1916
1917 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1918 // session and move it to this thread.
1919 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1920 if (chain != 0) {
1921 Mutex::Autolock _l(thread->mLock);
1922 thread->addEffectChain_l(chain);
1923 }
1924 break;
1925 }
1926 // End of retry loop.
1927 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 }
Glenn Kastene198c362013-08-13 09:13:36 -07001929
Eric Laurentf14db3c2017-12-08 14:20:36 -08001930 output.cblk = recordTrack->getCblk();
1931 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001932 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001933
1934 // return handle to client
1935 recordHandle = new RecordHandle(recordTrack);
1936
1937Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001938 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001939 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001940 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001941 // Don't hold mClientLock when releasing the reference on the track as the
1942 // destructor will acquire it.
1943 {
1944 Mutex::Autolock _cl(mClientLock);
1945 client.clear();
1946 }
Eric Laurent896c9672017-12-08 14:08:45 -08001947 recordTrack.clear();
1948 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001949 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001950 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 }
1952
Glenn Kasten9156ef32013-08-06 15:39:08 -07001953 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 return recordHandle;
1955}
1956
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001957
1958
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959// ----------------------------------------------------------------------------
1960
Eric Laurenta4c5a552012-03-29 10:12:40 -07001961audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1962{
Eric Laurent44622db2014-08-01 19:00:33 -07001963 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001964 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001965 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001966 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001967 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001968 }
1969 Mutex::Autolock _l(mLock);
1970 return loadHwModule_l(name);
1971}
1972
1973// loadHwModule_l() must be called with AudioFlinger::mLock held
1974audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1975{
1976 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1977 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1978 ALOGW("loadHwModule() module %s already loaded", name);
1979 return mAudioHwDevs.keyAt(i);
1980 }
1981 }
1982
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001983 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001984
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001985 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001986 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001987 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001988 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001989 }
1990
1991 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001992 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001993 mHardwareStatus = AUDIO_HW_IDLE;
1994 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001995 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001996 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001997 }
1998
John Grossmanee578c02012-07-23 17:05:46 -07001999 // Check and cache this HAL's level of support for master mute and master
2000 // volume. If this is the first HAL opened, and it supports the get
2001 // methods, use the initial values provided by the HAL as the current
2002 // master mute and volume settings.
2003
2004 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2005 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002006 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002007
2008 if (0 == mAudioHwDevs.size()) {
2009 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002010 float mv;
2011 if (OK == dev->getMasterVolume(&mv)) {
2012 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002013 }
2014
2015 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002016 bool mm;
2017 if (OK == dev->getMasterMute(&mm)) {
2018 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002019 }
2020 }
2021
Eric Laurenta4c5a552012-03-29 10:12:40 -07002022 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002023 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002024 flags = static_cast<AudioHwDevice::Flags>(flags |
2025 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2026 }
2027
2028 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002029 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002030 flags = static_cast<AudioHwDevice::Flags>(flags |
2031 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2032 }
2033
Eric Laurenta4c5a552012-03-29 10:12:40 -07002034 mHardwareStatus = AUDIO_HW_IDLE;
2035 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002036 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002037 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2038 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2039 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002040
Glenn Kastena13cde92016-03-28 15:26:02 -07002041 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002042 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002043
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002044 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002045
2046 return handle;
2047
2048}
2049
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002050// ----------------------------------------------------------------------------
2051
Glenn Kasten3b16c762012-11-14 08:44:39 -08002052uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002053{
2054 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002055 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002056 return thread != NULL ? thread->sampleRate() : 0;
2057}
2058
Glenn Kastene33054e2012-11-14 12:54:39 -08002059size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002060{
2061 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002062 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002063 return thread != NULL ? thread->frameCountHAL() : 0;
2064}
2065
2066// ----------------------------------------------------------------------------
2067
Andy Hung6f248bb2018-01-23 14:04:37 -08002068status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002069{
2070 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002071 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002072 return PERMISSION_DENIED;
2073 }
2074 Mutex::Autolock _l(mLock);
2075 if (mIsDeviceTypeKnown) {
2076 return INVALID_OPERATION;
2077 }
2078 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002079 mTotalMemory = totalMemory;
2080 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2081 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2082 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2083 // though actual setting is determined through device configuration.
2084 constexpr int64_t GB = 1024 * 1024 * 1024;
2085 mClientSharedHeapSize =
2086 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2087 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2088 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2089 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2090 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002091 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002092
2093 // TODO: Cache the client shared heap size in a persistent property.
2094 // It's possible that a native process or Java service or app accesses audioserver
2095 // after it is registered by system server, but before AudioService updates
2096 // the memory info. This would occur immediately after boot or an audioserver
2097 // crash and restore. Before update from AudioService, the client would get the
2098 // minimum heap size.
2099
2100 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2101 (isLowRamDevice ? "true" : "false"),
2102 (long long)mTotalMemory,
2103 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002104 return NO_ERROR;
2105}
2106
Andy Hung6f248bb2018-01-23 14:04:37 -08002107size_t AudioFlinger::getClientSharedHeapSize() const
2108{
2109 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2110 if (heapSizeInBytes != 0) { // read-only property overrides all.
2111 return heapSizeInBytes;
2112 }
2113 return mClientSharedHeapSize;
2114}
2115
Mikhail Naganovdea53042018-04-26 13:10:21 -07002116status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2117{
2118 ALOGV(__func__);
2119
2120 audio_module_handle_t module;
2121 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2122 module = config->ext.device.hw_module;
2123 } else {
2124 module = config->ext.mix.hw_module;
2125 }
2126
2127 Mutex::Autolock _l(mLock);
2128 ssize_t index = mAudioHwDevs.indexOfKey(module);
2129 if (index < 0) {
2130 ALOGW("%s() bad hw module %d", __func__, module);
2131 return BAD_VALUE;
2132 }
2133
2134 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2135 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2136}
2137
Eric Laurent93c3d412014-08-01 14:48:35 -07002138audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2139{
2140 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002141
2142 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2143 if (index >= 0) {
2144 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2145 mHwAvSyncIds.valueAt(index), sessionId);
2146 return mHwAvSyncIds.valueAt(index);
2147 }
2148
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002149 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002150 if (dev == NULL) {
2151 return AUDIO_HW_SYNC_INVALID;
2152 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002153 String8 reply;
2154 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002155 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002156 param = AudioParameter(reply);
2157 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002158
2159 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002160 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002161 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2162 return AUDIO_HW_SYNC_INVALID;
2163 }
2164
2165 // allow only one session for a given HW A/V sync ID.
2166 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2167 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2168 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2169 value, mHwAvSyncIds.keyAt(i));
2170 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002171 break;
2172 }
2173 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002174
2175 mHwAvSyncIds.add(sessionId, value);
2176
2177 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2178 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2179 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002180 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002181 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002182 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002183 String8 keyValuePairs = param.toString();
2184 thread->setParameters(keyValuePairs);
2185 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2186 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002187 break;
2188 }
2189 }
2190
2191 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2192 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002193}
2194
Eric Laurent72e3f392015-05-20 14:43:50 -07002195status_t AudioFlinger::systemReady()
2196{
2197 Mutex::Autolock _l(mLock);
2198 ALOGI("%s", __FUNCTION__);
2199 if (mSystemReady) {
2200 ALOGW("%s called twice", __FUNCTION__);
2201 return NO_ERROR;
2202 }
2203 mSystemReady = true;
2204 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2205 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2206 thread->systemReady();
2207 }
2208 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2209 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2210 thread->systemReady();
2211 }
2212 return NO_ERROR;
2213}
2214
jiabin46a76fa2018-01-05 10:18:21 -08002215status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2216{
jiabin9ff780e2018-03-19 18:19:52 -07002217 AutoMutex lock(mHardwareLock);
2218 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2219 status_t status = dev->getMicrophones(microphones);
2220 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002221}
2222
Eric Laurentfa90e842014-10-17 18:12:31 -07002223// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2224void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2225{
2226 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2227 if (index >= 0) {
2228 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2229 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2230 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002231 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002232 String8 keyValuePairs = param.toString();
2233 thread->setParameters(keyValuePairs);
2234 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2235 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002236 }
2237}
2238
2239
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002240// ----------------------------------------------------------------------------
2241
Eric Laurent83b88082014-06-20 18:31:16 -07002242
Eric Laurent6acd1d42017-01-04 14:23:29 -08002243sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002244 audio_io_handle_t *output,
2245 audio_config_t *config,
2246 audio_devices_t devices,
2247 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002248 audio_output_flags_t flags)
2249{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002250 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002251 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002252 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002253 }
2254
Eric Laurentcf2c0212014-07-25 16:20:43 -07002255 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002256 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2257 } else {
2258 // Audio Policy does not currently request a specific output handle.
2259 // If this is ever needed, see openInput_l() for example code.
2260 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2261 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002262 }
Eric Laurent83b88082014-06-20 18:31:16 -07002263
2264 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2265
Eric Laurent83b88082014-06-20 18:31:16 -07002266 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002267 // This if statement allows overriding the audio policy settings
2268 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2269 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2270 // Check only for Normal Mixing mode
2271 if (kEnableExtendedPrecision) {
2272 // Specify format (uncomment one below to choose)
2273 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2274 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2275 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2276 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002277 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002278 }
2279 if (kEnableExtendedChannels) {
2280 // Specify channel mask (uncomment one below to choose)
2281 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2282 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2283 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2284 }
Eric Laurent83b88082014-06-20 18:31:16 -07002285 }
2286
Phil Burk062e67a2015-02-11 13:40:50 -08002287 AudioStreamOut *outputStream = NULL;
2288 status_t status = outHwDev->openOutputStream(
2289 &outputStream,
2290 *output,
2291 devices,
2292 flags,
2293 config,
2294 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002295
2296 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002297
Phil Burk062e67a2015-02-11 13:40:50 -08002298 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002299 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2300 sp<MmapPlaybackThread> thread =
2301 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2302 devices, AUDIO_DEVICE_NONE, mSystemReady);
2303 mMmapThreads.add(*output, thread);
2304 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2305 *output, thread.get());
2306 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002307 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002308 sp<PlaybackThread> thread;
2309 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2310 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2311 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2312 *output, thread.get());
2313 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2314 || !isValidPcmSinkFormat(config->format)
2315 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2316 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2317 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2318 *output, thread.get());
2319 } else {
2320 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2321 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2322 *output, thread.get());
2323 }
2324 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002325 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002326 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002327 }
Eric Laurent83b88082014-06-20 18:31:16 -07002328 }
2329
2330 return 0;
2331}
2332
Eric Laurentcf2c0212014-07-25 16:20:43 -07002333status_t AudioFlinger::openOutput(audio_module_handle_t module,
2334 audio_io_handle_t *output,
2335 audio_config_t *config,
2336 audio_devices_t *devices,
2337 const String8& address,
2338 uint32_t *latencyMs,
2339 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002341 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2342 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002343 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002344 (devices != NULL) ? *devices : 0,
2345 config->sample_rate,
2346 config->format,
2347 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002348 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002350 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002351 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002353
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 Mutex::Autolock _l(mLock);
2355
Eric Laurent6acd1d42017-01-04 14:23:29 -08002356 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002357 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002358 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2359 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2360 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361
Eric Laurent6acd1d42017-01-04 14:23:29 -08002362 // notify client processes of the new output creation
2363 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002364
Eric Laurent6acd1d42017-01-04 14:23:29 -08002365 // the first primary output opened designates the primary hw device
2366 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002367 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002368 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002369
Eric Laurent6acd1d42017-01-04 14:23:29 -08002370 AutoMutex lock(mHardwareLock);
2371 mHardwareStatus = AUDIO_HW_SET_MODE;
2372 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2373 mHardwareStatus = AUDIO_HW_IDLE;
2374 }
2375 } else {
2376 MmapThread *mmapThread = (MmapThread *)thread.get();
2377 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002378 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002379 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 }
2381
Eric Laurentcf2c0212014-07-25 16:20:43 -07002382 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383}
2384
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002385audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2386 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387{
2388 Mutex::Autolock _l(mLock);
2389 MixerThread *thread1 = checkMixerThread_l(output1);
2390 MixerThread *thread2 = checkMixerThread_l(output2);
2391
2392 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002393 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2394 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002395 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 }
2397
Glenn Kasteneeecb982016-02-26 10:44:04 -08002398 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002399 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 thread->addOutputTrack(thread2);
2401 mPlaybackThreads.add(id, thread);
2402 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002403 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 return id;
2405}
2406
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002407status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408{
Glenn Kastend96c5722012-04-25 13:44:49 -07002409 return closeOutput_nonvirtual(output);
2410}
2411
2412status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2413{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 // keep strong reference on the playback thread so that
2415 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002416 sp<PlaybackThread> playbackThread;
2417 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 {
2419 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002420 playbackThread = checkPlaybackThread_l(output);
2421 if (playbackThread != NULL) {
2422 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423
Andy Hungdc099c22018-09-18 13:46:39 -07002424 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002425
Eric Laurent6acd1d42017-01-04 14:23:29 -08002426 if (playbackThread->type() == ThreadBase::MIXER) {
2427 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2428 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2429 DuplicatingThread *dupThread =
2430 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2431 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2432 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002433 }
2434 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002435
2436
Eric Laurent6acd1d42017-01-04 14:23:29 -08002437 mPlaybackThreads.removeItem(output);
2438 // save all effects to the default thread
2439 if (mPlaybackThreads.size()) {
2440 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2441 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002442 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002443 Mutex::Autolock _dl(dstThread->mLock);
2444 Mutex::Autolock _sl(playbackThread->mLock);
2445 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2446 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002447 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002448 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002449 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 }
2451 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002452 } else {
2453 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2454 if (mmapThread == 0) {
2455 return BAD_VALUE;
2456 }
Andy Hungdc099c22018-09-18 13:46:39 -07002457 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002458 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002459 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002461 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2462 ioDesc->mIoHandle = output;
2463 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002464 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002466 // The thread entity (active unit of execution) is no longer running here,
2467 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468
Eric Laurent6acd1d42017-01-04 14:23:29 -08002469 if (playbackThread != 0) {
2470 playbackThread->exit();
2471 if (!playbackThread->isDuplicating()) {
2472 closeOutputFinish(playbackThread);
2473 }
2474 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002475 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002476 mmapThread->exit();
2477 AudioStreamOut *out = mmapThread->clearOutput();
2478 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2479 // from now on thread->mOutput is NULL
2480 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 }
2482 return NO_ERROR;
2483}
2484
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002485void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002486{
2487 AudioStreamOut *out = thread->clearOutput();
2488 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2489 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002490 delete out;
2491}
2492
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002493void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002494{
2495 mPlaybackThreads.removeItem(thread->mId);
2496 thread->exit();
2497 closeOutputFinish(thread);
2498}
2499
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002500status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501{
2502 Mutex::Autolock _l(mLock);
2503 PlaybackThread *thread = checkPlaybackThread_l(output);
2504
2505 if (thread == NULL) {
2506 return BAD_VALUE;
2507 }
2508
Steve Block3856b092011-10-20 11:56:00 +01002509 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 thread->suspend();
2511
2512 return NO_ERROR;
2513}
2514
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002515status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516{
2517 Mutex::Autolock _l(mLock);
2518 PlaybackThread *thread = checkPlaybackThread_l(output);
2519
2520 if (thread == NULL) {
2521 return BAD_VALUE;
2522 }
2523
Steve Block3856b092011-10-20 11:56:00 +01002524 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525
2526 thread->restore();
2527
2528 return NO_ERROR;
2529}
2530
Eric Laurentcf2c0212014-07-25 16:20:43 -07002531status_t AudioFlinger::openInput(audio_module_handle_t module,
2532 audio_io_handle_t *input,
2533 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002534 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002535 const String8& address,
2536 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002537 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538{
Eric Laurent83b88082014-06-20 18:31:16 -07002539 Mutex::Autolock _l(mLock);
2540
Glenn Kastene7d66712015-03-05 13:46:52 -08002541 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002542 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002543 }
2544
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002545 sp<ThreadBase> thread = openInput_l(
2546 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002547
2548 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002549 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002550 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002551 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002553 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002554}
Dima Zavin799a70e2011-04-18 16:57:27 -07002555
Eric Laurent6acd1d42017-01-04 14:23:29 -08002556sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002557 audio_io_handle_t *input,
2558 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002559 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002560 const String8& address,
2561 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002562 audio_input_flags_t flags,
2563 audio_devices_t outputDevice,
2564 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002565{
Glenn Kastene7d66712015-03-05 13:46:52 -08002566 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002567 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002568 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002569 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002570 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002571
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002572 // Some flags are specific to framework and must not leak to the HAL.
2573 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2574
Glenn Kasteneeecb982016-02-26 10:44:04 -08002575 // Audio Policy can request a specific handle for hardware hotword.
2576 // The goal here is not to re-open an already opened input.
2577 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002578 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002579 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2580 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2581 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2582 return 0;
2583 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2584 // This should not happen in a transient state with current design.
2585 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2586 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002587 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002588
Eric Laurentcf2c0212014-07-25 16:20:43 -07002589 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002590 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002591 sp<StreamInHalInterface> inStream;
2592 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002593 *input, devices, &halconfig, flags, address.string(), source,
2594 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002595 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2596 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002597 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002598 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002599 halconfig.sample_rate,
2600 halconfig.format,
2601 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002602 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002603 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002605 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002606 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002607 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002608 audio_is_linear_pcm(config->format) &&
2609 audio_is_linear_pcm(halconfig.format) &&
2610 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002611 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2612 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002613 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002614 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002615 inStream.clear();
2616 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002617 *input, devices, &halconfig, flags, address.string(), source,
2618 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002619 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620 }
2621
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002622 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002623 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002624 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2625 sp<MmapCaptureThread> thread =
2626 new MmapCaptureThread(this, *input,
2627 inHwDev, inputStream,
2628 primaryOutputDevice_l(), devices, mSystemReady);
2629 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002630 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2631 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002632 return thread;
2633 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002634 // Start record thread
2635 // RecordThread requires both input and output device indication to forward to audio
2636 // pre processing modules
2637 sp<RecordThread> thread = new RecordThread(this,
2638 inputStream,
2639 *input,
2640 primaryOutputDevice_l(),
2641 devices,
2642 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002643 );
2644 mRecordThreads.add(*input, thread);
2645 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2646 return thread;
2647 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 }
2649
Eric Laurentcf2c0212014-07-25 16:20:43 -07002650 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 return 0;
2652}
2653
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002654status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655{
Glenn Kastend96c5722012-04-25 13:44:49 -07002656 return closeInput_nonvirtual(input);
2657}
2658
2659status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2660{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 // keep strong reference on the record thread so that
2662 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002663 sp<RecordThread> recordThread;
2664 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665 {
2666 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002667 recordThread = checkRecordThread_l(input);
2668 if (recordThread != 0) {
2669 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670
Andy Hungdc099c22018-09-18 13:46:39 -07002671 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002672
Eric Laurent6acd1d42017-01-04 14:23:29 -08002673 // If we still have effect chains, it means that a client still holds a handle
2674 // on at least one effect. We must either move the chain to an existing thread with the
2675 // same session ID or put it aside in case a new record thread is opened for a
2676 // new capture on the same session
2677 sp<EffectChain> chain;
2678 {
2679 Mutex::Autolock _sl(recordThread->mLock);
2680 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2681 // Note: maximum one chain per record thread
2682 if (effectChains.size() != 0) {
2683 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002684 }
2685 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002686 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002687 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002688 // This should only happen in case of overlap between one thread tear down and the
2689 // creation of its replacement
2690 size_t i;
2691 for (i = 0; i < mRecordThreads.size(); i++) {
2692 sp<RecordThread> t = mRecordThreads.valueAt(i);
2693 if (t == recordThread) {
2694 continue;
2695 }
2696 if (t->hasAudioSession(chain->sessionId()) != 0) {
2697 Mutex::Autolock _l(t->mLock);
2698 ALOGV("closeInput() found thread %d for effect session %d",
2699 t->id(), chain->sessionId());
2700 t->addEffectChain_l(chain);
2701 break;
2702 }
2703 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002704 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002705 if (i == mRecordThreads.size()) {
2706 putOrphanEffectChain_l(chain);
2707 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002708 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002709 mRecordThreads.removeItem(input);
2710 } else {
2711 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2712 if (mmapThread == 0) {
2713 return BAD_VALUE;
2714 }
Andy Hungdc099c22018-09-18 13:46:39 -07002715 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002716 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002717 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002718 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2719 ioDesc->mIoHandle = input;
2720 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 }
Eric Laurent83b88082014-06-20 18:31:16 -07002722 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2723 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002724 if (recordThread != 0) {
2725 closeInputFinish(recordThread);
2726 } else if (mmapThread != 0) {
2727 mmapThread->exit();
2728 AudioStreamIn *in = mmapThread->clearInput();
2729 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2730 // from now on thread->mInput is NULL
2731 delete in;
2732 }
Eric Laurent83b88082014-06-20 18:31:16 -07002733 return NO_ERROR;
2734}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002736void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002737{
2738 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002739 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002740 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002741 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002742 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002743}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002745void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002746{
2747 mRecordThreads.removeItem(thread->mId);
2748 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749}
2750
Glenn Kastend2304db2014-02-03 07:40:31 -08002751status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752{
2753 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002754 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755
2756 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2757 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002758 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002759 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002760 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2761 mMmapThreads[i]->invalidateTracks(stream);
2762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763 return NO_ERROR;
2764}
2765
2766
Glenn Kasteneeecb982016-02-26 10:44:04 -08002767audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768{
Glenn Kasten9d003132016-04-06 14:38:09 -07002769 // This is a binder API, so a malicious client could pass in a bad parameter.
2770 // Check for that before calling the internal API nextUniqueId().
2771 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2772 ALOGE("newAudioUniqueId invalid use %d", use);
2773 return AUDIO_UNIQUE_ID_ALLOCATE;
2774 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002775 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776}
2777
Glenn Kastend848eb42016-03-08 13:42:11 -08002778void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002779{
2780 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002781 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002782 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002783 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2784 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002785 caller = pid;
2786 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002787
Eric Laurent021cf962014-05-13 10:18:14 -07002788 {
2789 Mutex::Autolock _cl(mClientLock);
2790 // Ignore requests received from processes not known as notification client. The request
2791 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2792 // called from a different pid leaving a stale session reference. Also we don't know how
2793 // to clear this reference if the client process dies.
2794 if (mNotificationClients.indexOfKey(caller) < 0) {
2795 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2796 return;
2797 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002798 }
2799
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002800 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002801 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002802 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002803 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2804 ref->mCnt++;
2805 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002806 return;
2807 }
2808 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002809 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2810 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002811}
2812
Glenn Kastend848eb42016-03-08 13:42:11 -08002813void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002814{
Eric Laurent6c796322019-04-09 14:13:17 -07002815 std::vector< sp<EffectModule> > removedEffects;
2816 {
2817 Mutex::Autolock _l(mLock);
2818 pid_t caller = IPCThreadState::self()->getCallingPid();
2819 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2820 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2821 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2822 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002823 }
Eric Laurent6c796322019-04-09 14:13:17 -07002824 size_t num = mAudioSessionRefs.size();
2825 for (size_t i = 0; i < num; i++) {
2826 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2827 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2828 ref->mCnt--;
2829 ALOGV(" decremented refcount to %d", ref->mCnt);
2830 if (ref->mCnt == 0) {
2831 mAudioSessionRefs.removeAt(i);
2832 delete ref;
2833 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2834 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2835 }
2836 goto Exit;
2837 }
2838 }
2839 // If the caller is audioserver it is likely that the session being released was acquired
2840 // on behalf of a process not in notification clients and we ignore the warning.
2841 ALOGW_IF(!isAudioServerUid(callerUid),
2842 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002843 }
Eric Laurent6c796322019-04-09 14:13:17 -07002844
2845Exit:
2846 for (auto& effect : removedEffects) {
2847 effect->updatePolicyState();
2848 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002849}
2850
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002851bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2852{
2853 size_t num = mAudioSessionRefs.size();
2854 for (size_t i = 0; i < num; i++) {
2855 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2856 if (ref->mSessionid == audioSession) {
2857 return true;
2858 }
2859 }
2860 return false;
2861}
2862
Eric Laurent6c796322019-04-09 14:13:17 -07002863std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002864
Steve Block3856b092011-10-20 11:56:00 +01002865 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002866
2867 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002868 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002869
2870 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2871 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002872 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002873 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2874 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002875 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2876 chains.push(ec);
2877 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002878 }
2879 }
Eric Laurent6c796322019-04-09 14:13:17 -07002880
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002881 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2882 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002883 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002884 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2885 sp<EffectChain> ec = t->mEffectChains[j];
2886 chains.push(ec);
2887 }
2888 }
2889
Eric Laurent6c796322019-04-09 14:13:17 -07002890 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2891 sp<MmapThread> t = mMmapThreads.valueAt(i);
2892 Mutex::Autolock _l(t->mLock);
2893 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2894 sp<EffectChain> ec = t->mEffectChains[j];
2895 chains.push(ec);
2896 }
2897 }
2898
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002899 for (size_t i = 0; i < chains.size(); i++) {
2900 sp<EffectChain> ec = chains[i];
2901 int sessionid = ec->sessionId();
2902 sp<ThreadBase> t = ec->mThread.promote();
2903 if (t == 0) {
2904 continue;
2905 }
2906 size_t numsessionrefs = mAudioSessionRefs.size();
2907 bool found = false;
2908 for (size_t k = 0; k < numsessionrefs; k++) {
2909 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002910 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002911 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002912 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002913 found = true;
2914 break;
2915 }
2916 }
2917 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002918 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002919 // remove all effects from the chain
2920 while (ec->mEffects.size()) {
2921 sp<EffectModule> effect = ec->mEffects[0];
2922 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002923 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002924 if (effect->purgeHandles()) {
2925 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002926 }
Eric Laurent6c796322019-04-09 14:13:17 -07002927 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002928 }
2929 }
2930 }
Eric Laurent6c796322019-04-09 14:13:17 -07002931 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002932}
2933
Andy Hungdc099c22018-09-18 13:46:39 -07002934// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2935void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2936{
2937 audio_utils::FdToString fdToString;
2938 const int fd = fdToString.fd();
2939 if (fd >= 0) {
2940 thread->dump(fd, {} /* args */);
2941 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2942 }
2943}
2944
Glenn Kasteneeecb982016-02-26 10:44:04 -08002945// checkThread_l() must be called with AudioFlinger::mLock held
2946AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2947{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002948 ThreadBase *thread = checkMmapThread_l(ioHandle);
2949 if (thread == 0) {
2950 switch (audio_unique_id_get_use(ioHandle)) {
2951 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2952 thread = checkPlaybackThread_l(ioHandle);
2953 break;
2954 case AUDIO_UNIQUE_ID_USE_INPUT:
2955 thread = checkRecordThread_l(ioHandle);
2956 break;
2957 default:
2958 break;
2959 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002960 }
2961 return thread;
2962}
2963
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002965AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966{
Glenn Kastena1117922012-01-26 10:53:32 -08002967 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968}
2969
2970// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002971AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972{
2973 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002974 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975}
2976
2977// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002978AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979{
Glenn Kastena1117922012-01-26 10:53:32 -08002980 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981}
2982
Eric Laurent6acd1d42017-01-04 14:23:29 -08002983// checkMmapThread_l() must be called with AudioFlinger::mLock held
2984AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2985{
2986 return mMmapThreads.valueFor(io).get();
2987}
2988
2989
2990// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2991AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2992{
Eric Laurent7459b902017-04-19 18:10:41 -07002993 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002994 if (volumeInterface == nullptr) {
2995 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2996 if (mmapThread != nullptr) {
2997 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002998 MmapPlaybackThread *mmapPlaybackThread =
2999 static_cast<MmapPlaybackThread *>(mmapThread);
3000 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003001 }
3002 }
3003 }
3004 return volumeInterface;
3005}
3006
3007Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3008{
3009 Vector <VolumeInterface *> volumeInterfaces;
3010 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003011 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003012 }
3013 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3014 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003015 MmapPlaybackThread *mmapPlaybackThread =
3016 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3017 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003018 }
3019 }
3020 return volumeInterfaces;
3021}
3022
Glenn Kasteneeecb982016-02-26 10:44:04 -08003023audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024{
Glenn Kasten9d003132016-04-06 14:38:09 -07003025 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003026 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003027 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3028 for (int retry = 0; retry < maxRetries; retry++) {
3029 // The cast allows wraparound from max positive to min negative instead of abort
3030 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3031 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3032 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3033 // allow wrap by skipping 0 and -1 for session ids
3034 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3035 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3036 return (audio_unique_id_t) (base | use);
3037 }
3038 }
3039 // We have no way of recovering from wraparound
3040 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3041 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042}
3043
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003044AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003045{
3046 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3047 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003048 if(thread->isDuplicating()) {
3049 continue;
3050 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003051 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003052 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003053 return thread;
3054 }
3055 }
3056 return NULL;
3057}
3058
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003059audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003060{
3061 PlaybackThread *thread = primaryPlaybackThread_l();
3062
3063 if (thread == NULL) {
3064 return 0;
3065 }
3066
Eric Laurentf1c04f92012-08-28 14:26:53 -07003067 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003068}
3069
Glenn Kastena7335632016-06-09 17:09:53 -07003070AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3071{
3072 size_t minFrameCount = 0;
3073 PlaybackThread *minThread = NULL;
3074 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3075 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3076 if (!thread->isDuplicating()) {
3077 size_t frameCount = thread->frameCountHAL();
3078 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3079 (frameCount == minFrameCount && thread->hasFastMixer() &&
3080 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3081 minFrameCount = frameCount;
3082 minThread = thread;
3083 }
3084 }
3085 }
3086 return minThread;
3087}
3088
Eric Laurenta011e352012-03-29 15:51:43 -07003089sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003090 audio_session_t triggerSession,
3091 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003092 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003093 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003094{
3095 Mutex::Autolock _l(mLock);
3096
3097 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3098 status_t playStatus = NAME_NOT_FOUND;
3099 status_t recStatus = NAME_NOT_FOUND;
3100 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3101 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3102 if (playStatus == NO_ERROR) {
3103 return event;
3104 }
3105 }
3106 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3107 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3108 if (recStatus == NO_ERROR) {
3109 return event;
3110 }
3111 }
3112 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3113 mPendingSyncEvents.add(event);
3114 } else {
3115 ALOGV("createSyncEvent() invalid event %d", event->type());
3116 event.clear();
3117 }
3118 return event;
3119}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003120
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121// ----------------------------------------------------------------------------
3122// Effect management
3123// ----------------------------------------------------------------------------
3124
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003125sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3126 return mEffectsFactoryHal;
3127}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128
Glenn Kastenf587ba52012-01-26 16:25:10 -08003129status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130{
3131 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003132 if (mEffectsFactoryHal.get()) {
3133 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3134 } else {
3135 return -ENODEV;
3136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137}
3138
Glenn Kastenf587ba52012-01-26 16:25:10 -08003139status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140{
3141 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003142 if (mEffectsFactoryHal.get()) {
3143 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3144 } else {
3145 return -ENODEV;
3146 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147}
3148
Glenn Kasten5e92a782012-01-30 07:40:52 -08003149status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003150 const effect_uuid_t *pTypeUuid,
3151 uint32_t preferredTypeFlag,
3152 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003154 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3155 return BAD_VALUE;
3156 }
3157
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003159
3160 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003161 return -ENODEV;
3162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003164 status_t status = NO_ERROR;
3165 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3166 // If uuid is specified, request effect descriptor from that.
3167 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3168 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3169 // If uuid is not specified, look for an available implementation
3170 // of the required type instead.
3171
3172 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3173 effect_descriptor_t desc;
3174 desc.flags = 0; // prevent compiler warning
3175
3176 uint32_t numEffects = 0;
3177 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3178 if (status < 0) {
3179 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3180 return status;
3181 }
3182
3183 bool found = false;
3184 for (uint32_t i = 0; i < numEffects; i++) {
3185 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3186 if (status < 0) {
3187 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3188 continue;
3189 }
3190 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3191 // If matching type found save effect descriptor.
3192 found = true;
3193 *descriptor = desc;
3194
3195 // If there's no preferred flag or this descriptor matches the preferred
3196 // flag, success! If this descriptor doesn't match the preferred
3197 // flag, continue enumeration in case a better matching version of this
3198 // effect type is available. Note that this means if no effect with a
3199 // correct flag is found, the descriptor returned will correspond to the
3200 // last effect that at least had a matching type uuid (if any).
3201 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3202 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3203 break;
3204 }
3205 }
3206 }
3207
3208 if (!found) {
3209 status = NAME_NOT_FOUND;
3210 ALOGW("getEffectDescriptor(): Effect not found by type.");
3211 }
3212 } else {
3213 status = BAD_VALUE;
3214 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3215 }
3216 return status;
3217}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003219sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 effect_descriptor_t *pDesc,
3221 const sp<IEffectClient>& effectClient,
3222 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003223 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003224 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003225 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003226 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227 status_t *status,
3228 int *id,
3229 int *enabled)
3230{
3231 status_t lStatus = NO_ERROR;
3232 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234
Eric Laurentb6436272016-12-07 19:24:50 -08003235 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003236 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003237 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3238 ALOGW_IF(pid != -1 && pid != callingPid,
3239 "%s uid %d pid %d tried to pass itself off as pid %d",
3240 __func__, callingUid, callingPid, pid);
3241 pid = callingPid;
3242 }
3243
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003244 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3245 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246
3247 if (pDesc == NULL) {
3248 lStatus = BAD_VALUE;
3249 goto Exit;
3250 }
3251
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003252 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003253 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003254 lStatus = NO_INIT;
3255 goto Exit;
3256 }
3257
Andy Hung6096dcd2019-03-13 13:20:30 -07003258 // check audio settings permission for global effects
3259 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3260 if (!settingsAllowed()) {
3261 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3262 lStatus = PERMISSION_DENIED;
3263 goto Exit;
3264 }
3265 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3266 if (!isAudioServerUid(callingUid)) {
3267 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3268 lStatus = PERMISSION_DENIED;
3269 goto Exit;
3270 }
3271
3272 if (io == AUDIO_IO_HANDLE_NONE) {
3273 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3274 lStatus = BAD_VALUE;
3275 goto Exit;
3276 }
3277 } else {
3278 // general sessionId.
3279
3280 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3281 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3282 lStatus = BAD_VALUE;
3283 goto Exit;
3284 }
3285
3286 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3287 // to prevent creating an effect when one doesn't actually have track with that session?
3288 }
3289
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003291 // Get the full effect descriptor from the uuid/type.
3292 // If the session is the output mix, prefer an auxiliary effect,
3293 // otherwise no preference.
3294 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3295 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3296 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3297 if (lStatus < 0) {
3298 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3299 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 }
3301
3302 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003303 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3305 lStatus = INVALID_OPERATION;
3306 goto Exit;
3307 }
3308
Eric Laurent59255e42011-07-27 19:49:51 -07003309 // check recording permission for visualizer
3310 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003311 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003312 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003313 lStatus = PERMISSION_DENIED;
3314 goto Exit;
3315 }
3316
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003318 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003319 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003320 // if the output returned by getOutputForEffect() is removed before we lock the
3321 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3322 // and we will exit safely
3323 io = AudioSystem::getOutputForEffect(&desc);
3324 ALOGV("createEffect got output %d", io);
3325 }
3326
3327 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328
3329 // If output is not specified try to find a matching audio session ID in one of the
3330 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003331 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3332 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003333 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3334 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003335 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003336 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003337 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3338 if (io == AUDIO_IO_HANDLE_NONE) {
3339 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003341 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003342 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003343 }
Andy Hung444bb552019-03-14 17:06:39 -07003344
3345 // If you wish to create a Record preprocessing AudioEffect in Java,
3346 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3347 // Otherwise it will fail when created on a Playback thread by legacy
3348 // handling below. Ditto with Mmap, the associated Mmap track must be created
3349 // before creating the AudioEffect or the io handle must be specified.
3350 //
3351 // Detect if the effect is created after an AudioRecord is destroyed.
3352 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3353 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3354 " for session %d no longer exists",
3355 __func__, desc.name, sessionId);
3356 lStatus = PERMISSION_DENIED;
3357 goto Exit;
3358 }
3359
3360 // Legacy handling of creating an effect on an expired or made-up
3361 // session id. We think that it is a Playback effect.
3362 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003363 // If no output thread contains the requested session ID, default to
3364 // first output. The effect chain will be moved to the correct output
3365 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003366 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003367 io = mPlaybackThreads.keyAt(0);
3368 }
Steve Block3856b092011-10-20 11:56:00 +01003369 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003370 } else if (checkPlaybackThread_l(io) != nullptr) {
3371 // allow only one effect chain per sessionId on mPlaybackThreads.
3372 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3373 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3374 if (io == checkIo) continue;
3375 const uint32_t sessionType =
3376 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3377 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3378 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3379 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3380 android_errorWriteLog(0x534e4554, "123237974");
3381 lStatus = BAD_VALUE;
3382 goto Exit;
3383 }
3384 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003385 }
3386 ThreadBase *thread = checkRecordThread_l(io);
3387 if (thread == NULL) {
3388 thread = checkPlaybackThread_l(io);
3389 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003390 thread = checkMmapThread_l(io);
3391 if (thread == NULL) {
3392 ALOGE("createEffect() unknown output thread");
3393 lStatus = BAD_VALUE;
3394 goto Exit;
3395 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003396 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003397 } else {
3398 // Check if one effect chain was awaiting for an effect to be created on this
3399 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003400 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003401 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003402 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003403 thread->addEffectChain_l(chain);
3404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003406
Eric Laurent021cf962014-05-13 10:18:14 -07003407 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003409 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003410 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003411 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003412 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003413 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003414 // remove local strong reference to Client with mClientLock held
3415 Mutex::Autolock _cl(mClientLock);
3416 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003417 } else {
3418 // handle must be valid here, but check again to be safe.
3419 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421 }
3422
Eric Laurent6c796322019-04-09 14:13:17 -07003423 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3424 // Check CPU and memory usage
3425 sp<EffectModule> effect = handle->effect().promote();
3426 if (effect != nullptr) {
3427 status_t rStatus = effect->updatePolicyState();
3428 if (rStatus != NO_ERROR) {
3429 lStatus = rStatus;
3430 }
3431 }
3432 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003433 handle.clear();
3434 }
3435
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003437 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 return handle;
3439}
3440
Glenn Kastend848eb42016-03-08 13:42:11 -08003441status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003442 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003443{
Steve Block3856b092011-10-20 11:56:00 +01003444 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003445 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003446 Mutex::Autolock _l(mLock);
3447 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003448 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003449 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450 }
Eric Laurentde070132010-07-13 04:45:46 -07003451 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3452 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003453 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003454 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 }
Eric Laurentde070132010-07-13 04:45:46 -07003456 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3457 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003458 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003459 return BAD_VALUE;
3460 }
3461
3462 Mutex::Autolock _dl(dstThread->mLock);
3463 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003464 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003465}
3466
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003467// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003468status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003469 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003470 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003471{
Steve Block3856b092011-10-20 11:56:00 +01003472 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003473 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003474
Eric Laurent59255e42011-07-27 19:49:51 -07003475 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003476 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003477 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003478 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003479 return INVALID_OPERATION;
3480 }
3481
Eric Laurent4c415062016-06-17 16:14:16 -07003482 // Check whether the destination thread and all effects in the chain are compatible
3483 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003484 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003485 " destination thread %p is not compatible with effects in the chain",
3486 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003487 return INVALID_OPERATION;
3488 }
3489
Eric Laurent39e94f82010-07-28 01:32:47 -07003490 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003491 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003492 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003493 // removed.
3494 srcThread->removeEffectChain_l(chain);
3495
3496 // transfer all effects one by one so that new effect chain is created on new thread with
3497 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003498 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003499 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003500 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003501 Vector< sp<EffectModule> > removed;
3502 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003503 while (effect != 0) {
3504 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003505 removed.add(effect);
3506 status = dstThread->addEffect_l(effect);
3507 if (status != NO_ERROR) {
3508 break;
3509 }
Eric Laurentec35a142011-10-05 17:42:25 -07003510 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3511 if (effect->state() == EffectModule::ACTIVE ||
3512 effect->state() == EffectModule::STOPPING) {
3513 effect->start();
3514 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003515 // if the move request is not received from audio policy manager, the effect must be
3516 // re-registered with the new strategy and output
3517 if (dstChain == 0) {
3518 dstChain = effect->chain().promote();
3519 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003520 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003521 status = NO_INIT;
3522 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003523 }
3524 strategy = dstChain->strategy();
3525 }
Eric Laurentde070132010-07-13 04:45:46 -07003526 effect = chain->getEffectFromId_l(0);
3527 }
3528
Eric Laurent5baf2af2013-09-12 17:37:00 -07003529 if (status != NO_ERROR) {
3530 for (size_t i = 0; i < removed.size(); i++) {
3531 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003532 }
3533 }
3534
3535 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536}
3537
Eric Laurent6c796322019-04-09 14:13:17 -07003538status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3539 const sp<PlaybackThread>& dstThread,
3540 sp<PlaybackThread> *srcThread)
3541{
3542 status_t status = NO_ERROR;
3543 Mutex::Autolock _l(mLock);
3544 sp<PlaybackThread> thread = getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3545
3546 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3547 Mutex::Autolock _dl(dstThread->mLock);
3548 Mutex::Autolock _sl(thread->mLock);
3549 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3550 sp<EffectChain> dstChain;
3551 if (srcChain == 0) {
3552 return INVALID_OPERATION;
3553 }
3554
3555 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3556 if (effect == 0) {
3557 return INVALID_OPERATION;
3558 }
3559 thread->removeEffect_l(effect);
3560 status = dstThread->addEffect_l(effect);
3561 if (status != NO_ERROR) {
3562 thread->addEffect_l(effect);
3563 status = INVALID_OPERATION;
3564 goto Exit;
3565 }
3566
3567 dstChain = effect->chain().promote();
3568 if (dstChain == 0) {
3569 thread->addEffect_l(effect);
3570 status = INVALID_OPERATION;
3571 }
3572
3573Exit:
3574 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3575 if (effect->state() == EffectModule::ACTIVE ||
3576 effect->state() == EffectModule::STOPPING) {
3577 effect->start();
3578 }
3579 }
3580
3581 if (status == NO_ERROR && srcThread != nullptr) {
3582 *srcThread = thread;
3583 }
3584 return status;
3585}
3586
Eric Laurent5baf2af2013-09-12 17:37:00 -07003587bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003588{
3589 if (mGlobalEffectEnableTime != 0 &&
3590 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3591 return true;
3592 }
3593
3594 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3595 sp<EffectChain> ec =
3596 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003597 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003598 return true;
3599 }
3600 }
3601 return false;
3602}
3603
Eric Laurent5baf2af2013-09-12 17:37:00 -07003604void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003605{
3606 Mutex::Autolock _l(mLock);
3607
3608 mGlobalEffectEnableTime = systemTime();
3609
3610 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3611 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3612 if (t->mType == ThreadBase::OFFLOAD) {
3613 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3614 }
3615 }
3616
3617}
3618
Eric Laurentaaa44472014-09-12 17:41:50 -07003619status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3620{
Eric Laurentd8365c52017-07-16 15:27:05 -07003621 // clear possible suspended state before parking the chain so that it starts in default state
3622 // when attached to a new record thread
3623 chain->setEffectSuspended_l(FX_IID_AEC, false);
3624 chain->setEffectSuspended_l(FX_IID_NS, false);
3625
Glenn Kastend848eb42016-03-08 13:42:11 -08003626 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003627 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003628 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003629 if (index >= 0) {
3630 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3631 return ALREADY_EXISTS;
3632 }
3633 mOrphanEffectChains.add(session, chain);
3634 return NO_ERROR;
3635}
3636
3637sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3638{
3639 sp<EffectChain> chain;
3640 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003641 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003642 if (index >= 0) {
3643 chain = mOrphanEffectChains.valueAt(index);
3644 mOrphanEffectChains.removeItemsAt(index);
3645 }
3646 return chain;
3647}
3648
3649bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3650{
3651 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003652 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003653 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003654 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003655 if (index >= 0) {
3656 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003657 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003658 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003659 mOrphanEffectChains.removeItemsAt(index);
3660 }
3661 return true;
3662 }
3663 return false;
3664}
3665
3666
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667// ----------------------------------------------------------------------------
3668
3669status_t AudioFlinger::onTransact(
3670 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3671{
3672 return BnAudioFlinger::onTransact(code, data, reply, flags);
3673}
3674
Glenn Kasten63238ef2015-03-02 15:50:29 -08003675} // namespace android