blob: 2bef6ac15febb458eb2d28732b5a987838510abe [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
jiabina392a552019-09-23 10:34:20 -070022// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23#define AUDIO_ARRAYS_STATIC_CHECK 1
24
Glenn Kasten153b9fe2013-07-15 11:23:36 -070025#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080026#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <math.h>
28#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/time.h>
31#include <sys/resource.h>
Mikhail Naganov88b30d22020-03-09 19:43:13 +000032#include <thread>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080034#include <android/media/IAudioPolicyService.h>
jiabin57303cc2018-12-18 15:45:57 -080035#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080036#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <binder/IServiceManager.h>
38#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070039#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070041#include <media/audiohal/DeviceHalInterface.h>
42#include <media/audiohal/DevicesFactoryHalInterface.h>
43#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070044#include <media/AudioParameter.h>
Andy Hungb68f5eb2019-12-03 16:49:17 -080045#include <media/MediaMetricsItem.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070046#include <media/TypeConverter.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080047#include <mediautils/TimeCheck.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070048#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <utils/String16.h>
50#include <utils/threads.h>
51
Steven Morelandf0c02ce2018-02-23 14:53:55 -080052#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <cutils/properties.h>
54
Dima Zavin64760242011-05-11 14:15:23 -070055#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070056#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070059#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070060
Andy Hung6770c6f2015-04-07 13:43:36 -070061#include <media/AudioResamplerPublic.h>
62
Mikhail Naganov9fe94012016-10-14 14:57:40 -070063#include <system/audio_effects/effect_visualizer.h>
64#include <system/audio_effects/effect_ns.h>
65#include <system/audio_effects/effect_aec.h>
jiabineb3bda02020-06-30 14:07:03 -070066#include <system/audio_effects/effect_hapticgenerator.h>
Eric Laurentf690c462021-09-17 14:47:03 +020067#include <system/audio_effects/effect_spatializer.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070068
Glenn Kasten3b21c502011-12-15 09:52:39 -080069#include <audio_utils/primitives.h>
70
Eric Laurentfeb0db62011-07-22 09:04:31 -070071#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080072
Glenn Kasten9e58b552013-01-18 15:09:48 -080073#include <media/IMediaLogService.h>
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070074#include <media/AidlConversion.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080075#include <media/AudioValidator.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080076#include <media/nbaio/Pipe.h>
77#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080078#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070079#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungab7ef302018-05-15 19:35:29 -070080#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070081#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070082#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080083
rago3bd1c872016-09-26 12:58:14 -070084//#define BUFLOG_NDEBUG 0
85#include <BufLog.h>
86
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080087#include "TypedLogger.h"
88
Mathias Agopian65ab4712010-07-14 17:59:35 -070089// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
John Grossman1c345192012-03-27 14:00:17 -070091// Note: the following macro is used for extremely verbose logging message. In
92// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
93// 0; but one side effect of this is to turn all LOGV's as well. Some messages
94// are so verbose that we want to suppress them even when we have ALOG_ASSERT
95// turned on. Do not uncomment the #def below unless you really know what you
96// are doing and want to see all of the extremely verbose messages.
97//#define VERY_VERY_VERBOSE_LOGGING
98#ifdef VERY_VERY_VERBOSE_LOGGING
99#define ALOGVV ALOGV
100#else
101#define ALOGVV(a...) do { } while(0)
102#endif
Eric Laurentde070132010-07-13 04:45:46 -0700103
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104namespace android {
105
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700106using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000107using android::content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700108
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800109static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
110static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700111static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700112static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
Glenn Kasten58912562012-04-03 10:45:00 -0700114
John Grossman4ff14ba2012-02-08 16:37:41 -0800115nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800116
Eric Laurent81784c32012-11-19 14:55:58 -0800117uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700118
Eric Laurent813e2a72013-08-31 12:59:48 -0700119// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
120// we define a minimum time during which a global effect is considered enabled.
121static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
122
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700123// Keep a strong reference to media.log service around forever.
124// The service is within our parent process so it can never die in a way that we could observe.
125// These two variables are const after initialization.
126static sp<IBinder> sMediaLogServiceAsBinder;
127static sp<IMediaLogService> sMediaLogService;
128
129static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
130
131static void sMediaLogInit()
132{
133 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
134 if (sMediaLogServiceAsBinder != 0) {
135 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
136 }
137}
138
jiabin57303cc2018-12-18 15:45:57 -0800139// Keep a strong reference to external vibrator service
140static sp<os::IExternalVibratorService> sExternalVibratorService;
141
142static sp<os::IExternalVibratorService> getExternalVibratorService() {
143 if (sExternalVibratorService == 0) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700144 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800145 String16("external_vibrator_service"));
146 if (binder != 0) {
147 sExternalVibratorService =
148 interface_cast<os::IExternalVibratorService>(binder);
149 }
150 }
151 return sExternalVibratorService;
152}
153
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000154class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
155 public:
156 void onNewDevicesAvailable() override {
157 // Start a detached thread to execute notification in parallel.
158 // This is done to prevent mutual blocking of audio_flinger and
159 // audio_policy services during system initialization.
160 std::thread notifier([]() {
161 AudioSystem::onNewAudioModulesAvailable();
162 });
163 notifier.detach();
164 }
165};
166
Svet Ganov33761132021-05-13 22:51:08 +0000167// TODO b/182392769: use attribution source util
Eric Laurentec376dc2021-04-08 20:41:22 +0200168/* static */
Svet Ganov33761132021-05-13 22:51:08 +0000169AttributionSourceState AudioFlinger::checkAttributionSourcePackage(
170 const AttributionSourceState& attributionSource) {
Eric Laurentec376dc2021-04-08 20:41:22 +0200171 Vector<String16> packages;
Svet Ganov33761132021-05-13 22:51:08 +0000172 PermissionController{}.getPackagesForUid(attributionSource.uid, packages);
Eric Laurentec376dc2021-04-08 20:41:22 +0200173
Svet Ganov33761132021-05-13 22:51:08 +0000174 AttributionSourceState checkedAttributionSource = attributionSource;
175 if (!attributionSource.packageName.has_value()
176 || attributionSource.packageName.value().size() == 0) {
Eric Laurentec376dc2021-04-08 20:41:22 +0200177 if (!packages.isEmpty()) {
Svet Ganov33761132021-05-13 22:51:08 +0000178 checkedAttributionSource.packageName =
Eric Laurentec376dc2021-04-08 20:41:22 +0200179 std::move(legacy2aidl_String16_string(packages[0]).value());
180 }
181 } else {
182 String16 opPackageLegacy = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000183 aidl2legacy_string_view_String16(attributionSource.packageName.value_or("")));
Eric Laurentec376dc2021-04-08 20:41:22 +0200184 if (std::find_if(packages.begin(), packages.end(),
185 [&opPackageLegacy](const auto& package) {
186 return opPackageLegacy == package; }) == packages.end()) {
187 ALOGW("The package name(%s) provided does not correspond to the uid %d",
Svet Ganov33761132021-05-13 22:51:08 +0000188 attributionSource.packageName.value_or("").c_str(), attributionSource.uid);
189 checkedAttributionSource.packageName = std::optional<std::string>();
Eric Laurentec376dc2021-04-08 20:41:22 +0200190 }
191 }
Svet Ganov33761132021-05-13 22:51:08 +0000192 return checkedAttributionSource;
Eric Laurentec376dc2021-04-08 20:41:22 +0200193}
194
Mathias Agopian65ab4712010-07-14 17:59:35 -0700195// ----------------------------------------------------------------------------
196
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700197std::string formatToString(audio_format_t format) {
198 std::string result;
199 FormatConverter::toString(format, result);
200 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800201}
202
Mathias Agopian65ab4712010-07-14 17:59:35 -0700203// ----------------------------------------------------------------------------
204
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800205void AudioFlinger::instantiate() {
206 sp<IServiceManager> sm(defaultServiceManager());
207 sm->addService(String16(IAudioFlinger::DEFAULT_SERVICE_NAME),
208 new AudioFlingerServerAdapter(new AudioFlinger()), false,
209 IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
210}
211
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212AudioFlinger::AudioFlinger()
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800213 : mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800215 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700216 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800217 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700219 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800220 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700221 mBtNrecIsOff(false),
222 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700223 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800224 mTotalMemory(0),
225 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700226 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700227 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800228 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700229 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700230{
Eric Laurentf43be0c2021-03-25 10:45:53 +0100231 // Move the audio session unique ID generator start base as time passes to limit risk of
232 // generating the same ID again after an audioserver restart.
233 // This is important because clients will reuse previously allocated audio session IDs
234 // when reconnecting after an audioserver restart and newly allocated IDs may conflict with
235 // active clients.
236 // Moving the base by 1 for each elapsed second is a good compromise between avoiding overlap
237 // between allocation ranges and not reaching wrap around too soon.
238 timespec ts{};
239 clock_gettime(CLOCK_MONOTONIC, &ts);
240 // zero ID has a special meaning, so start allocation at least at AUDIO_UNIQUE_ID_USE_MAX
Eric Laurentf37f1982021-06-01 13:23:27 +0200241 uint32_t movingBase = (uint32_t)std::max((long)1, ts.tv_sec);
Glenn Kastend2e67e12016-04-11 08:26:37 -0700242 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
243 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
Eric Laurentf43be0c2021-03-25 10:45:53 +0100244 mNextUniqueIds[use] =
Eric Laurentf37f1982021-06-01 13:23:27 +0200245 ((use == AUDIO_UNIQUE_ID_USE_SESSION || use == AUDIO_UNIQUE_ID_USE_CLIENT) ?
246 movingBase : 1) * AUDIO_UNIQUE_ID_USE_MAX;
Glenn Kastend2e67e12016-04-11 08:26:37 -0700247 }
248
Eric Laurent94ca1142020-10-07 10:45:20 -0700249#if 1
250 // FIXME See bug 165702394 and bug 168511485
251 const bool doLog = false;
252#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800253 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700254#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800255 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800256 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
257 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700258 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800259 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700260
Wei Jia3f273d12015-11-24 09:06:49 -0800261 // reset battery stats.
262 // if the audio service has crashed, battery stats could be left
263 // in bad state, reset the state upon service start.
264 BatteryNotifier::getInstance().noteResetAudio();
265
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700266 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700267 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
268
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800269 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700270 std::vector<pid_t> halPids;
271 mDevicesFactoryHal->getHalPids(&halPids);
272 TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800273
274 // Notify that we have started (also called when audioserver service restarts)
275 mediametrics::LogItem(mMetricsId)
276 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
277 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700278}
279
280void AudioFlinger::onFirstRef()
281{
Eric Laurent93575202011-01-18 18:39:02 -0800282 Mutex::Autolock _l(mLock);
283
Dima Zavin799a70e2011-04-18 16:57:27 -0700284 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800285 char val_str[PROPERTY_VALUE_MAX] = { 0 };
286 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
287 uint32_t int_val;
288 if (1 == sscanf(val_str, "%u", &int_val)) {
289 mStandbyTimeInNsecs = milliseconds(int_val);
290 ALOGI("Using %u mSec as standby time.", int_val);
291 } else {
292 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
293 ALOGI("Using default %u mSec as standby time.",
294 (uint32_t)(mStandbyTimeInNsecs / 1000000));
295 }
296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700297
Eric Laurenta4c5a552012-03-29 10:12:40 -0700298 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800299
Andy Hung6626a012021-01-12 13:38:00 -0800300 gAudioFlinger = this; // we are already refcounted, store into atomic pointer.
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000301
302 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
303 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304}
305
Eric Laurent42896a02019-09-27 15:40:33 -0700306status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
307 TimeCheck::setAudioHalPids(pids);
308 return NO_ERROR;
309}
310
jiabin1319f5a2021-03-30 22:21:24 +0000311status_t AudioFlinger::setVibratorInfos(
312 const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
313 Mutex::Autolock _l(mLock);
314 mAudioVibratorInfos = vibratorInfos;
315 return NO_ERROR;
316}
317
jiabinf042b9b2021-05-07 23:46:28 +0000318status_t AudioFlinger::updateSecondaryOutputs(
319 const TrackSecondaryOutputsMap& trackSecondaryOutputs) {
320 Mutex::Autolock _l(mLock);
321 for (const auto& [trackId, secondaryOutputs] : trackSecondaryOutputs) {
322 size_t i = 0;
323 for (; i < mPlaybackThreads.size(); ++i) {
324 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
325 Mutex::Autolock _tl(thread->mLock);
326 sp<PlaybackThread::Track> track = thread->getTrackById_l(trackId);
327 if (track != nullptr) {
328 ALOGD("%s trackId: %u", __func__, trackId);
329 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
330 break;
331 }
332 }
333 ALOGW_IF(i >= mPlaybackThreads.size(),
334 "%s cannot find track with id %u", __func__, trackId);
335 }
336 return NO_ERROR;
337}
338
Mikhail Naganovd7ba61d2022-02-01 23:53:59 +0000339status_t AudioFlinger::setDeviceConnectedState(const struct audio_port_v7 *port, bool connected) {
340 status_t final_result = NO_INIT;
341 Mutex::Autolock _l(mLock);
342 AutoMutex lock(mHardwareLock);
343 mHardwareStatus = AUDIO_HW_SET_CONNECTED_STATE;
344 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
345 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
346 status_t result = dev->setConnectedState(port, connected);
347 // Same logic as with setParameter: it's a success if at least one
348 // HAL module accepts the update.
349 if (final_result != NO_ERROR) {
350 final_result = result;
351 }
352 }
353 mHardwareStatus = AUDIO_HW_IDLE;
354 return final_result;
355}
356
jiabin1319f5a2021-03-30 22:21:24 +0000357// getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
Lais Andradebc3f37a2021-07-02 00:13:19 +0100358std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() {
jiabin1319f5a2021-03-30 22:21:24 +0000359 if (mAudioVibratorInfos.empty()) {
Lais Andradebc3f37a2021-07-02 00:13:19 +0100360 return {};
jiabin1319f5a2021-03-30 22:21:24 +0000361 }
Lais Andradebc3f37a2021-07-02 00:13:19 +0100362 return mAudioVibratorInfos.front();
jiabin1319f5a2021-03-30 22:21:24 +0000363}
364
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365AudioFlinger::~AudioFlinger()
366{
367 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700368 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700369 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 }
371 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700372 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700373 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700374 }
Andy Hungb4946b62019-03-14 11:19:28 -0700375 while (!mMmapThreads.isEmpty()) {
376 const audio_io_handle_t io = mMmapThreads.keyAt(0);
377 if (mMmapThreads.valueAt(0)->isOutput()) {
378 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
379 } else {
380 closeInput_nonvirtual(io); // removes entry from mMmapThreads
381 }
382 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700383
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800384 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
385 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700386 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700388
389 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700390 if (sMediaLogService != 0) {
391 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
392 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
393 mUnregisteredWriters.pop();
394 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700395 }
396 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397}
398
Eric Laurentfc235202016-12-20 18:48:17 -0800399//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800400__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800401status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
402 const audio_attributes_t *attr,
403 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700404 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800405 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800406 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800407 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700408 sp<MmapStreamInterface>& interface,
409 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800410{
Andy Hung6626a012021-01-12 13:38:00 -0800411 // TODO: Use ServiceManager to get IAudioFlinger instead of by atomic pointer.
412 // This allows moving oboeservice (AAudio) to a separate process in the future.
413 sp<AudioFlinger> af = AudioFlinger::gAudioFlinger.load(); // either nullptr or singleton AF.
Eric Laurentfc235202016-12-20 18:48:17 -0800414 status_t ret = NO_INIT;
415 if (af != 0) {
416 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800417 direction, attr, config, client, deviceId,
418 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800419 }
420 return ret;
421}
422
Eric Laurent6acd1d42017-01-04 14:23:29 -0800423status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
424 const audio_attributes_t *attr,
425 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700426 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800427 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800428 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800429 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700430 sp<MmapStreamInterface>& interface,
431 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800432{
433 status_t ret = initCheck();
434 if (ret != NO_ERROR) {
435 return ret;
436 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800437 audio_session_t actualSessionId = *sessionId;
438 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
439 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
440 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800441 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700442 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800443 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700444 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800445 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
446 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
447 fullConfig.sample_rate = config->sample_rate;
448 fullConfig.channel_mask = config->channel_mask;
449 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800450 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700451
452 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800453 actualSessionId,
Svet Ganov33761132021-05-13 22:51:08 +0000454 &streamType, client.attributionSource,
Ricardo Correa57a37692020-03-23 17:27:25 -0700455 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800456 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
457 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800458 deviceId, &portId, &secondaryOutputs);
459 ALOGW_IF(!secondaryOutputs.empty(),
460 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800461 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700462 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700463 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800464 actualSessionId,
Svet Ganov33761132021-05-13 22:51:08 +0000465 client.attributionSource,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800466 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700467 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800468 }
469 if (ret != NO_ERROR) {
470 return ret;
471 }
472
473 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
474 // audio policy manager and we can retrieve it
475 sp<MmapThread> thread = mMmapThreads.valueFor(io);
476 if (thread != 0) {
477 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700478 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700479 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800480 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800481 config->sample_rate = thread->sampleRate();
482 config->channel_mask = thread->channelMask();
483 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800484 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700485 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700486 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700487 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800488 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700489 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800490 ret = NO_INIT;
491 }
492
493 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
494
Eric Laurentfc235202016-12-20 18:48:17 -0800495 return ret;
496}
497
jiabin57303cc2018-12-18 15:45:57 -0800498/* static */
499int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
500 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
jiabin78dc9c82021-02-22 19:13:29 +0000501 if (evs != nullptr) {
jiabin57303cc2018-12-18 15:45:57 -0800502 int32_t ret;
503 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
504 if (status.isOk()) {
jiabin78dc9c82021-02-22 19:13:29 +0000505 ALOGD("%s, start external vibration with intensity as %d", __func__, ret);
jiabin57303cc2018-12-18 15:45:57 -0800506 return ret;
507 }
508 }
jiabin78dc9c82021-02-22 19:13:29 +0000509 ALOGD("%s, start external vibration with intensity as MUTE due to %s",
510 __func__,
511 evs == nullptr ? "external vibration service not found"
512 : "error when querying intensity");
jiabine70bc7f2020-06-30 22:07:55 -0700513 return static_cast<int>(os::HapticScale::MUTE);
jiabin57303cc2018-12-18 15:45:57 -0800514}
515
516/* static */
517void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
518 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
519 if (evs != 0) {
520 evs->onExternalVibrationStop(*externalVibration);
521 }
522}
523
Eric Laurentb82e6b72019-11-22 17:25:04 -0800524status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
525 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700526 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800527 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
528 if (audioHwDevice == nullptr) {
529 return NO_INIT;
530 }
531 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
532}
533
534status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
535 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700536 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800537 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
538 if (audioHwDevice == nullptr) {
539 return NO_INIT;
540 }
541 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
542}
543
Eric Laurenta4c5a552012-03-29 10:12:40 -0700544static const char * const audio_interfaces[] = {
545 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
546 AUDIO_HARDWARE_MODULE_ID_A2DP,
547 AUDIO_HARDWARE_MODULE_ID_USB,
548};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700549
Phil Burk062e67a2015-02-11 13:40:50 -0800550AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700551 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700552 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700553{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700554 // if module is 0, the request comes from an old policy manager and we should load
555 // well known modules
Eric Laurent00abf0d2020-04-22 19:28:22 -0700556 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700557 if (module == 0) {
558 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700559 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700560 loadHwModule_l(audio_interfaces[i]);
561 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700562 // then try to find a module supporting the requested device.
563 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
564 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700565 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
566 uint32_t supportedDevices;
567 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700568 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700569 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700570 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700571 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700572 } else {
573 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700574 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
575 if (audioHwDevice != NULL) {
576 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700577 }
578 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700579
Dima Zavin799a70e2011-04-18 16:57:27 -0700580 return NULL;
581}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582
Glenn Kasten0f11b512014-01-31 16:18:54 -0800583void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 String8 result;
586
587 result.append("Clients:\n");
588 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800589 sp<Client> client = mClients.valueAt(i).promote();
590 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800591 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 }
593 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700594
Eric Laurentd1b28d42013-09-18 18:47:13 -0700595 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800596 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700597 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800598 const pid_t pid = mNotificationClients[i]->getPid();
599 const uid_t uid = mNotificationClients[i]->getUid();
600 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
601 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700602 }
603
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700604 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800605 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700606 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
607 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800608 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
609 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
610 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613}
614
615
Glenn Kasten0f11b512014-01-31 16:18:54 -0800616void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617{
618 const size_t SIZE = 256;
619 char buffer[SIZE];
620 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800621 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622
John Grossman4ff14ba2012-02-08 16:37:41 -0800623 snprintf(buffer, SIZE, "Hardware status: %d\n"
624 "Standby Time mSec: %u\n",
625 hardwareStatus,
626 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 result.append(buffer);
628 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629}
630
Glenn Kasten0f11b512014-01-31 16:18:54 -0800631void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632{
633 const size_t SIZE = 256;
634 char buffer[SIZE];
635 String8 result;
636 snprintf(buffer, SIZE, "Permission Denial: "
637 "can't dump AudioFlinger from pid=%d, uid=%d\n",
638 IPCThreadState::self()->getCallingPid(),
639 IPCThreadState::self()->getCallingUid());
640 result.append(buffer);
641 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642}
643
Eric Laurent81784c32012-11-19 14:55:58 -0800644bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700646 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
647 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648}
649
650status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
651{
Glenn Kasten44deb052012-02-05 18:09:08 -0800652 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 dumpPermissionDenial(fd, args);
654 } else {
655 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800656 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657 if (!hardwareLocked) {
658 String8 result(kHardwareLockedString);
659 write(fd, result.string(), result.size());
660 } else {
661 mHardwareLock.unlock();
662 }
663
Eric Tan7b651152018-07-13 10:17:19 -0700664 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700665
666 // failed to lock - AudioFlinger is probably deadlocked
667 if (!locked) {
668 String8 result(kDeadlockedString);
669 write(fd, result.string(), result.size());
670 }
671
Eric Laurent021cf962014-05-13 10:18:14 -0700672 bool clientLocked = dumpTryLock(mClientLock);
673 if (!clientLocked) {
674 String8 result(kClientLockedString);
675 write(fd, result.string(), result.size());
676 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700677
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700678 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700679 mEffectsFactoryHal->dumpEffects(fd);
680 } else {
681 String8 result(kNoEffectsFactory);
682 write(fd, result.string(), result.size());
683 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700684
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700686 if (clientLocked) {
687 mClientLock.unlock();
688 }
689
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690 dumpInternals(fd, args);
691
692 // dump playback threads
693 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
694 mPlaybackThreads.valueAt(i)->dump(fd, args);
695 }
696
697 // dump record threads
698 for (size_t i = 0; i < mRecordThreads.size(); i++) {
699 mRecordThreads.valueAt(i)->dump(fd, args);
700 }
701
Eric Laurent6acd1d42017-01-04 14:23:29 -0800702 // dump mmap threads
703 for (size_t i = 0; i < mMmapThreads.size(); i++) {
704 mMmapThreads.valueAt(i)->dump(fd, args);
705 }
706
Eric Laurentaaa44472014-09-12 17:41:50 -0700707 // dump orphan effect chains
708 if (mOrphanEffectChains.size() != 0) {
709 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
710 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
711 mOrphanEffectChains.valueAt(i)->dump(fd, args);
712 }
713 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700714 // dump all hardware devs
715 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700716 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Andy Hung542ae9b2021-06-16 09:37:53 -0700717 dev->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700719
Mikhail Naganov201369b2018-05-16 16:52:32 -0700720 mPatchPanel.dump(fd);
721
Eric Laurentb82e6b72019-11-22 17:25:04 -0800722 mDeviceEffectManager.dump(fd);
723
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700724 // dump external setParameters
725 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
726 dprintf(fd, "\n%s setParameters:\n", name);
727 logger.dump(fd, " " /* prefix */);
728 };
729 dumpLogger(mRejectedSetParameterLog, "Rejected");
730 dumpLogger(mAppSetParameterLog, "App");
731 dumpLogger(mSystemSetParameterLog, "System");
732
Andy Hunga8115dc2018-08-24 15:51:59 -0700733 // dump historical threads in the last 10 seconds
734 const std::string threadLog = mThreadLog.dumpToString(
735 "Historical Thread Log ", 0 /* lines */,
736 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
737 write(fd, threadLog.c_str(), threadLog.size());
738
rago3bd1c872016-09-26 12:58:14 -0700739 BUFLOG_RESET;
740
Glenn Kastend65d73c2012-06-22 17:21:07 -0700741 if (locked) {
742 mLock.unlock();
743 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800744
Andy Hung8946a282018-04-19 20:04:56 -0700745#ifdef TEE_SINK
746 // NBAIO_Tee dump is safe to call outside of AF lock.
747 NBAIO_Tee::dumpAll(fd, "_DUMP");
748#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800749 // append a copy of media.log here by forwarding fd to it, but don't attempt
750 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700751 if (sMediaLogServiceAsBinder != 0) {
752 dprintf(fd, "\nmedia.log:\n");
753 Vector<String16> args;
754 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800755 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700756
757 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700758 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700759 bool unreachableMemory = false;
760 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700761 if (arg == String16("-m")) {
762 dumpMem = true;
763 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700764 unreachableMemory = true;
765 }
766 }
767
Andy Hung07b745e2016-05-23 16:21:07 -0700768 if (dumpMem) {
769 dprintf(fd, "\nDumping memory:\n");
770 std::string s = dumpMemoryAddresses(100 /* limit */);
771 write(fd, s.c_str(), s.size());
772 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700773 if (unreachableMemory) {
774 dprintf(fd, "\nDumping unreachable memory:\n");
775 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700776 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700777 write(fd, s.c_str(), s.size());
778 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779 }
780 return NO_ERROR;
781}
782
Eric Laurent021cf962014-05-13 10:18:14 -0700783sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800784{
Eric Laurent021cf962014-05-13 10:18:14 -0700785 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800786 // If pid is already in the mClients wp<> map, then use that entry
787 // (for which promote() is always != 0), otherwise create a new entry and Client.
788 sp<Client> client = mClients.valueFor(pid).promote();
789 if (client == 0) {
790 client = new Client(this, pid);
791 mClients.add(pid, client);
792 }
793
794 return client;
795}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796
Glenn Kasten9e58b552013-01-18 15:09:48 -0800797sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
798{
Jiabin Huang60766082020-07-28 22:03:56 +0000799 // If there is no memory allocated for logs, return a no-op writer that does nothing.
800 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700801 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800802 return new NBLog::Writer();
803 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700804 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
805 // If allocation fails, consult the vector of previously unregistered writers
806 // and garbage-collect one or more them until an allocation succeeds
807 if (shared == 0) {
808 Mutex::Autolock _l(mUnregisteredWritersLock);
809 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
810 {
811 // Pick the oldest stale writer to garbage-collect
812 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
813 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700814 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700815 // Now the media.log remote reference to IMemory is gone. When our last local
816 // reference to IMemory also drops to zero at end of this block,
817 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
818 }
819 // Re-attempt the allocation
820 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
821 if (shared != 0) {
822 goto success;
823 }
824 }
825 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +0000826 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -0700827 return new NBLog::Writer();
828 }
829success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700830 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800831 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
832 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700833 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800834 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800835}
836
837void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
838{
Glenn Kasten685ef092013-02-04 08:15:34 -0800839 if (writer == 0) {
840 return;
841 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800842 sp<IMemory> iMemory(writer->getIMemory());
843 if (iMemory == 0) {
844 return;
845 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700846 // Rather than removing the writer immediately, append it to a queue of old writers to
847 // be garbage-collected later. This allows us to continue to view old logs for a while.
848 Mutex::Autolock _l(mUnregisteredWritersLock);
849 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800850}
851
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852// IAudioFlinger interface
853
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -0800854status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
855 media::CreateTrackResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856{
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800857 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -0800858 CreateTrackInput input = VALUE_OR_RETURN_STATUS(CreateTrackInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800859 CreateTrackOutput output;
860
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861 sp<PlaybackThread::Track> track;
862 sp<TrackHandle> trackHandle;
863 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800865 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800866 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800867 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700869 // TODO b/182392553: refactor or make clearer
870 pid_t clientPid =
Svet Ganov33761132021-05-13 22:51:08 +0000871 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(input.clientInfo.attributionSource.pid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700872 bool updatePid = (clientPid == (pid_t)-1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700873 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700874 uid_t clientUid =
Svet Ganov33761132021-05-13 22:51:08 +0000875 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(input.clientInfo.attributionSource.uid));
Eric Laurent6c796322019-04-09 14:13:17 -0700876 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
877 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700878 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700879
Svet Ganov33761132021-05-13 22:51:08 +0000880 AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700881 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800882 ALOGW_IF(clientUid != callingUid,
883 "%s uid %d tried to pass itself off as %d",
884 __FUNCTION__, callingUid, clientUid);
Svet Ganov33761132021-05-13 22:51:08 +0000885 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Eric Laurent21da6472017-11-09 16:29:26 -0800886 clientUid = callingUid;
887 updatePid = true;
888 }
Eric Laurent09f1ed22019-04-24 17:45:17 -0700889 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800890 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700891 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700892 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800893 __func__, callingUid, callingPid, clientPid);
894 clientPid = callingPid;
Svet Ganov33761132021-05-13 22:51:08 +0000895 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700896 }
897
Eric Laurent21da6472017-11-09 16:29:26 -0800898 audio_session_t sessionId = input.sessionId;
899 if (sessionId == AUDIO_SESSION_ALLOCATE) {
900 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800901 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
902 lStatus = BAD_VALUE;
903 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800904 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800905
Eric Laurent21da6472017-11-09 16:29:26 -0800906 output.sessionId = sessionId;
907 output.outputId = AUDIO_IO_HANDLE_NONE;
908 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700909 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Svet Ganov33761132021-05-13 22:51:08 +0000910 adjAttributionSource, &input.config, input.flags,
Ricardo Correa57a37692020-03-23 17:27:25 -0700911 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800912
913 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
914 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
915 goto Exit;
916 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800917 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
918 // but if someone uses binder directly they could bypass that and cause us to crash
919 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000920 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 lStatus = BAD_VALUE;
922 goto Exit;
923 }
924
Glenn Kasten53b5d092014-02-05 10:00:23 -0800925 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800926 if (!audio_is_output_channel(input.config.channel_mask)) {
927 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800928 lStatus = BAD_VALUE;
929 goto Exit;
930 }
931
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700932 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800933 if (!audio_is_valid_format(input.config.format)) {
934 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700935 lStatus = BAD_VALUE;
936 goto Exit;
937 }
938
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 {
940 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800941 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800943 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 lStatus = BAD_VALUE;
945 goto Exit;
946 }
947
Eric Laurent21da6472017-11-09 16:29:26 -0800948 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949
Glenn Kastene848bd92014-03-13 15:00:32 -0700950 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800951 // check if an effect chain with the same session ID is present on another
952 // output thread and move it here.
953 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
954 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
955 if (mPlaybackThreads.keyAt(i) != output.outputId) {
956 uint32_t sessions = t->hasAudioSession(sessionId);
957 if (sessions & ThreadBase::EFFECT_SESSION) {
958 effectThread = t.get();
959 break;
Eric Laurentde070132010-07-13 04:45:46 -0700960 }
961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962 }
Eric Laurent21da6472017-11-09 16:29:26 -0800963 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964
Eric Laurent21da6472017-11-09 16:29:26 -0800965 output.sampleRate = input.config.sample_rate;
966 output.frameCount = input.frameCount;
967 output.notificationFrameCount = input.notificationFrameCount;
968 output.flags = input.flags;
Andy Hunga2159aa2021-07-20 13:01:52 -0700969 output.streamType = streamType;
Eric Laurent21da6472017-11-09 16:29:26 -0800970
Eric Laurent42984412019-05-09 17:57:03 -0700971 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700972 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800973 &output.frameCount, &output.notificationFrameCount,
974 input.notificationsPerBuffer, input.speed,
975 input.sharedBuffer, sessionId, &output.flags,
Svet Ganov33761132021-05-13 22:51:08 +0000976 callingPid, adjAttributionSource, input.clientInfo.clientTid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700977 &lStatus, portId, input.audioTrackCallback);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800978 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700979 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700980
Eric Laurent21da6472017-11-09 16:29:26 -0800981 output.afFrameCount = thread->frameCount();
982 output.afSampleRate = thread->sampleRate();
983 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800984 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800985
Kevin Rocard153f92d2018-12-18 18:33:28 -0800986 if (lStatus == NO_ERROR) {
987 // Connect secondary outputs. Failure on a secondary output must not imped the primary
988 // Any secondary output setup failure will lead to a desync between the AP and AF until
989 // the track is destroyed.
jiabinf042b9b2021-05-07 23:46:28 +0000990 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800991 }
992
Eric Laurent39e94f82010-07-28 01:32:47 -0700993 // move effect chain to this output thread if an effect on same session was waiting
994 // for a track to be created
995 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700996 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700997 Mutex::Autolock _dl(thread->mLock);
998 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700999 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
1000 effectThreadId = thread->id();
1001 effectIds = thread->getEffectIds_l(sessionId);
1002 }
Eric Laurent39e94f82010-07-28 01:32:47 -07001003 }
Eric Laurenta011e352012-03-29 15:51:43 -07001004
1005 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001006 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -08001007 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -07001008 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -07001009 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07001010 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -07001011 } else {
1012 mPendingSyncEvents[i]->cancel();
1013 }
Eric Laurenta011e352012-03-29 15:51:43 -07001014 mPendingSyncEvents.removeAt(i);
1015 i--;
1016 }
1017 }
1018 }
Andy Hung6eff0ff2021-07-30 19:01:48 -07001019 if ((output.flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
1020 setAudioHwSyncForSession_l(thread, sessionId);
1021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 }
Glenn Kastene198c362013-08-13 09:13:36 -07001023
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001024 if (lStatus != NO_ERROR) {
1025 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001026 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001027 // Don't hold mClientLock when releasing the reference on the track as the
1028 // destructor will acquire it.
1029 {
1030 Mutex::Autolock _cl(mClientLock);
1031 client.clear();
1032 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001034 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 }
1036
Eric Laurent6c796322019-04-09 14:13:17 -07001037 // effectThreadId is not NONE if an effect chain corresponding to the track session
1038 // was found on another thread and must be moved on this thread
1039 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1040 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1041 }
1042
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001043 output.audioTrack = new TrackHandle(track);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001044 _output = VALUE_OR_FATAL(output.toAidl());
1045
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001047 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001048 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001049 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001050 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051}
1052
Glenn Kasten2c073da2016-02-26 09:14:08 -08001053uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054{
1055 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001056 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001058 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001059 return 0;
1060 }
1061 return thread->sampleRate();
1062}
1063
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001064audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065{
1066 Mutex::Autolock _l(mLock);
1067 PlaybackThread *thread = checkPlaybackThread_l(output);
1068 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001069 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001070 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071 }
1072 return thread->format();
1073}
1074
Glenn Kasten2c073da2016-02-26 09:14:08 -08001075size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076{
1077 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001078 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001080 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 return 0;
1082 }
Glenn Kasten58912562012-04-03 10:45:00 -07001083 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1084 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 return thread->frameCount();
1086}
1087
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001088size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1089{
1090 Mutex::Autolock _l(mLock);
1091 ThreadBase *thread = checkThread_l(ioHandle);
1092 if (thread == NULL) {
1093 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1094 return 0;
1095 }
1096 return thread->frameCountHAL();
1097}
1098
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001099uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100{
1101 Mutex::Autolock _l(mLock);
1102 PlaybackThread *thread = checkPlaybackThread_l(output);
1103 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001104 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 return 0;
1106 }
1107 return thread->latency();
1108}
1109
1110status_t AudioFlinger::setMasterVolume(float value)
1111{
Eric Laurenta1884f92011-08-23 08:25:03 -07001112 status_t ret = initCheck();
1113 if (ret != NO_ERROR) {
1114 return ret;
1115 }
1116
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 // check calling permissions
1118 if (!settingsAllowed()) {
1119 return PERMISSION_DENIED;
1120 }
1121
Eric Laurenta4c5a552012-03-29 10:12:40 -07001122 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001123 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001124
John Grossmanee578c02012-07-23 17:05:46 -07001125 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001126 {
John Grossmanee578c02012-07-23 17:05:46 -07001127 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001128 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1129 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001130
Eric Laurent00abf0d2020-04-22 19:28:22 -07001131 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1132 if (dev->canSetMasterVolume()) {
1133 dev->hwDevice()->setMasterVolume(value);
1134 }
1135 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 }
John Grossmanee578c02012-07-23 17:05:46 -07001138 // Now set the master volume in each playback thread. Playback threads
1139 // assigned to HALs which do not have master volume support will apply
1140 // master volume during the mix operation. Threads with HALs which do
1141 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001142 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1143 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1144 continue;
1145 }
John Grossmanee578c02012-07-23 17:05:46 -07001146 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148
1149 return NO_ERROR;
1150}
1151
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001152status_t AudioFlinger::setMasterBalance(float balance)
1153{
1154 status_t ret = initCheck();
1155 if (ret != NO_ERROR) {
1156 return ret;
1157 }
1158
1159 // check calling permissions
1160 if (!settingsAllowed()) {
1161 return PERMISSION_DENIED;
1162 }
1163
1164 // check range
1165 if (isnan(balance) || fabs(balance) > 1.f) {
1166 return BAD_VALUE;
1167 }
1168
1169 Mutex::Autolock _l(mLock);
1170
1171 // short cut.
1172 if (mMasterBalance == balance) return NO_ERROR;
1173
1174 mMasterBalance = balance;
1175
1176 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1177 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1178 continue;
1179 }
1180 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1181 }
1182
1183 return NO_ERROR;
1184}
1185
Glenn Kastenf78aee72012-01-04 11:00:47 -08001186status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187{
Eric Laurenta1884f92011-08-23 08:25:03 -07001188 status_t ret = initCheck();
1189 if (ret != NO_ERROR) {
1190 return ret;
1191 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192
1193 // check calling permissions
1194 if (!settingsAllowed()) {
1195 return PERMISSION_DENIED;
1196 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001197 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001198 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 return BAD_VALUE;
1200 }
1201
1202 { // scope for the lock
1203 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001204 if (mPrimaryHardwareDev == nullptr) {
1205 return INVALID_OPERATION;
1206 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001207 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001209 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 mHardwareStatus = AUDIO_HW_IDLE;
1211 }
1212
1213 if (NO_ERROR == ret) {
1214 Mutex::Autolock _l(mLock);
1215 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001216 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001217 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 }
1219
Joey Poomarin52989982020-03-05 17:40:49 +08001220 mediametrics::LogItem(mMetricsId)
1221 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1222 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1223 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 return ret;
1225}
1226
1227status_t AudioFlinger::setMicMute(bool state)
1228{
Eric Laurenta1884f92011-08-23 08:25:03 -07001229 status_t ret = initCheck();
1230 if (ret != NO_ERROR) {
1231 return ret;
1232 }
1233
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 // check calling permissions
1235 if (!settingsAllowed()) {
1236 return PERMISSION_DENIED;
1237 }
1238
1239 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001240 if (mPrimaryHardwareDev == nullptr) {
1241 return INVALID_OPERATION;
1242 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001243 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1244 if (primaryDev == nullptr) {
1245 ALOGW("%s: no primary HAL device", __func__);
1246 return INVALID_OPERATION;
1247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001249 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001251 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001252 if (dev != primaryDev) {
1253 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001254 }
1255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001257 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258 return ret;
1259}
1260
1261bool AudioFlinger::getMicMute() const
1262{
Eric Laurenta1884f92011-08-23 08:25:03 -07001263 status_t ret = initCheck();
1264 if (ret != NO_ERROR) {
1265 return false;
1266 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001267 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001268 if (mPrimaryHardwareDev == nullptr) {
1269 return false;
1270 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001271 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1272 if (primaryDev == nullptr) {
1273 ALOGW("%s: no primary HAL device", __func__);
1274 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001275 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001276 bool state;
1277 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1278 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001280 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1281 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282}
1283
Eric Laurent5ada82e2019-08-29 17:53:54 -07001284void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001285{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001286 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001287
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001288 AutoMutex lock(mLock);
1289 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001290 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001291 }
1292 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001293 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001294 }
1295}
1296
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297status_t AudioFlinger::setMasterMute(bool muted)
1298{
John Grossmand8f178d2012-07-20 14:51:35 -07001299 status_t ret = initCheck();
1300 if (ret != NO_ERROR) {
1301 return ret;
1302 }
1303
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304 // check calling permissions
1305 if (!settingsAllowed()) {
1306 return PERMISSION_DENIED;
1307 }
1308
John Grossmanee578c02012-07-23 17:05:46 -07001309 Mutex::Autolock _l(mLock);
1310 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001311
John Grossmanee578c02012-07-23 17:05:46 -07001312 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001313 {
John Grossmanee578c02012-07-23 17:05:46 -07001314 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001315 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1316 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001317
Eric Laurent00abf0d2020-04-22 19:28:22 -07001318 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1319 if (dev->canSetMasterMute()) {
1320 dev->hwDevice()->setMasterMute(muted);
1321 }
1322 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001323 }
John Grossmand8f178d2012-07-20 14:51:35 -07001324 }
1325
John Grossmanee578c02012-07-23 17:05:46 -07001326 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001327 // assigned to HALs which do not have master mute support will apply master mute
1328 // during the mix operation. Threads with HALs which do support master mute
1329 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001330 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1331 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1332 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001333 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334
1335 return NO_ERROR;
1336}
1337
1338float AudioFlinger::masterVolume() const
1339{
Glenn Kasten98067102011-12-13 11:47:54 -08001340 Mutex::Autolock _l(mLock);
1341 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342}
1343
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001344status_t AudioFlinger::getMasterBalance(float *balance) const
1345{
1346 Mutex::Autolock _l(mLock);
1347 *balance = getMasterBalance_l();
1348 return NO_ERROR; // if called through binder, may return a transactional error
1349}
1350
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351bool AudioFlinger::masterMute() const
1352{
Glenn Kasten98067102011-12-13 11:47:54 -08001353 Mutex::Autolock _l(mLock);
1354 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355}
1356
John Grossman4ff14ba2012-02-08 16:37:41 -08001357float AudioFlinger::masterVolume_l() const
1358{
John Grossman4ff14ba2012-02-08 16:37:41 -08001359 return mMasterVolume;
1360}
1361
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001362float AudioFlinger::getMasterBalance_l() const
1363{
1364 return mMasterBalance;
1365}
1366
John Grossmand8f178d2012-07-20 14:51:35 -07001367bool AudioFlinger::masterMute_l() const
1368{
John Grossmanee578c02012-07-23 17:05:46 -07001369 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001370}
1371
Eric Laurent223fd5c2014-11-11 13:43:36 -08001372status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1373{
1374 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001375 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001376 return BAD_VALUE;
1377 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001378 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1379 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1380 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001381 return PERMISSION_DENIED;
1382 }
1383
1384 return NO_ERROR;
1385}
1386
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001387status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1388 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389{
1390 // check calling permissions
1391 if (!settingsAllowed()) {
1392 return PERMISSION_DENIED;
1393 }
1394
Eric Laurent223fd5c2014-11-11 13:43:36 -08001395 status_t status = checkStreamType(stream);
1396 if (status != NO_ERROR) {
1397 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001398 }
Eric Laurent98e38192018-02-15 18:31:53 -08001399 if (output == AUDIO_IO_HANDLE_NONE) {
1400 return BAD_VALUE;
1401 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001402 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1403 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001404
1405 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001406 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1407 if (volumeInterface == NULL) {
1408 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409 }
Eric Laurent98e38192018-02-15 18:31:53 -08001410 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411
1412 return NO_ERROR;
1413}
1414
Glenn Kastenfff6d712012-01-12 16:38:12 -08001415status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416{
1417 // check calling permissions
1418 if (!settingsAllowed()) {
1419 return PERMISSION_DENIED;
1420 }
1421
Eric Laurent223fd5c2014-11-11 13:43:36 -08001422 status_t status = checkStreamType(stream);
1423 if (status != NO_ERROR) {
1424 return status;
1425 }
1426 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1427
1428 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001429 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001430 return BAD_VALUE;
1431 }
1432
Eric Laurent93575202011-01-18 18:39:02 -08001433 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001435 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1436 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1437 volumeInterfaces[i]->setStreamMute(stream, muted);
1438 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439
1440 return NO_ERROR;
1441}
1442
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001443float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001445 status_t status = checkStreamType(stream);
1446 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447 return 0.0f;
1448 }
Eric Laurent98e38192018-02-15 18:31:53 -08001449 if (output == AUDIO_IO_HANDLE_NONE) {
1450 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451 }
1452
Eric Laurent98e38192018-02-15 18:31:53 -08001453 AutoMutex lock(mLock);
1454 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1455 if (volumeInterface == NULL) {
1456 return 0.0f;
1457 }
1458
1459 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460}
1461
Glenn Kastenfff6d712012-01-12 16:38:12 -08001462bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001464 status_t status = checkStreamType(stream);
1465 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 return true;
1467 }
1468
Glenn Kasten6637baa2012-01-09 09:40:36 -08001469 AutoMutex lock(mLock);
1470 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471}
1472
Eric Laurent054d9d32015-04-24 08:48:48 -07001473
Andy Hungd9ef4b12020-11-11 15:13:18 -08001474void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
Eric Laurent054d9d32015-04-24 08:48:48 -07001475{
1476 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1477 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1478 }
1479}
1480
jiabinc52b1ff2019-10-31 17:20:42 -07001481void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1482{
1483 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1484 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1485 }
1486}
1487
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001488// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1489void AudioFlinger::forwardParametersToDownstreamPatches_l(
1490 audio_io_handle_t upStream, const String8& keyValuePairs,
1491 std::function<bool(const sp<PlaybackThread>&)> useThread)
1492{
1493 std::vector<PatchPanel::SoftwarePatch> swPatches;
1494 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1495 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1496 __func__, swPatches.size(), upStream);
1497 for (const auto& swPatch : swPatches) {
1498 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1499 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1500 downStream->setParameters(keyValuePairs);
1501 }
1502 }
1503}
1504
Eric Laurent74c38dc2020-12-23 18:19:44 +01001505// Update downstream patches for all playback threads attached to an MSD module
1506void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
1507 const std::set<audio_io_handle_t> streams)
1508{
1509 for (const audio_io_handle_t stream : streams) {
1510 PlaybackThread *playbackThread = checkPlaybackThread_l(stream);
1511 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1512 continue;
1513 }
1514 playbackThread->setDownStreamPatch(patch);
1515 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1516 }
1517}
1518
Eric Laurentf1047e82018-04-16 19:18:20 -07001519// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1520// Some keys are used for audio routing and audio path configuration and should be reserved for use
1521// by audio policy and audio flinger for functional, privacy and security reasons.
1522void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1523{
1524 static const String8 kReservedParameters[] = {
1525 String8(AudioParameter::keyRouting),
1526 String8(AudioParameter::keySamplingRate),
1527 String8(AudioParameter::keyFormat),
1528 String8(AudioParameter::keyChannels),
1529 String8(AudioParameter::keyFrameCount),
1530 String8(AudioParameter::keyInputSource),
1531 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001532 String8(AudioParameter::keyDeviceConnect),
1533 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001534 String8(AudioParameter::keyStreamSupportedFormats),
1535 String8(AudioParameter::keyStreamSupportedChannels),
1536 String8(AudioParameter::keyStreamSupportedSamplingRates),
1537 };
1538
Andy Hung4ef19fa2018-05-15 19:35:29 -07001539 if (isAudioServerUid(callingUid)) {
1540 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001541 }
1542
1543 AudioParameter param = AudioParameter(keyValuePairs);
1544 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001545 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001546 for (auto& key : kReservedParameters) {
1547 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001548 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001549 param.remove(key);
1550 }
1551 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001552 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1553 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001554 keyValuePairs = param.toString();
1555}
1556
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001557void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1558 size_t rejectedKVPSize, const String8& rejectedKVPs,
1559 uid_t callingUid) {
1560 auto prefix = String8::format("UID %5d", callingUid);
1561 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1562 if (rejectedKVPSize != 0) {
1563 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1564 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1565 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1566 } else {
1567 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1568 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1569 }
1570}
1571
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001572status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573{
Eric Laurentf1047e82018-04-16 19:18:20 -07001574 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1575 ioHandle, keyValuePairs.string(),
1576 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001577
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 // check calling permissions
1579 if (!settingsAllowed()) {
1580 return PERMISSION_DENIED;
1581 }
1582
Eric Laurentf1047e82018-04-16 19:18:20 -07001583 String8 filteredKeyValuePairs = keyValuePairs;
1584 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1585
1586 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1587
Glenn Kasten142f5192014-03-25 17:44:59 -07001588 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1589 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001590 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001591 // result will remain NO_INIT if no audio device is present
1592 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001593 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001594 AutoMutex lock(mHardwareLock);
1595 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1596 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001597 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001598 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001599 // return success if at least one audio device accepts the parameters as not all
1600 // HALs are requested to support all parameters. If no audio device supports the
1601 // requested parameters, the last error is reported.
1602 if (final_result != NO_ERROR) {
1603 final_result = result;
1604 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001605 }
1606 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001607 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001608 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001609 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001610 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001611 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1612 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001613 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001614 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001615 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001616 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001617 }
1618 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001619 String8 screenState;
1620 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001621 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001622 if (isOff != (AudioFlinger::mScreenState & 1)) {
1623 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001624 }
1625 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001626 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 }
1628
1629 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1630 // and the thread is exited once the lock is released
1631 sp<ThreadBase> thread;
1632 {
1633 Mutex::Autolock _l(mLock);
1634 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001635 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001637 if (thread == 0) {
1638 thread = checkMmapThread_l(ioHandle);
1639 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001640 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001641 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001642 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001643 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001644 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1645 (value != 0)) {
Andy Hungd9ef4b12020-11-11 15:13:18 -08001646 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001647 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 }
1649 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001650 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001651 status_t result = thread->setParameters(filteredKeyValuePairs);
1652 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1653 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 }
1655 return BAD_VALUE;
1656}
1657
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001658String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001660 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1661 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662
Eric Laurenta4c5a552012-03-29 10:12:40 -07001663 Mutex::Autolock _l(mLock);
1664
Glenn Kasten142f5192014-03-25 17:44:59 -07001665 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001666 String8 out_s8;
1667
Eric Laurent00abf0d2020-04-22 19:28:22 -07001668 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001669 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001670 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001671 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001672 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07001673 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001674 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001675 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001676 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001677 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 }
1679
Eric Laurent6acd1d42017-01-04 14:23:29 -08001680 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1681 if (thread == NULL) {
1682 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1683 if (thread == NULL) {
1684 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1685 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001686 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001687 }
1688 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001690 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691}
1692
Glenn Kastendd8104c2012-07-02 12:42:44 -07001693size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1694 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695{
Eric Laurenta1884f92011-08-23 08:25:03 -07001696 status_t ret = initCheck();
1697 if (ret != NO_ERROR) {
1698 return 0;
1699 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001700 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001701 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001702 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001703 return 0;
1704 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001705
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001706 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001707 if (mPrimaryHardwareDev == nullptr) {
1708 return 0;
1709 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001710 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001711
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001712 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001713 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1714 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1715 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1716 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1717 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1718
1719 std::vector<audio_format_t> formats = {format};
1720 if (format != AUDIO_FORMAT_PCM_16_BIT)
1721 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1722
1723 std::vector<uint32_t> sampleRates = {sampleRate};
1724 static const uint32_t SR_44100 = 44100;
1725 static const uint32_t SR_48000 = 48000;
1726
1727 if (sampleRate != SR_48000)
1728 sampleRates.push_back(SR_48000);
1729 if (sampleRate != SR_44100)
1730 sampleRates.push_back(SR_44100);
1731
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001732 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001733
Robin Lee9899ff72019-12-24 22:02:08 +01001734 // Change parameters of the configuration each iteration until we find a
1735 // configuration that the device will support.
1736 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001737 for (auto testChannelMask : channelMasks) {
1738 config.channel_mask = testChannelMask;
1739 for (auto testFormat : formats) {
1740 config.format = testFormat;
1741 for (auto testSampleRate : sampleRates) {
1742 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001743
Judy Hsiaoabab5222019-11-09 18:14:58 +08001744 size_t bytes = 0;
1745 status_t result = dev->getInputBufferSize(&config, &bytes);
1746 if (result != OK || bytes == 0) {
1747 continue;
1748 }
1749
1750 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1751 config.format != format) {
1752 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1753 uint32_t srcChannelCount =
1754 audio_channel_count_from_in_mask(config.channel_mask);
1755 size_t srcFrames =
1756 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1757 size_t dstFrames = destinationFramesPossible(
1758 srcFrames, config.sample_rate, sampleRate);
1759 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1760 }
1761 return bytes;
1762 }
1763 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001764 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001765
1766 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1767 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1768 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769}
1770
Glenn Kasten5f972c02014-01-13 09:59:31 -08001771uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 Mutex::Autolock _l(mLock);
1774
1775 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1776 if (recordThread != NULL) {
1777 return recordThread->getInputFramesLost();
1778 }
1779 return 0;
1780}
1781
1782status_t AudioFlinger::setVoiceVolume(float value)
1783{
Eric Laurenta1884f92011-08-23 08:25:03 -07001784 status_t ret = initCheck();
1785 if (ret != NO_ERROR) {
1786 return ret;
1787 }
1788
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789 // check calling permissions
1790 if (!settingsAllowed()) {
1791 return PERMISSION_DENIED;
1792 }
1793
1794 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001795 if (mPrimaryHardwareDev == nullptr) {
1796 return INVALID_OPERATION;
1797 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001798 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001799 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001800 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 mHardwareStatus = AUDIO_HW_IDLE;
1802
Joey Poomarin52989982020-03-05 17:40:49 +08001803 mediametrics::LogItem(mMetricsId)
1804 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
1805 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
1806 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 return ret;
1808}
1809
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001810status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001811 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 Mutex::Autolock _l(mLock);
1814
1815 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1816 if (playbackThread != NULL) {
1817 return playbackThread->getRenderPosition(halFrames, dspFrames);
1818 }
1819
1820 return BAD_VALUE;
1821}
1822
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001823void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001826 if (client == 0) {
1827 return;
1828 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001829 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001830 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001831 {
1832 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001833 if (mNotificationClients.indexOfKey(pid) < 0) {
1834 sp<NotificationClient> notificationClient = new NotificationClient(this,
1835 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001836 pid,
1837 uid);
1838 ALOGV("registerClient() client %p, pid %d, uid %u",
1839 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840
Eric Laurent021cf962014-05-13 10:18:14 -07001841 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842
Marco Nelissen06b46062014-11-14 07:58:25 -08001843 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001844 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001845 }
1846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847
Eric Laurent021cf962014-05-13 10:18:14 -07001848 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001849 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001850 // the config change is always sent from playback or record threads to avoid deadlock
1851 // with AudioSystem::gLock
1852 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001853 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001854 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001856 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001857 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 }
1859}
1860
1861void AudioFlinger::removeNotificationClient(pid_t pid)
1862{
Eric Laurent6c796322019-04-09 14:13:17 -07001863 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001864 {
Eric Laurent6c796322019-04-09 14:13:17 -07001865 Mutex::Autolock _l(mLock);
1866 {
1867 Mutex::Autolock _cl(mClientLock);
1868 mNotificationClients.removeItem(pid);
1869 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001870
Eric Laurent6c796322019-04-09 14:13:17 -07001871 ALOGV("%d died, releasing its sessions", pid);
1872 size_t num = mAudioSessionRefs.size();
1873 bool removed = false;
1874 for (size_t i = 0; i < num; ) {
1875 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1876 ALOGV(" pid %d @ %zu", ref->mPid, i);
1877 if (ref->mPid == pid) {
1878 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1879 mAudioSessionRefs.removeAt(i);
1880 delete ref;
1881 removed = true;
1882 num--;
1883 } else {
1884 i++;
1885 }
1886 }
1887 if (removed) {
1888 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001889 }
1890 }
Eric Laurent6c796322019-04-09 14:13:17 -07001891 for (auto& effect : removedEffects) {
1892 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894}
1895
Eric Laurent73e26b62015-04-27 16:55:58 -07001896void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001897 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001898 pid_t pid) {
1899 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
1900 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
1901 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
1902 legacy2aidl_audio_io_config_event_AudioIoConfigEvent(event));
1903
Eric Laurent021cf962014-05-13 10:18:14 -07001904 Mutex::Autolock _l(mClientLock);
1905 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001907 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001908 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(eventAidl,
1909 descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911 }
1912}
1913
Eric Laurent021cf962014-05-13 10:18:14 -07001914// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915void AudioFlinger::removeClient_l(pid_t pid)
1916{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001917 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001918 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 mClients.removeItem(pid);
1920}
1921
Eric Laurent717e1282012-06-29 16:36:52 -07001922// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001923sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1924 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001925{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001926 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001927
1928 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001929 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001930 ALOG_ASSERT(thread == 0);
1931 thread = mPlaybackThreads.valueAt(i);
1932 }
1933 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001934 if (thread != nullptr) {
1935 return thread;
1936 }
1937 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1938 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1939 ALOG_ASSERT(thread == 0);
1940 thread = mRecordThreads.valueAt(i);
1941 }
1942 }
1943 if (thread != nullptr) {
1944 return thread;
1945 }
1946 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1947 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1948 ALOG_ASSERT(thread == 0);
1949 thread = mMmapThreads.valueAt(i);
1950 }
1951 }
Eric Laurent717e1282012-06-29 16:36:52 -07001952 return thread;
1953}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956
1957// ----------------------------------------------------------------------------
1958
1959AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1960 : RefBase(),
1961 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001962 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963{
Andy Hung6f248bb2018-01-23 14:04:37 -08001964 mMemoryDealer = new MemoryDealer(
1965 audioFlinger->getClientSharedHeapSize(),
1966 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967}
1968
Eric Laurent021cf962014-05-13 10:18:14 -07001969// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970AudioFlinger::Client::~Client()
1971{
1972 mAudioFlinger->removeClient_l(mPid);
1973}
1974
Glenn Kasten435dbe62012-01-30 10:15:48 -08001975sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976{
1977 return mMemoryDealer;
1978}
1979
1980// ----------------------------------------------------------------------------
1981
1982AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001983 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001984 pid_t pid,
1985 uid_t uid)
1986 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987{
1988}
1989
1990AudioFlinger::NotificationClient::~NotificationClient()
1991{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992}
1993
Glenn Kasten0f11b512014-01-31 16:18:54 -08001994void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995{
1996 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001997 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998}
1999
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002000// ----------------------------------------------------------------------------
2001AudioFlinger::MediaLogNotifier::MediaLogNotifier()
2002 : mPendingRequests(false) {}
2003
2004
2005void AudioFlinger::MediaLogNotifier::requestMerge() {
2006 AutoMutex _l(mMutex);
2007 mPendingRequests = true;
2008 mCond.signal();
2009}
2010
2011bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002012 // Should already have been checked, but just in case
2013 if (sMediaLogService == 0) {
2014 return false;
2015 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002016 // Wait until there are pending requests
2017 {
2018 AutoMutex _l(mMutex);
2019 mPendingRequests = false; // to ignore past requests
2020 while (!mPendingRequests) {
2021 mCond.wait(mMutex);
2022 // TODO may also need an exitPending check
2023 }
2024 mPendingRequests = false;
2025 }
2026 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002027 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002028 usleep(kPostTriggerSleepPeriod);
2029 return true;
2030}
2031
2032void AudioFlinger::requestLogMerge() {
2033 mMediaLogNotifier->requestMerge();
2034}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035
2036// ----------------------------------------------------------------------------
2037
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002038status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2039 media::CreateRecordResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040{
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002041 CreateRecordInput input = VALUE_OR_RETURN_STATUS(CreateRecordInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002042 CreateRecordOutput output;
2043
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 sp<RecordThread::RecordTrack> recordTrack;
2045 sp<RecordHandle> recordHandle;
2046 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002048 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002049 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050
Eric Laurentf14db3c2017-12-08 14:20:36 -08002051 output.cblk.clear();
2052 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002053 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002054
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002055 // TODO b/182392553: refactor or clean up
Svet Ganov33761132021-05-13 22:51:08 +00002056 AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource;
2057 bool updatePid = (adjAttributionSource.pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002058 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Svet Ganov33761132021-05-13 22:51:08 +00002059 const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(
2060 adjAttributionSource.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -07002061 if (!isAudioServerOrMediaServerUid(callingUid)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002062 ALOGW_IF(currentUid != callingUid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002063 "%s uid %d tried to pass itself off as %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002064 __FUNCTION__, callingUid, currentUid);
Svet Ganov33761132021-05-13 22:51:08 +00002065 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002066 updatePid = true;
2067 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07002068 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Svet Ganov33761132021-05-13 22:51:08 +00002069 const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
2070 adjAttributionSource.pid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002071 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002072 ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002073 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002074 __func__, callingUid, callingPid, currentPid);
Svet Ganov33761132021-05-13 22:51:08 +00002075 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Marco Nelissendcb346b2015-09-09 10:47:29 -07002076 }
2077
Andy Hung6770c6f2015-04-07 13:43:36 -07002078 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08002079 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2080 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002081 lStatus = BAD_VALUE;
2082 goto Exit;
2083 }
2084
Glenn Kasten53b5d092014-02-05 10:00:23 -08002085 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002086 if (!audio_is_input_channel(input.config.channel_mask)) {
2087 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002088 lStatus = BAD_VALUE;
2089 goto Exit;
2090 }
2091
Eric Laurentf14db3c2017-12-08 14:20:36 -08002092 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2093 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2094 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2095 lStatus = BAD_VALUE;
2096 goto Exit;
2097 }
2098
2099 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002100 output.selectedDeviceId = input.selectedDeviceId;
2101 output.flags = input.flags;
2102
Svet Ganov33761132021-05-13 22:51:08 +00002103 client = registerPid(VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid)));
Eric Laurentf14db3c2017-12-08 14:20:36 -08002104
2105 // Not a conventional loop, but a retry loop for at most two iterations total.
2106 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2107 // Exits loop via break on no error of got exit on error
2108 // The sp<> references will be dropped when re-entering scope.
2109 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2110 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002111 // release previously opened input if retrying.
2112 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2113 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002114 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002115 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002116 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002117 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002118 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002119 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002120 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002121 sessionId,
2122 // FIXME compare to AudioTrack
Svet Ganov33761132021-05-13 22:51:08 +00002123 adjAttributionSource,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002124 &input.config,
2125 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002126 if (lStatus != NO_ERROR) {
2127 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2128 goto Exit;
2129 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002130
Glenn Kasten05997e22014-03-13 15:08:33 -07002131 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002133 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002135 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2136 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 goto Exit;
2138 }
2139
Eric Laurentf14db3c2017-12-08 14:20:36 -08002140 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141
Eric Laurentf14db3c2017-12-08 14:20:36 -08002142 output.sampleRate = input.config.sample_rate;
2143 output.frameCount = input.frameCount;
2144 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002145
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002146 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002147 input.config.format, input.config.channel_mask,
2148 &output.frameCount, sessionId,
2149 &output.notificationFrameCount,
Svet Ganov33761132021-05-13 22:51:08 +00002150 callingPid, adjAttributionSource, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002151 input.clientInfo.clientTid,
Eric Laurentec376dc2021-04-08 20:41:22 +02002152 &lStatus, portId, input.maxSharedAudioHistoryMs);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002153 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002154
Eric Laurentf14db3c2017-12-08 14:20:36 -08002155 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2156 // audio policy manager without FAST constraint
2157 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002158 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002159 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002160
2161 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002162 goto Exit;
2163 }
2164
2165 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2166 // session and move it to this thread.
2167 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2168 if (chain != 0) {
2169 Mutex::Autolock _l(thread->mLock);
2170 thread->addEffectChain_l(chain);
2171 }
2172 break;
2173 }
2174 // End of retry loop.
2175 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 }
Glenn Kastene198c362013-08-13 09:13:36 -07002177
Eric Laurentf14db3c2017-12-08 14:20:36 -08002178 output.cblk = recordTrack->getCblk();
2179 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002180 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002181
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002182 output.audioRecord = new RecordHandle(recordTrack);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002183 _output = VALUE_OR_FATAL(output.toAidl());
2184
Eric Laurentf14db3c2017-12-08 14:20:36 -08002185Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002186 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002187 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002188 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002189 // Don't hold mClientLock when releasing the reference on the track as the
2190 // destructor will acquire it.
2191 {
2192 Mutex::Autolock _cl(mClientLock);
2193 client.clear();
2194 }
Eric Laurent896c9672017-12-08 14:08:45 -08002195 recordTrack.clear();
2196 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002197 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 }
2200
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002201 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202}
2203
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002204
2205
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206// ----------------------------------------------------------------------------
2207
Eric Laurenta4c5a552012-03-29 10:12:40 -07002208audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2209{
Eric Laurent44622db2014-08-01 19:00:33 -07002210 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002211 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002212 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002213 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002214 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002215 }
2216 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002217 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002218 return loadHwModule_l(name);
2219}
2220
Eric Laurent00abf0d2020-04-22 19:28:22 -07002221// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002222audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2223{
2224 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2225 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2226 ALOGW("loadHwModule() module %s already loaded", name);
2227 return mAudioHwDevs.keyAt(i);
2228 }
2229 }
2230
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002231 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002232
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002233 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002234 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002235 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002236 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002237 }
2238
2239 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002240 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002241 mHardwareStatus = AUDIO_HW_IDLE;
2242 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002243 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002244 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002245 }
2246
John Grossmanee578c02012-07-23 17:05:46 -07002247 // Check and cache this HAL's level of support for master mute and master
2248 // volume. If this is the first HAL opened, and it supports the get
2249 // methods, use the initial values provided by the HAL as the current
2250 // master mute and volume settings.
2251
2252 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002253 if (0 == mAudioHwDevs.size()) {
2254 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2255 float mv;
2256 if (OK == dev->getMasterVolume(&mv)) {
2257 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002258 }
2259
Eric Laurent00abf0d2020-04-22 19:28:22 -07002260 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2261 bool mm;
2262 if (OK == dev->getMasterMute(&mm)) {
2263 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002264 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002265 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002266
2267 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2268 if (OK == dev->setMasterVolume(mMasterVolume)) {
2269 flags = static_cast<AudioHwDevice::Flags>(flags |
2270 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2271 }
2272
2273 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2274 if (OK == dev->setMasterMute(mMasterMute)) {
2275 flags = static_cast<AudioHwDevice::Flags>(flags |
2276 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2277 }
2278
2279 mHardwareStatus = AUDIO_HW_IDLE;
2280
Mikhail Naganov97373b02018-07-23 13:27:24 -07002281 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002282 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2283 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2284 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002285
Glenn Kastena13cde92016-03-28 15:26:02 -07002286 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002287 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2288 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2289 mPrimaryHardwareDev = audioDevice;
2290 mHardwareStatus = AUDIO_HW_SET_MODE;
2291 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2292 mHardwareStatus = AUDIO_HW_IDLE;
2293 }
2294
2295 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002296
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002297 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002298
2299 return handle;
2300
2301}
2302
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002303// ----------------------------------------------------------------------------
2304
Glenn Kasten3b16c762012-11-14 08:44:39 -08002305uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002306{
2307 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002308 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002309 return thread != NULL ? thread->sampleRate() : 0;
2310}
2311
Glenn Kastene33054e2012-11-14 12:54:39 -08002312size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002313{
2314 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002315 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002316 return thread != NULL ? thread->frameCountHAL() : 0;
2317}
2318
2319// ----------------------------------------------------------------------------
2320
Andy Hung6f248bb2018-01-23 14:04:37 -08002321status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002322{
2323 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002324 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002325 return PERMISSION_DENIED;
2326 }
2327 Mutex::Autolock _l(mLock);
2328 if (mIsDeviceTypeKnown) {
2329 return INVALID_OPERATION;
2330 }
2331 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002332 mTotalMemory = totalMemory;
2333 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2334 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2335 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2336 // though actual setting is determined through device configuration.
2337 constexpr int64_t GB = 1024 * 1024 * 1024;
2338 mClientSharedHeapSize =
2339 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2340 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2341 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2342 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2343 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002344 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002345
2346 // TODO: Cache the client shared heap size in a persistent property.
2347 // It's possible that a native process or Java service or app accesses audioserver
2348 // after it is registered by system server, but before AudioService updates
2349 // the memory info. This would occur immediately after boot or an audioserver
2350 // crash and restore. Before update from AudioService, the client would get the
2351 // minimum heap size.
2352
2353 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2354 (isLowRamDevice ? "true" : "false"),
2355 (long long)mTotalMemory,
2356 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002357 return NO_ERROR;
2358}
2359
Andy Hung6f248bb2018-01-23 14:04:37 -08002360size_t AudioFlinger::getClientSharedHeapSize() const
2361{
2362 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2363 if (heapSizeInBytes != 0) { // read-only property overrides all.
2364 return heapSizeInBytes;
2365 }
2366 return mClientSharedHeapSize;
2367}
2368
Mikhail Naganovdea53042018-04-26 13:10:21 -07002369status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2370{
2371 ALOGV(__func__);
2372
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08002373 status_t status = AudioValidator::validateAudioPortConfig(*config);
2374 if (status != NO_ERROR) {
2375 return status;
2376 }
2377
Mikhail Naganovdea53042018-04-26 13:10:21 -07002378 audio_module_handle_t module;
2379 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2380 module = config->ext.device.hw_module;
2381 } else {
2382 module = config->ext.mix.hw_module;
2383 }
2384
2385 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002386 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002387 ssize_t index = mAudioHwDevs.indexOfKey(module);
2388 if (index < 0) {
2389 ALOGW("%s() bad hw module %d", __func__, module);
2390 return BAD_VALUE;
2391 }
2392
2393 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2394 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2395}
2396
Eric Laurent93c3d412014-08-01 14:48:35 -07002397audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2398{
2399 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002400
2401 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2402 if (index >= 0) {
2403 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2404 mHwAvSyncIds.valueAt(index), sessionId);
2405 return mHwAvSyncIds.valueAt(index);
2406 }
2407
Eric Laurent00abf0d2020-04-22 19:28:22 -07002408 sp<DeviceHalInterface> dev;
2409 {
2410 AutoMutex lock(mHardwareLock);
2411 if (mPrimaryHardwareDev == nullptr) {
2412 return AUDIO_HW_SYNC_INVALID;
2413 }
2414 dev = mPrimaryHardwareDev->hwDevice();
2415 }
2416 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002417 return AUDIO_HW_SYNC_INVALID;
2418 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002419 String8 reply;
2420 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002421 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002422 param = AudioParameter(reply);
2423 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002424
2425 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002426 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002427 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2428 return AUDIO_HW_SYNC_INVALID;
2429 }
2430
2431 // allow only one session for a given HW A/V sync ID.
2432 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2433 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2434 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2435 value, mHwAvSyncIds.keyAt(i));
2436 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002437 break;
2438 }
2439 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002440
2441 mHwAvSyncIds.add(sessionId, value);
2442
2443 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2444 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2445 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002446 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002447 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002448 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002449 String8 keyValuePairs = param.toString();
2450 thread->setParameters(keyValuePairs);
2451 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2452 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002453 break;
2454 }
2455 }
2456
2457 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2458 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002459}
2460
Eric Laurent72e3f392015-05-20 14:43:50 -07002461status_t AudioFlinger::systemReady()
2462{
2463 Mutex::Autolock _l(mLock);
2464 ALOGI("%s", __FUNCTION__);
2465 if (mSystemReady) {
2466 ALOGW("%s called twice", __FUNCTION__);
2467 return NO_ERROR;
2468 }
2469 mSystemReady = true;
2470 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2471 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2472 thread->systemReady();
2473 }
2474 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2475 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2476 thread->systemReady();
2477 }
Eric Laurent39934ea2021-07-13 13:35:32 +02002478 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2479 ThreadBase *thread = (ThreadBase *)mMmapThreads.valueAt(i).get();
2480 thread->systemReady();
2481 }
Eric Laurent72e3f392015-05-20 14:43:50 -07002482 return NO_ERROR;
2483}
2484
jiabin46a76fa2018-01-05 10:18:21 -08002485status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2486{
jiabin9ff780e2018-03-19 18:19:52 -07002487 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002488 status_t status = INVALID_OPERATION;
2489
2490 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2491 std::vector<media::MicrophoneInfo> mics;
2492 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2493 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2494 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2495 mHardwareStatus = AUDIO_HW_IDLE;
2496 if (devStatus == NO_ERROR) {
2497 microphones->insert(microphones->begin(), mics.begin(), mics.end());
2498 // report success if at least one HW module supports the function.
2499 status = NO_ERROR;
2500 }
2501 }
2502
jiabin9ff780e2018-03-19 18:19:52 -07002503 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002504}
2505
Eric Laurentfa90e842014-10-17 18:12:31 -07002506// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2507void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2508{
2509 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2510 if (index >= 0) {
2511 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2512 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2513 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002514 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002515 String8 keyValuePairs = param.toString();
2516 thread->setParameters(keyValuePairs);
2517 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2518 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002519 }
2520}
2521
2522
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002523// ----------------------------------------------------------------------------
2524
Eric Laurent83b88082014-06-20 18:31:16 -07002525
Eric Laurent6acd1d42017-01-04 14:23:29 -08002526sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002527 audio_io_handle_t *output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002528 audio_config_t *halConfig,
2529 audio_config_base_t *mixerConfig __unused,
jiabin43810402019-10-24 14:58:31 -07002530 audio_devices_t deviceType,
2531 const String8& address,
2532 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002533{
jiabin43810402019-10-24 14:58:31 -07002534 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002535 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002536 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002537 }
2538
Eric Laurentcf2c0212014-07-25 16:20:43 -07002539 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002540 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2541 } else {
2542 // Audio Policy does not currently request a specific output handle.
2543 // If this is ever needed, see openInput_l() for example code.
2544 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2545 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002546 }
Eric Laurent83b88082014-06-20 18:31:16 -07002547
2548 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2549
Eric Laurent83b88082014-06-20 18:31:16 -07002550 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002551 // This if statement allows overriding the audio policy settings
2552 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2553 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2554 // Check only for Normal Mixing mode
2555 if (kEnableExtendedPrecision) {
2556 // Specify format (uncomment one below to choose)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002557 //halConfig->format = AUDIO_FORMAT_PCM_FLOAT;
2558 //halConfig->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2559 //halConfig->format = AUDIO_FORMAT_PCM_32_BIT;
2560 //halConfig->format = AUDIO_FORMAT_PCM_8_24_BIT;
2561 // ALOGV("openOutput_l() upgrading format to %#08x", halConfig->format);
Andy Hung9a592762014-07-21 21:56:01 -07002562 }
2563 if (kEnableExtendedChannels) {
2564 // Specify channel mask (uncomment one below to choose)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002565 //halConfig->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2566 //halConfig->channel_mask = audio_channel_mask_from_representation_and_bits(
Andy Hung9a592762014-07-21 21:56:01 -07002567 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2568 }
Eric Laurent83b88082014-06-20 18:31:16 -07002569 }
2570
Phil Burk062e67a2015-02-11 13:40:50 -08002571 AudioStreamOut *outputStream = NULL;
2572 status_t status = outHwDev->openOutputStream(
2573 &outputStream,
2574 *output,
jiabin43810402019-10-24 14:58:31 -07002575 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002576 flags,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002577 halConfig,
Phil Burk062e67a2015-02-11 13:40:50 -08002578 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002579
2580 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002581
Phil Burk062e67a2015-02-11 13:40:50 -08002582 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2584 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002585 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002586 mMmapThreads.add(*output, thread);
2587 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2588 *output, thread.get());
2589 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002590 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002591 sp<PlaybackThread> thread;
Eric Laurentfa0f6742021-08-17 18:39:44 +02002592 //TODO: b/193496180 use spatializer flag at audio HAL when available
Eric Laurentb3f315a2021-07-13 15:09:05 +02002593 if (flags == (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_FAST
2594 | AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) {
Eric Laurent0dccd2e2021-10-26 17:40:18 +02002595#ifdef MULTICHANNEL_EFFECT_CHAIN
Eric Laurentfa0f6742021-08-17 18:39:44 +02002596 thread = new SpatializerThread(this, outputStream, *output,
Eric Laurentb3f315a2021-07-13 15:09:05 +02002597 mSystemReady, mixerConfig);
Eric Laurent0dccd2e2021-10-26 17:40:18 +02002598 ALOGD("openOutput_l() created spatializer output: ID %d thread %p",
Eric Laurentb3f315a2021-07-13 15:09:05 +02002599 *output, thread.get());
Eric Laurent0dccd2e2021-10-26 17:40:18 +02002600#else
2601 ALOGE("openOutput_l() cannot create spatializer thread "
2602 "without #define MULTICHANNEL_EFFECT_CHAIN");
2603#endif
Eric Laurentb3f315a2021-07-13 15:09:05 +02002604 } else if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002605 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002606 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2607 *output, thread.get());
2608 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002609 || !isValidPcmSinkFormat(halConfig->format)
2610 || !isValidPcmSinkChannelMask(halConfig->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002611 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002612 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2613 *output, thread.get());
2614 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002615 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002616 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2617 *output, thread.get());
2618 }
2619 mPlaybackThreads.add(*output, thread);
Eric Laurent74c38dc2020-12-23 18:19:44 +01002620 struct audio_patch patch;
2621 mPatchPanel.notifyStreamOpened(outHwDev, *output, &patch);
2622 if (thread->isMsdDevice()) {
2623 thread->setDownStreamPatch(&patch);
2624 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002625 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002626 }
Eric Laurent83b88082014-06-20 18:31:16 -07002627 }
2628
2629 return 0;
2630}
2631
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002632status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request,
2633 media::OpenOutputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634{
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002635 audio_module_handle_t module = VALUE_OR_RETURN_STATUS(
2636 aidl2legacy_int32_t_audio_module_handle_t(request.module));
Eric Laurentf1f22e72021-07-13 14:04:14 +02002637 audio_config_t halConfig = VALUE_OR_RETURN_STATUS(
2638 aidl2legacy_AudioConfig_audio_config_t(request.halConfig));
2639 audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS(
2640 aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002641 sp<DeviceDescriptorBase> device = VALUE_OR_RETURN_STATUS(
2642 aidl2legacy_DeviceDescriptorBase(request.device));
2643 audio_output_flags_t flags = VALUE_OR_RETURN_STATUS(
Andy Hung973638a2020-12-08 20:47:45 -08002644 aidl2legacy_int32_t_audio_output_flags_t_mask(request.flags));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002645
2646 audio_io_handle_t output;
2647 uint32_t latencyMs;
2648
jiabin43810402019-10-24 14:58:31 -07002649 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002650 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002651 this, module,
jiabin43810402019-10-24 14:58:31 -07002652 device->toString().c_str(),
Eric Laurentf1f22e72021-07-13 14:04:14 +02002653 halConfig.sample_rate,
2654 halConfig.format,
2655 halConfig.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002656 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
jiabin43810402019-10-24 14:58:31 -07002658 audio_devices_t deviceType = device->type();
2659 const String8 address = String8(device->address().c_str());
2660
2661 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002662 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002664
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665 Mutex::Autolock _l(mLock);
2666
Eric Laurentf1f22e72021-07-13 14:04:14 +02002667 sp<ThreadBase> thread = openOutput_l(module, &output, &halConfig,
2668 &mixerConfig, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002669 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002670 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2671 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002672 latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002673
Eric Laurent6acd1d42017-01-04 14:23:29 -08002674 // notify client processes of the new output creation
2675 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002676
Eric Laurent00abf0d2020-04-22 19:28:22 -07002677 // the first primary output opened designates the primary hw device if no HW module
2678 // named "primary" was already loaded.
2679 AutoMutex lock(mHardwareLock);
2680 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002681 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002682 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002683
Eric Laurent6acd1d42017-01-04 14:23:29 -08002684 mHardwareStatus = AUDIO_HW_SET_MODE;
2685 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2686 mHardwareStatus = AUDIO_HW_IDLE;
2687 }
2688 } else {
2689 MmapThread *mmapThread = (MmapThread *)thread.get();
2690 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002691 }
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002692 response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output));
Eric Laurentf1f22e72021-07-13 14:04:14 +02002693 response->config =
2694 VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(halConfig));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002695 response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(latencyMs));
Andy Hung973638a2020-12-08 20:47:45 -08002696 response->flags = VALUE_OR_RETURN_STATUS(
2697 legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
Eric Laurentcf2c0212014-07-25 16:20:43 -07002698 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699 }
2700
Eric Laurentcf2c0212014-07-25 16:20:43 -07002701 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702}
2703
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002704audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2705 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706{
2707 Mutex::Autolock _l(mLock);
2708 MixerThread *thread1 = checkMixerThread_l(output1);
2709 MixerThread *thread2 = checkMixerThread_l(output2);
2710
2711 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002712 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2713 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002714 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 }
2716
Glenn Kasteneeecb982016-02-26 10:44:04 -08002717 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002718 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 thread->addOutputTrack(thread2);
2720 mPlaybackThreads.add(id, thread);
2721 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002722 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 return id;
2724}
2725
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002726status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727{
Glenn Kastend96c5722012-04-25 13:44:49 -07002728 return closeOutput_nonvirtual(output);
2729}
2730
2731status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2732{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 // keep strong reference on the playback thread so that
2734 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002735 sp<PlaybackThread> playbackThread;
2736 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737 {
2738 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002739 playbackThread = checkPlaybackThread_l(output);
2740 if (playbackThread != NULL) {
2741 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742
Andy Hungdc099c22018-09-18 13:46:39 -07002743 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002744
Eric Laurent6acd1d42017-01-04 14:23:29 -08002745 if (playbackThread->type() == ThreadBase::MIXER) {
2746 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2747 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2748 DuplicatingThread *dupThread =
2749 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2750 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2751 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002752 }
2753 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754
2755
Eric Laurent6acd1d42017-01-04 14:23:29 -08002756 mPlaybackThreads.removeItem(output);
2757 // save all effects to the default thread
2758 if (mPlaybackThreads.size()) {
2759 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2760 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002761 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002762 Mutex::Autolock _dl(dstThread->mLock);
2763 Mutex::Autolock _sl(playbackThread->mLock);
2764 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2765 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002766 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002767 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002768 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769 }
2770 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002771 } else {
2772 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2773 if (mmapThread == 0) {
2774 return BAD_VALUE;
2775 }
Andy Hungdc099c22018-09-18 13:46:39 -07002776 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002777 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002778 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002780 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2781 ioDesc->mIoHandle = output;
2782 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002783 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002785 // The thread entity (active unit of execution) is no longer running here,
2786 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787
Eric Laurent6acd1d42017-01-04 14:23:29 -08002788 if (playbackThread != 0) {
2789 playbackThread->exit();
2790 if (!playbackThread->isDuplicating()) {
2791 closeOutputFinish(playbackThread);
2792 }
2793 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002794 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002795 mmapThread->exit();
2796 AudioStreamOut *out = mmapThread->clearOutput();
2797 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2798 // from now on thread->mOutput is NULL
2799 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 }
2801 return NO_ERROR;
2802}
2803
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002804void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002805{
2806 AudioStreamOut *out = thread->clearOutput();
2807 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2808 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002809 delete out;
2810}
2811
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002812void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002813{
2814 mPlaybackThreads.removeItem(thread->mId);
2815 thread->exit();
2816 closeOutputFinish(thread);
2817}
2818
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002819status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820{
2821 Mutex::Autolock _l(mLock);
2822 PlaybackThread *thread = checkPlaybackThread_l(output);
2823
2824 if (thread == NULL) {
2825 return BAD_VALUE;
2826 }
2827
Steve Block3856b092011-10-20 11:56:00 +01002828 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 thread->suspend();
2830
2831 return NO_ERROR;
2832}
2833
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002834status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835{
2836 Mutex::Autolock _l(mLock);
2837 PlaybackThread *thread = checkPlaybackThread_l(output);
2838
2839 if (thread == NULL) {
2840 return BAD_VALUE;
2841 }
2842
Steve Block3856b092011-10-20 11:56:00 +01002843 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844
2845 thread->restore();
2846
2847 return NO_ERROR;
2848}
2849
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002850status_t AudioFlinger::openInput(const media::OpenInputRequest& request,
2851 media::OpenInputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852{
Eric Laurent83b88082014-06-20 18:31:16 -07002853 Mutex::Autolock _l(mLock);
2854
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002855 if (request.device.type == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002856 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002857 }
2858
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002859 audio_io_handle_t input = VALUE_OR_RETURN_STATUS(
2860 aidl2legacy_int32_t_audio_io_handle_t(request.input));
2861 audio_config_t config = VALUE_OR_RETURN_STATUS(
2862 aidl2legacy_AudioConfig_audio_config_t(request.config));
2863 AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
2864 aidl2legacy_AudioDeviceTypeAddress(request.device));
2865
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002866 sp<ThreadBase> thread = openInput_l(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002867 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)),
2868 &input,
2869 &config,
2870 device.mType,
2871 device.address().c_str(),
2872 VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSourceType_audio_source_t(request.source)),
Andy Hung973638a2020-12-08 20:47:45 -08002873 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)),
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002874 AUDIO_DEVICE_NONE,
2875 String8{});
2876
2877 response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
2878 response->config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config));
2879 response->device = request.device;
Eric Laurent83b88082014-06-20 18:31:16 -07002880
2881 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002882 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002883 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002884 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002886 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002887}
Dima Zavin799a70e2011-04-18 16:57:27 -07002888
Eric Laurent6acd1d42017-01-04 14:23:29 -08002889sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002890 audio_io_handle_t *input,
2891 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002892 audio_devices_t devices,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002893 const char* address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002894 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002895 audio_input_flags_t flags,
2896 audio_devices_t outputDevice,
2897 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002898{
Glenn Kastene7d66712015-03-05 13:46:52 -08002899 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002900 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002901 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002902 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002903 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002904
Glenn Kasteneeecb982016-02-26 10:44:04 -08002905 // Audio Policy can request a specific handle for hardware hotword.
2906 // The goal here is not to re-open an already opened input.
2907 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002908 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002909 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2910 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2911 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2912 return 0;
2913 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2914 // This should not happen in a transient state with current design.
2915 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2916 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002917 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002918
Eric Laurentcf2c0212014-07-25 16:20:43 -07002919 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002920 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002921 sp<StreamInHalInterface> inStream;
2922 status_t status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002923 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002924 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002925 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2926 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002927 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002928 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002929 halconfig.sample_rate,
2930 halconfig.format,
2931 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002932 flags,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002933 status, address);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002935 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002936 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002937 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002938 audio_is_linear_pcm(config->format) &&
2939 audio_is_linear_pcm(halconfig.format) &&
2940 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
Andy Hung936845a2021-06-08 00:09:06 -07002941 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_LIMIT) &&
2942 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_LIMIT)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002943 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002944 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002945 inStream.clear();
2946 status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002947 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002948 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002949 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950 }
2951
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002952 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002953 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002954 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2955 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002956 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002957 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002958 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2959 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002960 return thread;
2961 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002962 // Start record thread
2963 // RecordThread requires both input and output device indication to forward to audio
2964 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002965 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002966 mRecordThreads.add(*input, thread);
2967 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2968 return thread;
2969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 }
2971
Eric Laurentcf2c0212014-07-25 16:20:43 -07002972 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 return 0;
2974}
2975
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002976status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977{
Glenn Kastend96c5722012-04-25 13:44:49 -07002978 return closeInput_nonvirtual(input);
2979}
2980
2981status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2982{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983 // keep strong reference on the record thread so that
2984 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002985 sp<RecordThread> recordThread;
2986 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987 {
2988 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002989 recordThread = checkRecordThread_l(input);
2990 if (recordThread != 0) {
2991 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992
Andy Hungdc099c22018-09-18 13:46:39 -07002993 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002994
Eric Laurent6acd1d42017-01-04 14:23:29 -08002995 // If we still have effect chains, it means that a client still holds a handle
2996 // on at least one effect. We must either move the chain to an existing thread with the
2997 // same session ID or put it aside in case a new record thread is opened for a
2998 // new capture on the same session
2999 sp<EffectChain> chain;
3000 {
3001 Mutex::Autolock _sl(recordThread->mLock);
3002 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
3003 // Note: maximum one chain per record thread
3004 if (effectChains.size() != 0) {
3005 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07003006 }
3007 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003008 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003009 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08003010 // This should only happen in case of overlap between one thread tear down and the
3011 // creation of its replacement
3012 size_t i;
3013 for (i = 0; i < mRecordThreads.size(); i++) {
3014 sp<RecordThread> t = mRecordThreads.valueAt(i);
3015 if (t == recordThread) {
3016 continue;
3017 }
3018 if (t->hasAudioSession(chain->sessionId()) != 0) {
3019 Mutex::Autolock _l(t->mLock);
3020 ALOGV("closeInput() found thread %d for effect session %d",
3021 t->id(), chain->sessionId());
3022 t->addEffectChain_l(chain);
3023 break;
3024 }
3025 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08003026 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08003027 if (i == mRecordThreads.size()) {
3028 putOrphanEffectChain_l(chain);
3029 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003030 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003031 mRecordThreads.removeItem(input);
3032 } else {
3033 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
3034 if (mmapThread == 0) {
3035 return BAD_VALUE;
3036 }
Andy Hungdc099c22018-09-18 13:46:39 -07003037 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003038 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07003039 }
Eric Laurent73e26b62015-04-27 16:55:58 -07003040 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
3041 ioDesc->mIoHandle = input;
3042 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043 }
Eric Laurent83b88082014-06-20 18:31:16 -07003044 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
3045 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08003046 if (recordThread != 0) {
3047 closeInputFinish(recordThread);
3048 } else if (mmapThread != 0) {
3049 mmapThread->exit();
3050 AudioStreamIn *in = mmapThread->clearInput();
3051 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3052 // from now on thread->mInput is NULL
3053 delete in;
3054 }
Eric Laurent83b88082014-06-20 18:31:16 -07003055 return NO_ERROR;
3056}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003058void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003059{
3060 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003061 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003062 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003063 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07003064 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07003065}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066
Mikhail Naganov444ecc32018-05-01 17:40:05 -07003067void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003068{
3069 mRecordThreads.removeItem(thread->mId);
3070 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003071}
3072
Glenn Kastend2304db2014-02-03 07:40:31 -08003073status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074{
3075 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08003076 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077
3078 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3079 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07003080 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07003081 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003082 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3083 mMmapThreads[i]->invalidateTracks(stream);
3084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085 return NO_ERROR;
3086}
3087
3088
Glenn Kasteneeecb982016-02-26 10:44:04 -08003089audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090{
Glenn Kasten9d003132016-04-06 14:38:09 -07003091 // This is a binder API, so a malicious client could pass in a bad parameter.
3092 // Check for that before calling the internal API nextUniqueId().
3093 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3094 ALOGE("newAudioUniqueId invalid use %d", use);
3095 return AUDIO_UNIQUE_ID_ALLOCATE;
3096 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003097 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098}
3099
Andy Hung8b0bfd92019-12-23 13:11:11 -08003100void AudioFlinger::acquireAudioSessionId(
3101 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003102{
3103 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08003104 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003105 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003106 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003107 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3108 caller = pid; // check must match releaseAudioSessionId()
3109 }
3110 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3111 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003112 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003113
Eric Laurent021cf962014-05-13 10:18:14 -07003114 {
3115 Mutex::Autolock _cl(mClientLock);
3116 // Ignore requests received from processes not known as notification client. The request
3117 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3118 // called from a different pid leaving a stale session reference. Also we don't know how
3119 // to clear this reference if the client process dies.
3120 if (mNotificationClients.indexOfKey(caller) < 0) {
3121 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3122 return;
3123 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003124 }
3125
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003126 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003127 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003128 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003129 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3130 ref->mCnt++;
3131 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003132 return;
3133 }
3134 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003135 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003136 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003137}
3138
Glenn Kastend848eb42016-03-08 13:42:11 -08003139void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003140{
Eric Laurent6c796322019-04-09 14:13:17 -07003141 std::vector< sp<EffectModule> > removedEffects;
3142 {
3143 Mutex::Autolock _l(mLock);
3144 pid_t caller = IPCThreadState::self()->getCallingPid();
3145 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3146 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003147 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3148 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003149 }
Eric Laurent6c796322019-04-09 14:13:17 -07003150 size_t num = mAudioSessionRefs.size();
3151 for (size_t i = 0; i < num; i++) {
3152 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3153 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3154 ref->mCnt--;
3155 ALOGV(" decremented refcount to %d", ref->mCnt);
3156 if (ref->mCnt == 0) {
3157 mAudioSessionRefs.removeAt(i);
3158 delete ref;
3159 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3160 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3161 }
3162 goto Exit;
3163 }
3164 }
3165 // If the caller is audioserver it is likely that the session being released was acquired
3166 // on behalf of a process not in notification clients and we ignore the warning.
3167 ALOGW_IF(!isAudioServerUid(callerUid),
3168 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003169 }
Eric Laurent6c796322019-04-09 14:13:17 -07003170
3171Exit:
3172 for (auto& effect : removedEffects) {
3173 effect->updatePolicyState();
3174 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003175}
3176
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003177bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3178{
3179 size_t num = mAudioSessionRefs.size();
3180 for (size_t i = 0; i < num; i++) {
3181 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3182 if (ref->mSessionid == audioSession) {
3183 return true;
3184 }
3185 }
3186 return false;
3187}
3188
Eric Laurent6c796322019-04-09 14:13:17 -07003189std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003190
Steve Block3856b092011-10-20 11:56:00 +01003191 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003192
3193 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003194 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003195
3196 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3197 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003198 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003199 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3200 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003201 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003202 chains.push(ec);
3203 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003204 }
3205 }
Eric Laurent6c796322019-04-09 14:13:17 -07003206
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003207 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3208 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003209 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003210 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3211 sp<EffectChain> ec = t->mEffectChains[j];
3212 chains.push(ec);
3213 }
3214 }
3215
Eric Laurent6c796322019-04-09 14:13:17 -07003216 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3217 sp<MmapThread> t = mMmapThreads.valueAt(i);
3218 Mutex::Autolock _l(t->mLock);
3219 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3220 sp<EffectChain> ec = t->mEffectChains[j];
3221 chains.push(ec);
3222 }
3223 }
3224
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003225 for (size_t i = 0; i < chains.size(); i++) {
3226 sp<EffectChain> ec = chains[i];
3227 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003228 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003229 if (t == 0) {
3230 continue;
3231 }
3232 size_t numsessionrefs = mAudioSessionRefs.size();
3233 bool found = false;
3234 for (size_t k = 0; k < numsessionrefs; k++) {
3235 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003236 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003237 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003238 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003239 found = true;
3240 break;
3241 }
3242 }
3243 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003244 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003245 // remove all effects from the chain
3246 while (ec->mEffects.size()) {
3247 sp<EffectModule> effect = ec->mEffects[0];
3248 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003249 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003250 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003251 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003252 }
Eric Laurent6c796322019-04-09 14:13:17 -07003253 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003254 }
3255 }
3256 }
Eric Laurent6c796322019-04-09 14:13:17 -07003257 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003258}
3259
Andy Hungdc099c22018-09-18 13:46:39 -07003260// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3261void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3262{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303263 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
3264 audio_utils::FdToString fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
Andy Hungdc099c22018-09-18 13:46:39 -07003265 const int fd = fdToString.fd();
3266 if (fd >= 0) {
3267 thread->dump(fd, {} /* args */);
3268 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3269 }
3270}
3271
Glenn Kasteneeecb982016-02-26 10:44:04 -08003272// checkThread_l() must be called with AudioFlinger::mLock held
3273AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3274{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003275 ThreadBase *thread = checkMmapThread_l(ioHandle);
3276 if (thread == 0) {
3277 switch (audio_unique_id_get_use(ioHandle)) {
3278 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3279 thread = checkPlaybackThread_l(ioHandle);
3280 break;
3281 case AUDIO_UNIQUE_ID_USE_INPUT:
3282 thread = checkRecordThread_l(ioHandle);
3283 break;
3284 default:
3285 break;
3286 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003287 }
3288 return thread;
3289}
3290
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003292AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293{
Glenn Kastena1117922012-01-26 10:53:32 -08003294 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295}
3296
3297// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003298AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299{
3300 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003301 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302}
3303
3304// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003305AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306{
Glenn Kastena1117922012-01-26 10:53:32 -08003307 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308}
3309
Eric Laurent6acd1d42017-01-04 14:23:29 -08003310// checkMmapThread_l() must be called with AudioFlinger::mLock held
3311AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3312{
3313 return mMmapThreads.valueFor(io).get();
3314}
3315
3316
3317// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3318AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3319{
Eric Laurent7459b902017-04-19 18:10:41 -07003320 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003321 if (volumeInterface == nullptr) {
3322 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3323 if (mmapThread != nullptr) {
3324 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003325 MmapPlaybackThread *mmapPlaybackThread =
3326 static_cast<MmapPlaybackThread *>(mmapThread);
3327 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003328 }
3329 }
3330 }
3331 return volumeInterface;
3332}
3333
3334Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3335{
3336 Vector <VolumeInterface *> volumeInterfaces;
3337 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003338 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003339 }
3340 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3341 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003342 MmapPlaybackThread *mmapPlaybackThread =
3343 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3344 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003345 }
3346 }
3347 return volumeInterfaces;
3348}
3349
Glenn Kasteneeecb982016-02-26 10:44:04 -08003350audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351{
Glenn Kasten9d003132016-04-06 14:38:09 -07003352 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003353 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003354 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3355 for (int retry = 0; retry < maxRetries; retry++) {
3356 // The cast allows wraparound from max positive to min negative instead of abort
3357 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3358 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3359 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3360 // allow wrap by skipping 0 and -1 for session ids
3361 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3362 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3363 return (audio_unique_id_t) (base | use);
3364 }
3365 }
3366 // We have no way of recovering from wraparound
3367 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3368 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369}
3370
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003371AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003372{
Eric Laurent00abf0d2020-04-22 19:28:22 -07003373 AutoMutex lock(mHardwareLock);
3374 if (mPrimaryHardwareDev == nullptr) {
3375 return nullptr;
3376 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003377 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3378 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003379 if(thread->isDuplicating()) {
3380 continue;
3381 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003382 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003383 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003384 return thread;
3385 }
3386 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07003387 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003388}
3389
jiabinc52b1ff2019-10-31 17:20:42 -07003390DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003391{
3392 PlaybackThread *thread = primaryPlaybackThread_l();
3393
3394 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003395 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003396 }
3397
jiabinc52b1ff2019-10-31 17:20:42 -07003398 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003399}
3400
Glenn Kastena7335632016-06-09 17:09:53 -07003401AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3402{
3403 size_t minFrameCount = 0;
3404 PlaybackThread *minThread = NULL;
3405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3406 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3407 if (!thread->isDuplicating()) {
3408 size_t frameCount = thread->frameCountHAL();
3409 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3410 (frameCount == minFrameCount && thread->hasFastMixer() &&
3411 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3412 minFrameCount = frameCount;
3413 minThread = thread;
3414 }
3415 }
3416 }
3417 return minThread;
3418}
3419
jiabineb3bda02020-06-30 14:07:03 -07003420AudioFlinger::ThreadBase *AudioFlinger::hapticPlaybackThread_l() const {
3421 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
3422 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3423 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
3424 return thread;
3425 }
3426 }
3427 return nullptr;
3428}
3429
jiabinf042b9b2021-05-07 23:46:28 +00003430void AudioFlinger::updateSecondaryOutputsForTrack_l(
3431 PlaybackThread::Track* track,
3432 PlaybackThread* thread,
3433 const std::vector<audio_io_handle_t> &secondaryOutputs) const {
3434 TeePatches teePatches;
3435 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
3436 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
3437 if (secondaryThread == nullptr) {
3438 ALOGE("no playback thread found for secondary output %d", thread->id());
3439 continue;
3440 }
3441
3442 size_t sourceFrameCount = thread->frameCount() * track->sampleRate()
3443 / thread->sampleRate();
3444 size_t sinkFrameCount = secondaryThread->frameCount() * track->sampleRate()
3445 / secondaryThread->sampleRate();
3446 // If the secondary output has just been opened, the first secondaryThread write
3447 // will not block as it will fill the empty startup buffer of the HAL,
3448 // so a second sink buffer needs to be ready for the immediate next blocking write.
3449 // Additionally, have a margin of one main thread buffer as the scheduling jitter
3450 // can reorder the writes (eg if thread A&B have the same write intervale,
3451 // the scheduler could schedule AB...BA)
3452 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
3453 // Total secondary output buffer must be at least as the read frames plus
3454 // the margin of a few buffers on both sides in case the
3455 // threads scheduling has some jitter.
3456 // That value should not impact latency as the secondary track is started before
3457 // its buffer is full, see frameCountToBeReady.
3458 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
3459 // The frameCount should also not be smaller than the secondary thread min frame
3460 // count
3461 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
3462 [&] { Mutex::Autolock _l(secondaryThread->mLock);
3463 return secondaryThread->latency_l(); }(),
3464 secondaryThread->mNormalFrameCount,
3465 secondaryThread->mSampleRate,
3466 track->sampleRate(),
3467 track->getSpeed());
3468 frameCount = std::max(frameCount, minFrameCount);
3469
3470 using namespace std::chrono_literals;
3471 auto inChannelMask = audio_channel_mask_out_to_in(track->channelMask());
jiabinfaa67ff2022-09-15 17:49:50 +00003472 if (inChannelMask == AUDIO_CHANNEL_INVALID) {
3473 // The downstream PatchTrack has the proper output channel mask,
3474 // so if there is no input channel mask equivalent, we can just
3475 // use an index mask here to create the PatchRecord.
3476 inChannelMask = audio_channel_mask_out_to_in_index_mask(track->channelMask());
3477 }
jiabinf042b9b2021-05-07 23:46:28 +00003478 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
3479 track->sampleRate(),
3480 inChannelMask,
3481 track->format(),
3482 frameCount,
3483 nullptr /* buffer */,
3484 (size_t)0 /* bufferSize */,
3485 AUDIO_INPUT_FLAG_DIRECT,
3486 0ns /* timeout */);
3487 status_t status = patchRecord->initCheck();
3488 if (status != NO_ERROR) {
3489 ALOGE("Secondary output patchRecord init failed: %d", status);
3490 continue;
3491 }
3492
3493 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
3494 // for fast usage: thread has fast mixer, sample rate matches, etc.;
3495 // for now, we exclude fast tracks by removing the Fast flag.
3496 const audio_output_flags_t outputFlags =
3497 (audio_output_flags_t)(track->getOutputFlags() & ~AUDIO_OUTPUT_FLAG_FAST);
3498 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
3499 track->streamType(),
3500 track->sampleRate(),
3501 track->channelMask(),
3502 track->format(),
3503 frameCount,
3504 patchRecord->buffer(),
3505 patchRecord->bufferSize(),
3506 outputFlags,
3507 0ns /* timeout */,
3508 frameCountToBeReady);
3509 status = patchTrack->initCheck();
3510 if (status != NO_ERROR) {
3511 ALOGE("Secondary output patchTrack init failed: %d", status);
3512 continue;
3513 }
3514 teePatches.push_back({patchRecord, patchTrack});
3515 secondaryThread->addPatchTrack(patchTrack);
3516 // In case the downstream patchTrack on the secondaryThread temporarily outlives
3517 // our created track, ensure the corresponding patchRecord is still alive.
3518 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
3519 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
3520 }
3521 track->setTeePatches(std::move(teePatches));
3522}
3523
Eric Laurenta011e352012-03-29 15:51:43 -07003524sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003525 audio_session_t triggerSession,
3526 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003527 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003528 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003529{
3530 Mutex::Autolock _l(mLock);
3531
3532 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3533 status_t playStatus = NAME_NOT_FOUND;
3534 status_t recStatus = NAME_NOT_FOUND;
3535 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3536 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3537 if (playStatus == NO_ERROR) {
3538 return event;
3539 }
3540 }
3541 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3542 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3543 if (recStatus == NO_ERROR) {
3544 return event;
3545 }
3546 }
3547 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3548 mPendingSyncEvents.add(event);
3549 } else {
3550 ALOGV("createSyncEvent() invalid event %d", event->type());
3551 event.clear();
3552 }
3553 return event;
3554}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003555
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556// ----------------------------------------------------------------------------
3557// Effect management
3558// ----------------------------------------------------------------------------
3559
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003560sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3561 return mEffectsFactoryHal;
3562}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003563
Glenn Kastenf587ba52012-01-26 16:25:10 -08003564status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565{
3566 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003567 if (mEffectsFactoryHal.get()) {
3568 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3569 } else {
3570 return -ENODEV;
3571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003572}
3573
Glenn Kastenf587ba52012-01-26 16:25:10 -08003574status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575{
3576 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003577 if (mEffectsFactoryHal.get()) {
3578 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3579 } else {
3580 return -ENODEV;
3581 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582}
3583
Glenn Kasten5e92a782012-01-30 07:40:52 -08003584status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003585 const effect_uuid_t *pTypeUuid,
3586 uint32_t preferredTypeFlag,
3587 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003589 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3590 return BAD_VALUE;
3591 }
3592
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003594
3595 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003596 return -ENODEV;
3597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003599 status_t status = NO_ERROR;
3600 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3601 // If uuid is specified, request effect descriptor from that.
3602 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3603 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3604 // If uuid is not specified, look for an available implementation
3605 // of the required type instead.
3606
3607 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3608 effect_descriptor_t desc;
3609 desc.flags = 0; // prevent compiler warning
3610
3611 uint32_t numEffects = 0;
3612 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3613 if (status < 0) {
3614 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3615 return status;
3616 }
3617
3618 bool found = false;
3619 for (uint32_t i = 0; i < numEffects; i++) {
3620 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3621 if (status < 0) {
3622 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3623 continue;
3624 }
3625 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3626 // If matching type found save effect descriptor.
3627 found = true;
3628 *descriptor = desc;
3629
3630 // If there's no preferred flag or this descriptor matches the preferred
3631 // flag, success! If this descriptor doesn't match the preferred
3632 // flag, continue enumeration in case a better matching version of this
3633 // effect type is available. Note that this means if no effect with a
3634 // correct flag is found, the descriptor returned will correspond to the
3635 // last effect that at least had a matching type uuid (if any).
3636 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3637 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3638 break;
3639 }
3640 }
3641 }
3642
3643 if (!found) {
3644 status = NAME_NOT_FOUND;
3645 ALOGW("getEffectDescriptor(): Effect not found by type.");
3646 }
3647 } else {
3648 status = BAD_VALUE;
3649 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3650 }
3651 return status;
3652}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003654status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request,
3655 media::CreateEffectResponse* response) {
3656 const sp<IEffectClient>& effectClient = request.client;
3657 const int32_t priority = request.priority;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003658 const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003659 aidl2legacy_AudioDeviceTypeAddress(request.device));
Svet Ganov33761132021-05-13 22:51:08 +00003660 AttributionSourceState adjAttributionSource = request.attributionSource;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003661 const audio_session_t sessionId = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003662 aidl2legacy_int32_t_audio_session_t(request.sessionId));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003663 audio_io_handle_t io = VALUE_OR_RETURN_STATUS(
3664 aidl2legacy_int32_t_audio_io_handle_t(request.output));
3665 const effect_descriptor_t descIn = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003666 aidl2legacy_EffectDescriptor_effect_descriptor_t(request.desc));
3667 const bool probe = request.probe;
3668
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669 sp<EffectHandle> handle;
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003670 effect_descriptor_t descOut;
3671 int enabledOut = 0;
3672 int idOut = -1;
3673
3674 status_t lStatus = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003676 // TODO b/182392553: refactor or make clearer
Eric Laurentb6436272016-12-07 19:24:50 -08003677 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Svet Ganov33761132021-05-13 22:51:08 +00003678 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
3679 pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003680 if (currentPid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003681 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003682 ALOGW_IF(currentPid != -1 && currentPid != callingPid,
Eric Laurentb6436272016-12-07 19:24:50 -08003683 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003684 __func__, callingUid, callingPid, currentPid);
Svet Ganov33761132021-05-13 22:51:08 +00003685 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003686 currentPid = callingPid;
Eric Laurentb6436272016-12-07 19:24:50 -08003687 }
3688
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003689 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
Svet Ganov33761132021-05-13 22:51:08 +00003690 adjAttributionSource.pid, effectClient.get(), priority, sessionId, io,
3691 mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003693 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003694 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003695 lStatus = NO_INIT;
3696 goto Exit;
3697 }
3698
Andy Hung6096dcd2019-03-13 13:20:30 -07003699 // check audio settings permission for global effects
3700 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3701 if (!settingsAllowed()) {
3702 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3703 lStatus = PERMISSION_DENIED;
3704 goto Exit;
3705 }
3706 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3707 if (!isAudioServerUid(callingUid)) {
3708 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3709 lStatus = PERMISSION_DENIED;
3710 goto Exit;
3711 }
3712
3713 if (io == AUDIO_IO_HANDLE_NONE) {
3714 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3715 lStatus = BAD_VALUE;
3716 goto Exit;
3717 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003718 } else if (sessionId == AUDIO_SESSION_DEVICE) {
Svet Ganov33761132021-05-13 22:51:08 +00003719 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)) {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003720 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3721 lStatus = PERMISSION_DENIED;
3722 goto Exit;
3723 }
Eric Laurent94876032019-11-13 12:45:28 -08003724 if (io != AUDIO_IO_HANDLE_NONE) {
3725 ALOGE("%s: io handle should not be specified for device effect", __func__);
3726 lStatus = BAD_VALUE;
3727 goto Exit;
3728 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003729 } else {
3730 // general sessionId.
3731
3732 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3733 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3734 lStatus = BAD_VALUE;
3735 goto Exit;
3736 }
3737
3738 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3739 // to prevent creating an effect when one doesn't actually have track with that session?
3740 }
3741
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003743 // Get the full effect descriptor from the uuid/type.
3744 // If the session is the output mix, prefer an auxiliary effect,
3745 // otherwise no preference.
3746 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3747 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003748 lStatus = getEffectDescriptor(&descIn.uuid, &descIn.type, preferredType, &descOut);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003749 if (lStatus < 0) {
3750 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3751 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 }
3753
3754 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003755 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003756 (descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 lStatus = INVALID_OPERATION;
3758 goto Exit;
3759 }
3760
Eric Laurent59255e42011-07-27 19:49:51 -07003761 // check recording permission for visualizer
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003762 if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003763 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Svet Ganov33761132021-05-13 22:51:08 +00003764 !recordingAllowed(adjAttributionSource)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003765 lStatus = PERMISSION_DENIED;
3766 goto Exit;
3767 }
3768
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003769 const bool hapticPlaybackRequired = EffectModule::isHapticGenerator(&descOut.type);
jiabineb3bda02020-06-30 14:07:03 -07003770 if (hapticPlaybackRequired
3771 && (sessionId == AUDIO_SESSION_DEVICE
3772 || sessionId == AUDIO_SESSION_OUTPUT_MIX
3773 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
3774 // haptic-generating effect is only valid when the session id is a general session id
3775 lStatus = INVALID_OPERATION;
3776 goto Exit;
3777 }
3778
Eric Laurentf690c462021-09-17 14:47:03 +02003779 // Only audio policy service can create a spatializer effect
3780 if ((memcmp(&descOut.type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0) &&
3781 (callingUid != AID_AUDIOSERVER || currentPid != getpid())) {
3782 ALOGW("%s: attempt to create a spatializer effect from uid/pid %d/%d",
3783 __func__, callingUid, currentPid);
3784 lStatus = PERMISSION_DENIED;
3785 goto Exit;
3786 }
3787
Glenn Kasten142f5192014-03-25 17:44:59 -07003788 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003789 // if the output returned by getOutputForEffect() is removed before we lock the
3790 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3791 // and we will exit safely
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003792 io = AudioSystem::getOutputForEffect(&descOut);
Eric Laurenteb3c3372013-09-25 12:25:29 -07003793 ALOGV("createEffect got output %d", io);
3794 }
3795
3796 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797
Eric Laurentb82e6b72019-11-22 17:25:04 -08003798 if (sessionId == AUDIO_SESSION_DEVICE) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003799 sp<Client> client = registerPid(currentPid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003800 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Eric Laurentb82e6b72019-11-22 17:25:04 -08003801 handle = mDeviceEffectManager.createEffect_l(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003802 &descOut, device, client, effectClient, mPatchPanel.patches_l(),
Eric Laurentde8caf42021-08-11 17:19:25 +02003803 &enabledOut, &lStatus, probe, request.notifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003804 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3805 // remove local strong reference to Client with mClientLock held
3806 Mutex::Autolock _cl(mClientLock);
3807 client.clear();
3808 } else {
3809 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003810 if (handle.get() != nullptr) idOut = handle->id();
Eric Laurentb82e6b72019-11-22 17:25:04 -08003811 }
3812 goto Register;
3813 }
3814
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815 // If output is not specified try to find a matching audio session ID in one of the
3816 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003817 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3818 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003819 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3820 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003821 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003822 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003823 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3824 if (io == AUDIO_IO_HANDLE_NONE) {
3825 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003827 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003828 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003829 }
Andy Hung444bb552019-03-14 17:06:39 -07003830
3831 // If you wish to create a Record preprocessing AudioEffect in Java,
3832 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3833 // Otherwise it will fail when created on a Playback thread by legacy
3834 // handling below. Ditto with Mmap, the associated Mmap track must be created
3835 // before creating the AudioEffect or the io handle must be specified.
3836 //
3837 // Detect if the effect is created after an AudioRecord is destroyed.
3838 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3839 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003840 " for session %d no longer exists",
3841 __func__, descOut.name, sessionId);
Andy Hung444bb552019-03-14 17:06:39 -07003842 lStatus = PERMISSION_DENIED;
3843 goto Exit;
3844 }
3845
3846 // Legacy handling of creating an effect on an expired or made-up
3847 // session id. We think that it is a Playback effect.
3848 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003849 // If no output thread contains the requested session ID, default to
3850 // first output. The effect chain will be moved to the correct output
3851 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003852 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003853 io = mPlaybackThreads.keyAt(0);
3854 }
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003855 ALOGV("createEffect() got io %d for effect %s", io, descOut.name);
Eric Laurentb3f315a2021-07-13 15:09:05 +02003856 } else if (checkPlaybackThread_l(io) != nullptr
3857 && sessionId != AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung1631f062019-03-12 19:39:03 -07003858 // allow only one effect chain per sessionId on mPlaybackThreads.
3859 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3860 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07003861 if (io == checkIo) {
3862 if (hapticPlaybackRequired
3863 && mPlaybackThreads.valueAt(i)
3864 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3865 ALOGE("%s: haptic playback thread is required while the required playback "
3866 "thread(io=%d) doesn't support", __func__, (int)io);
3867 lStatus = BAD_VALUE;
3868 goto Exit;
3869 }
3870 continue;
3871 }
Andy Hung1631f062019-03-12 19:39:03 -07003872 const uint32_t sessionType =
3873 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3874 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3875 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003876 __func__, descOut.name, (int) io, (int) sessionId, (int) checkIo);
Andy Hung1631f062019-03-12 19:39:03 -07003877 android_errorWriteLog(0x534e4554, "123237974");
3878 lStatus = BAD_VALUE;
3879 goto Exit;
3880 }
3881 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003882 }
3883 ThreadBase *thread = checkRecordThread_l(io);
3884 if (thread == NULL) {
3885 thread = checkPlaybackThread_l(io);
3886 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003887 thread = checkMmapThread_l(io);
3888 if (thread == NULL) {
3889 ALOGE("createEffect() unknown output thread");
3890 lStatus = BAD_VALUE;
3891 goto Exit;
3892 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003893 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003894 } else {
3895 // Check if one effect chain was awaiting for an effect to be created on this
3896 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003897 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003898 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003899 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003900 thread->addEffectChain_l(chain);
3901 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003903
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003904 sp<Client> client = registerPid(currentPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003906 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003907 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
jiabineb3bda02020-06-30 14:07:03 -07003908 ThreadBase *oriThread = nullptr;
3909 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3910 ThreadBase *hapticThread = hapticPlaybackThread_l();
3911 if (hapticThread == nullptr) {
3912 ALOGE("%s haptic thread not found while it is required", __func__);
3913 lStatus = INVALID_OPERATION;
3914 goto Exit;
3915 }
3916 if (hapticThread != thread) {
3917 // Force to use haptic thread for haptic-generating effect.
3918 oriThread = thread;
3919 thread = hapticThread;
3920 }
3921 }
Eric Laurentde070132010-07-13 04:45:46 -07003922 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurentde8caf42021-08-11 17:19:25 +02003923 &descOut, &enabledOut, &lStatus, pinned, probe,
3924 request.notifyFramesProcessed);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003925 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003926 // remove local strong reference to Client with mClientLock held
3927 Mutex::Autolock _cl(mClientLock);
3928 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003929 } else {
3930 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003931 if (handle.get() != nullptr) idOut = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07003932 // Invalidate audio session when haptic playback is created.
3933 if (hapticPlaybackRequired && oriThread != nullptr) {
3934 // invalidateTracksForAudioSession will trigger locking the thread.
3935 oriThread->invalidateTracksForAudioSession(sessionId);
3936 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 }
3939
Eric Laurentb82e6b72019-11-22 17:25:04 -08003940Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003941 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent6c796322019-04-09 14:13:17 -07003942 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003943 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003944 if (effect != nullptr) {
3945 status_t rStatus = effect->updatePolicyState();
3946 if (rStatus != NO_ERROR) {
3947 lStatus = rStatus;
3948 }
3949 }
3950 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003951 handle.clear();
3952 }
3953
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003954 response->id = idOut;
3955 response->enabled = enabledOut != 0;
3956 response->effect = handle;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003957 response->desc = VALUE_OR_RETURN_STATUS(
3958 legacy2aidl_effect_descriptor_t_EffectDescriptor(descOut));
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003959
Mathias Agopian65ab4712010-07-14 17:59:35 -07003960Exit:
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003961 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962}
3963
Glenn Kastend848eb42016-03-08 13:42:11 -08003964status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003965 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003966{
Steve Block3856b092011-10-20 11:56:00 +01003967 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003968 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003969 Mutex::Autolock _l(mLock);
3970 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003971 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003972 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003973 }
Eric Laurentde070132010-07-13 04:45:46 -07003974 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3975 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003976 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003977 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 }
Eric Laurentde070132010-07-13 04:45:46 -07003979 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3980 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003981 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003982 return BAD_VALUE;
3983 }
3984
3985 Mutex::Autolock _dl(dstThread->mLock);
3986 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003987 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988}
3989
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003990
3991void AudioFlinger::setEffectSuspended(int effectId,
3992 audio_session_t sessionId,
3993 bool suspended)
3994{
3995 Mutex::Autolock _l(mLock);
3996
3997 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3998 if (thread == nullptr) {
3999 return;
4000 }
4001 Mutex::Autolock _sl(thread->mLock);
4002 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
4003 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
4004}
4005
4006
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004007// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08004008status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07004009 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07004010 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07004011{
Steve Block3856b092011-10-20 11:56:00 +01004012 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07004013 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07004014
Eric Laurent59255e42011-07-27 19:49:51 -07004015 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07004016 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004017 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07004018 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07004019 return INVALID_OPERATION;
4020 }
4021
Eric Laurent4c415062016-06-17 16:14:16 -07004022 // Check whether the destination thread and all effects in the chain are compatible
4023 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07004024 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07004025 " destination thread %p is not compatible with effects in the chain",
4026 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07004027 return INVALID_OPERATION;
4028 }
4029
Eric Laurent39e94f82010-07-28 01:32:47 -07004030 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004031 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07004032 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07004033 // removed.
4034 srcThread->removeEffectChain_l(chain);
4035
4036 // transfer all effects one by one so that new effect chain is created on new thread with
4037 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07004038 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004039 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07004040 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004041 Vector< sp<EffectModule> > removed;
4042 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07004043 while (effect != 0) {
4044 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004045 removed.add(effect);
4046 status = dstThread->addEffect_l(effect);
4047 if (status != NO_ERROR) {
4048 break;
4049 }
Eric Laurentec35a142011-10-05 17:42:25 -07004050 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4051 if (effect->state() == EffectModule::ACTIVE ||
4052 effect->state() == EffectModule::STOPPING) {
4053 effect->start();
4054 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004055 // if the move request is not received from audio policy manager, the effect must be
4056 // re-registered with the new strategy and output
4057 if (dstChain == 0) {
Andy Hungfda44002021-06-03 17:23:16 -07004058 dstChain = effect->getCallback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07004059 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004060 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004061 status = NO_INIT;
4062 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004063 }
4064 strategy = dstChain->strategy();
4065 }
Eric Laurentde070132010-07-13 04:45:46 -07004066 effect = chain->getEffectFromId_l(0);
4067 }
4068
Eric Laurent5baf2af2013-09-12 17:37:00 -07004069 if (status != NO_ERROR) {
4070 for (size_t i = 0; i < removed.size(); i++) {
4071 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004072 }
4073 }
4074
4075 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076}
4077
Eric Laurent6c796322019-04-09 14:13:17 -07004078status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
4079 const sp<PlaybackThread>& dstThread,
4080 sp<PlaybackThread> *srcThread)
4081{
4082 status_t status = NO_ERROR;
4083 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004084 sp<PlaybackThread> thread =
4085 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07004086
4087 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
4088 Mutex::Autolock _dl(dstThread->mLock);
4089 Mutex::Autolock _sl(thread->mLock);
4090 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4091 sp<EffectChain> dstChain;
4092 if (srcChain == 0) {
4093 return INVALID_OPERATION;
4094 }
4095
4096 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
4097 if (effect == 0) {
4098 return INVALID_OPERATION;
4099 }
4100 thread->removeEffect_l(effect);
4101 status = dstThread->addEffect_l(effect);
4102 if (status != NO_ERROR) {
4103 thread->addEffect_l(effect);
4104 status = INVALID_OPERATION;
4105 goto Exit;
4106 }
4107
Andy Hungfda44002021-06-03 17:23:16 -07004108 dstChain = effect->getCallback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004109 if (dstChain == 0) {
4110 thread->addEffect_l(effect);
4111 status = INVALID_OPERATION;
4112 }
4113
4114Exit:
4115 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4116 if (effect->state() == EffectModule::ACTIVE ||
4117 effect->state() == EffectModule::STOPPING) {
4118 effect->start();
4119 }
4120 }
4121
4122 if (status == NO_ERROR && srcThread != nullptr) {
4123 *srcThread = thread;
4124 }
4125 return status;
4126}
4127
Eric Laurent5baf2af2013-09-12 17:37:00 -07004128bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07004129{
4130 if (mGlobalEffectEnableTime != 0 &&
4131 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
4132 return true;
4133 }
4134
4135 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4136 sp<EffectChain> ec =
4137 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004138 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07004139 return true;
4140 }
4141 }
4142 return false;
4143}
4144
Eric Laurent5baf2af2013-09-12 17:37:00 -07004145void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07004146{
4147 Mutex::Autolock _l(mLock);
4148
4149 mGlobalEffectEnableTime = systemTime();
4150
4151 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4152 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
4153 if (t->mType == ThreadBase::OFFLOAD) {
4154 t->invalidateTracks(AUDIO_STREAM_MUSIC);
4155 }
4156 }
4157
4158}
4159
Eric Laurentaaa44472014-09-12 17:41:50 -07004160status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
4161{
Eric Laurentd8365c52017-07-16 15:27:05 -07004162 // clear possible suspended state before parking the chain so that it starts in default state
4163 // when attached to a new record thread
4164 chain->setEffectSuspended_l(FX_IID_AEC, false);
4165 chain->setEffectSuspended_l(FX_IID_NS, false);
4166
Glenn Kastend848eb42016-03-08 13:42:11 -08004167 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004168 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004169 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004170 if (index >= 0) {
4171 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
4172 return ALREADY_EXISTS;
4173 }
4174 mOrphanEffectChains.add(session, chain);
4175 return NO_ERROR;
4176}
4177
4178sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
4179{
4180 sp<EffectChain> chain;
4181 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004182 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004183 if (index >= 0) {
4184 chain = mOrphanEffectChains.valueAt(index);
4185 mOrphanEffectChains.removeItemsAt(index);
4186 }
4187 return chain;
4188}
4189
4190bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
4191{
4192 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08004193 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004194 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004195 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004196 if (index >= 0) {
4197 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08004198 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004199 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004200 mOrphanEffectChains.removeItemsAt(index);
4201 }
4202 return true;
4203 }
4204 return false;
4205}
4206
4207
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208// ----------------------------------------------------------------------------
4209
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004210status_t AudioFlinger::onTransactWrapper(TransactionCode code,
4211 const Parcel& data,
4212 uint32_t flags,
4213 const std::function<status_t()>& delegate) {
4214 (void) data;
4215 (void) flags;
4216
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004217 // make sure transactions reserved to AudioPolicyManager do not come from other processes
4218 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004219 case TransactionCode::SET_STREAM_VOLUME:
4220 case TransactionCode::SET_STREAM_MUTE:
4221 case TransactionCode::OPEN_OUTPUT:
4222 case TransactionCode::OPEN_DUPLICATE_OUTPUT:
4223 case TransactionCode::CLOSE_OUTPUT:
4224 case TransactionCode::SUSPEND_OUTPUT:
4225 case TransactionCode::RESTORE_OUTPUT:
4226 case TransactionCode::OPEN_INPUT:
4227 case TransactionCode::CLOSE_INPUT:
4228 case TransactionCode::INVALIDATE_STREAM:
4229 case TransactionCode::SET_VOICE_VOLUME:
4230 case TransactionCode::MOVE_EFFECTS:
4231 case TransactionCode::SET_EFFECT_SUSPENDED:
4232 case TransactionCode::LOAD_HW_MODULE:
4233 case TransactionCode::GET_AUDIO_PORT:
4234 case TransactionCode::CREATE_AUDIO_PATCH:
4235 case TransactionCode::RELEASE_AUDIO_PATCH:
4236 case TransactionCode::LIST_AUDIO_PATCHES:
4237 case TransactionCode::SET_AUDIO_PORT_CONFIG:
4238 case TransactionCode::SET_RECORD_SILENCED:
Eric Laurent39934ea2021-07-13 13:35:32 +02004239 case TransactionCode::AUDIO_POLICY_READY:
Mikhail Naganovd7ba61d2022-02-01 23:53:59 +00004240 case TransactionCode::SET_DEVICE_CONNECTED_STATE:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004241 ALOGW("%s: transaction %d received from PID %d",
4242 __func__, code, IPCThreadState::self()->getCallingPid());
4243 // return status only for non void methods
4244 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004245 case TransactionCode::SET_RECORD_SILENCED:
4246 case TransactionCode::SET_EFFECT_SUSPENDED:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004247 break;
4248 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004249 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004250 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004251 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004252 return OK;
4253 default:
4254 break;
4255 }
4256
4257 // make sure the following transactions come from system components
4258 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004259 case TransactionCode::SET_MASTER_VOLUME:
4260 case TransactionCode::SET_MASTER_MUTE:
Jean-Michel Trivie4f113b2020-11-16 11:50:33 -08004261 case TransactionCode::MASTER_MUTE:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004262 case TransactionCode::SET_MODE:
4263 case TransactionCode::SET_MIC_MUTE:
4264 case TransactionCode::SET_LOW_RAM_DEVICE:
4265 case TransactionCode::SYSTEM_READY:
jiabin1319f5a2021-03-30 22:21:24 +00004266 case TransactionCode::SET_AUDIO_HAL_PIDS:
jiabinf042b9b2021-05-07 23:46:28 +00004267 case TransactionCode::SET_VIBRATOR_INFOS:
4268 case TransactionCode::UPDATE_SECONDARY_OUTPUTS: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004269 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
4270 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
4271 __func__, code, IPCThreadState::self()->getCallingPid(),
4272 IPCThreadState::self()->getCallingUid());
4273 // return status only for non void methods
4274 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004275 case TransactionCode::SYSTEM_READY:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004276 break;
4277 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004278 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004279 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004280 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004281 return OK;
4282 }
4283 } break;
4284 default:
4285 break;
4286 }
4287
4288 // List of relevant events that trigger log merging.
4289 // Log merging should activate during audio activity of any kind. This are considered the
4290 // most relevant events.
4291 // TODO should select more wisely the items from the list
4292 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004293 case TransactionCode::CREATE_TRACK:
4294 case TransactionCode::CREATE_RECORD:
4295 case TransactionCode::SET_MASTER_VOLUME:
4296 case TransactionCode::SET_MASTER_MUTE:
4297 case TransactionCode::SET_MIC_MUTE:
4298 case TransactionCode::SET_PARAMETERS:
4299 case TransactionCode::CREATE_EFFECT:
4300 case TransactionCode::SYSTEM_READY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004301 requestLogMerge();
4302 break;
4303 }
4304 default:
4305 break;
4306 }
4307
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004308 std::string tag("IAudioFlinger command " +
4309 std::to_string(static_cast<std::underlying_type_t<TransactionCode>>(code)));
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004310 TimeCheck check(tag.c_str());
4311
4312 // Make sure we connect to Audio Policy Service before calling into AudioFlinger:
4313 // - AudioFlinger can call into Audio Policy Service with its global mutex held
4314 // - If this is the first time Audio Policy Service is queried from inside audioserver process
4315 // this will trigger Audio Policy Manager initialization.
4316 // - Audio Policy Manager initialization calls into AudioFlinger which will try to lock
4317 // its global mutex and a deadlock will occur.
4318 if (IPCThreadState::self()->getCallingPid() != getpid()) {
4319 AudioSystem::get_audio_policy_service();
4320 }
4321
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004322 return delegate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323}
4324
Glenn Kasten63238ef2015-03-02 15:50:29 -08004325} // namespace android