blob: b359331e60ab8c97a256e92e831e9e5a23e89ffc [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"
Jiabin Huangebe64102021-09-07 20:01:07 +000060#include "PropertyUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Andy Hung6770c6f2015-04-07 13:43:36 -070062#include <media/AudioResamplerPublic.h>
63
Mikhail Naganov9fe94012016-10-14 14:57:40 -070064#include <system/audio_effects/effect_visualizer.h>
65#include <system/audio_effects/effect_ns.h>
66#include <system/audio_effects/effect_aec.h>
jiabineb3bda02020-06-30 14:07:03 -070067#include <system/audio_effects/effect_hapticgenerator.h>
Eric Laurentf690c462021-09-17 14:47:03 +020068#include <system/audio_effects/effect_spatializer.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
Glenn Kasten3b21c502011-12-15 09:52:39 -080070#include <audio_utils/primitives.h>
71
Eric Laurentfeb0db62011-07-22 09:04:31 -070072#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080073
Glenn Kasten9e58b552013-01-18 15:09:48 -080074#include <media/IMediaLogService.h>
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070075#include <media/AidlConversion.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080076#include <media/AudioValidator.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080077#include <media/nbaio/Pipe.h>
78#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080079#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070080#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070082#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070083#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080084
rago3bd1c872016-09-26 12:58:14 -070085//#define BUFLOG_NDEBUG 0
86#include <BufLog.h>
87
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080088#include "TypedLogger.h"
89
Mathias Agopian65ab4712010-07-14 17:59:35 -070090// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070091
John Grossman1c345192012-03-27 14:00:17 -070092// Note: the following macro is used for extremely verbose logging message. In
93// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
94// 0; but one side effect of this is to turn all LOGV's as well. Some messages
95// are so verbose that we want to suppress them even when we have ALOG_ASSERT
96// turned on. Do not uncomment the #def below unless you really know what you
97// are doing and want to see all of the extremely verbose messages.
98//#define VERY_VERY_VERBOSE_LOGGING
99#ifdef VERY_VERY_VERBOSE_LOGGING
100#define ALOGVV ALOGV
101#else
102#define ALOGVV(a...) do { } while(0)
103#endif
Eric Laurentde070132010-07-13 04:45:46 -0700104
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105namespace android {
106
jiabine504e7b2021-09-18 00:27:08 +0000107#define MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION 7.0
108
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700109using media::IEffectClient;
jiabine99d0882021-09-17 05:21:25 +0000110using media::audio::common::AudioMMapPolicyInfo;
111using media::audio::common::AudioMMapPolicyType;
Svet Ganov33761132021-05-13 22:51:08 +0000112using android::content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700113
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800114static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
115static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700116static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700117static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118
Glenn Kasten58912562012-04-03 10:45:00 -0700119
John Grossman4ff14ba2012-02-08 16:37:41 -0800120nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800121
Eric Laurent81784c32012-11-19 14:55:58 -0800122uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700123
Eric Laurent813e2a72013-08-31 12:59:48 -0700124// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
125// we define a minimum time during which a global effect is considered enabled.
126static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
127
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700128// Keep a strong reference to media.log service around forever.
129// The service is within our parent process so it can never die in a way that we could observe.
130// These two variables are const after initialization.
131static sp<IBinder> sMediaLogServiceAsBinder;
132static sp<IMediaLogService> sMediaLogService;
133
134static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
135
136static void sMediaLogInit()
137{
138 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
139 if (sMediaLogServiceAsBinder != 0) {
140 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
141 }
142}
143
jiabin57303cc2018-12-18 15:45:57 -0800144// Keep a strong reference to external vibrator service
145static sp<os::IExternalVibratorService> sExternalVibratorService;
146
147static sp<os::IExternalVibratorService> getExternalVibratorService() {
148 if (sExternalVibratorService == 0) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700149 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800150 String16("external_vibrator_service"));
151 if (binder != 0) {
152 sExternalVibratorService =
153 interface_cast<os::IExternalVibratorService>(binder);
154 }
155 }
156 return sExternalVibratorService;
157}
158
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000159class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
160 public:
161 void onNewDevicesAvailable() override {
162 // Start a detached thread to execute notification in parallel.
163 // This is done to prevent mutual blocking of audio_flinger and
164 // audio_policy services during system initialization.
165 std::thread notifier([]() {
166 AudioSystem::onNewAudioModulesAvailable();
167 });
168 notifier.detach();
169 }
170};
171
Svet Ganov33761132021-05-13 22:51:08 +0000172// TODO b/182392769: use attribution source util
Eric Laurentec376dc2021-04-08 20:41:22 +0200173/* static */
Svet Ganov33761132021-05-13 22:51:08 +0000174AttributionSourceState AudioFlinger::checkAttributionSourcePackage(
175 const AttributionSourceState& attributionSource) {
Eric Laurentec376dc2021-04-08 20:41:22 +0200176 Vector<String16> packages;
Svet Ganov33761132021-05-13 22:51:08 +0000177 PermissionController{}.getPackagesForUid(attributionSource.uid, packages);
Eric Laurentec376dc2021-04-08 20:41:22 +0200178
Svet Ganov33761132021-05-13 22:51:08 +0000179 AttributionSourceState checkedAttributionSource = attributionSource;
180 if (!attributionSource.packageName.has_value()
181 || attributionSource.packageName.value().size() == 0) {
Eric Laurentec376dc2021-04-08 20:41:22 +0200182 if (!packages.isEmpty()) {
Svet Ganov33761132021-05-13 22:51:08 +0000183 checkedAttributionSource.packageName =
Eric Laurentec376dc2021-04-08 20:41:22 +0200184 std::move(legacy2aidl_String16_string(packages[0]).value());
185 }
186 } else {
187 String16 opPackageLegacy = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000188 aidl2legacy_string_view_String16(attributionSource.packageName.value_or("")));
Eric Laurentec376dc2021-04-08 20:41:22 +0200189 if (std::find_if(packages.begin(), packages.end(),
190 [&opPackageLegacy](const auto& package) {
191 return opPackageLegacy == package; }) == packages.end()) {
192 ALOGW("The package name(%s) provided does not correspond to the uid %d",
Svet Ganov33761132021-05-13 22:51:08 +0000193 attributionSource.packageName.value_or("").c_str(), attributionSource.uid);
194 checkedAttributionSource.packageName = std::optional<std::string>();
Eric Laurentec376dc2021-04-08 20:41:22 +0200195 }
196 }
Svet Ganov33761132021-05-13 22:51:08 +0000197 return checkedAttributionSource;
Eric Laurentec376dc2021-04-08 20:41:22 +0200198}
199
Mathias Agopian65ab4712010-07-14 17:59:35 -0700200// ----------------------------------------------------------------------------
201
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700202std::string formatToString(audio_format_t format) {
203 std::string result;
204 FormatConverter::toString(format, result);
205 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800206}
207
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208// ----------------------------------------------------------------------------
209
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800210void AudioFlinger::instantiate() {
211 sp<IServiceManager> sm(defaultServiceManager());
212 sm->addService(String16(IAudioFlinger::DEFAULT_SERVICE_NAME),
213 new AudioFlingerServerAdapter(new AudioFlinger()), false,
214 IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
215}
216
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217AudioFlinger::AudioFlinger()
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800218 : mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800219 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800220 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700221 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800222 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800223 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700224 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800225 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700226 mBtNrecIsOff(false),
227 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700228 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800229 mTotalMemory(0),
230 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700231 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700232 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800233 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700234 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235{
Eric Laurentf43be0c2021-03-25 10:45:53 +0100236 // Move the audio session unique ID generator start base as time passes to limit risk of
237 // generating the same ID again after an audioserver restart.
238 // This is important because clients will reuse previously allocated audio session IDs
239 // when reconnecting after an audioserver restart and newly allocated IDs may conflict with
240 // active clients.
241 // Moving the base by 1 for each elapsed second is a good compromise between avoiding overlap
242 // between allocation ranges and not reaching wrap around too soon.
243 timespec ts{};
244 clock_gettime(CLOCK_MONOTONIC, &ts);
245 // zero ID has a special meaning, so start allocation at least at AUDIO_UNIQUE_ID_USE_MAX
Eric Laurentf37f1982021-06-01 13:23:27 +0200246 uint32_t movingBase = (uint32_t)std::max((long)1, ts.tv_sec);
Glenn Kastend2e67e12016-04-11 08:26:37 -0700247 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
248 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
Eric Laurentf43be0c2021-03-25 10:45:53 +0100249 mNextUniqueIds[use] =
Eric Laurentf37f1982021-06-01 13:23:27 +0200250 ((use == AUDIO_UNIQUE_ID_USE_SESSION || use == AUDIO_UNIQUE_ID_USE_CLIENT) ?
251 movingBase : 1) * AUDIO_UNIQUE_ID_USE_MAX;
Glenn Kastend2e67e12016-04-11 08:26:37 -0700252 }
253
Eric Laurent94ca1142020-10-07 10:45:20 -0700254#if 1
255 // FIXME See bug 165702394 and bug 168511485
256 const bool doLog = false;
257#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800258 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700259#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800260 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800261 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
262 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700263 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800264 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700265
Wei Jia3f273d12015-11-24 09:06:49 -0800266 // reset battery stats.
267 // if the audio service has crashed, battery stats could be left
268 // in bad state, reset the state upon service start.
269 BatteryNotifier::getInstance().noteResetAudio();
270
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700271 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700272 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
273
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800274 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700275 std::vector<pid_t> halPids;
276 mDevicesFactoryHal->getHalPids(&halPids);
277 TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800278
279 // Notify that we have started (also called when audioserver service restarts)
280 mediametrics::LogItem(mMetricsId)
281 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
282 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700283}
284
285void AudioFlinger::onFirstRef()
286{
Eric Laurent93575202011-01-18 18:39:02 -0800287 Mutex::Autolock _l(mLock);
288
Dima Zavin799a70e2011-04-18 16:57:27 -0700289 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800290 char val_str[PROPERTY_VALUE_MAX] = { 0 };
291 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
292 uint32_t int_val;
293 if (1 == sscanf(val_str, "%u", &int_val)) {
294 mStandbyTimeInNsecs = milliseconds(int_val);
295 ALOGI("Using %u mSec as standby time.", int_val);
296 } else {
297 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
298 ALOGI("Using default %u mSec as standby time.",
299 (uint32_t)(mStandbyTimeInNsecs / 1000000));
300 }
301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302
Eric Laurenta4c5a552012-03-29 10:12:40 -0700303 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800304
Andy Hung6626a012021-01-12 13:38:00 -0800305 gAudioFlinger = this; // we are already refcounted, store into atomic pointer.
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000306
307 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
308 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
jiabine504e7b2021-09-18 00:27:08 +0000309
310 if (mDevicesFactoryHal->getHalVersion() <= MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION) {
311 mAAudioBurstsPerBuffer = getAAudioMixerBurstCountFromSystemProperty();
312 mAAudioHwBurstMinMicros = getAAudioHardwareBurstMinUsecFromSystemProperty();
313 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314}
315
Eric Laurent42896a02019-09-27 15:40:33 -0700316status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
317 TimeCheck::setAudioHalPids(pids);
318 return NO_ERROR;
319}
320
jiabin1319f5a2021-03-30 22:21:24 +0000321status_t AudioFlinger::setVibratorInfos(
322 const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
323 Mutex::Autolock _l(mLock);
324 mAudioVibratorInfos = vibratorInfos;
325 return NO_ERROR;
326}
327
jiabinf042b9b2021-05-07 23:46:28 +0000328status_t AudioFlinger::updateSecondaryOutputs(
329 const TrackSecondaryOutputsMap& trackSecondaryOutputs) {
330 Mutex::Autolock _l(mLock);
331 for (const auto& [trackId, secondaryOutputs] : trackSecondaryOutputs) {
332 size_t i = 0;
333 for (; i < mPlaybackThreads.size(); ++i) {
334 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
335 Mutex::Autolock _tl(thread->mLock);
336 sp<PlaybackThread::Track> track = thread->getTrackById_l(trackId);
337 if (track != nullptr) {
338 ALOGD("%s trackId: %u", __func__, trackId);
339 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
340 break;
341 }
342 }
343 ALOGW_IF(i >= mPlaybackThreads.size(),
344 "%s cannot find track with id %u", __func__, trackId);
345 }
346 return NO_ERROR;
347}
348
Jiabin Huangebe64102021-09-07 20:01:07 +0000349status_t AudioFlinger::getMmapPolicyInfos(
jiabine99d0882021-09-17 05:21:25 +0000350 AudioMMapPolicyType policyType, std::vector<AudioMMapPolicyInfo> *policyInfos) {
jiabine504e7b2021-09-18 00:27:08 +0000351 Mutex::Autolock _l(mLock);
Jiabin Huangebe64102021-09-07 20:01:07 +0000352 if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) {
353 *policyInfos = it->second;
354 return NO_ERROR;
355 }
jiabine504e7b2021-09-18 00:27:08 +0000356 if (mDevicesFactoryHal->getHalVersion() > MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION) {
Jiabin Huangebe64102021-09-07 20:01:07 +0000357 AutoMutex lock(mHardwareLock);
358 for (size_t i = 0; i < mAudioHwDevs.size(); ++i) {
359 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
jiabine99d0882021-09-17 05:21:25 +0000360 std::vector<AudioMMapPolicyInfo> infos;
Jiabin Huangebe64102021-09-07 20:01:07 +0000361 status_t status = dev->getMmapPolicyInfos(policyType, &infos);
362 if (status != NO_ERROR) {
363 ALOGE("Failed to query mmap policy info of %d, error %d",
364 mAudioHwDevs.keyAt(i), status);
365 continue;
366 }
367 policyInfos->insert(policyInfos->end(), infos.begin(), infos.end());
368 }
369 mPolicyInfos[policyType] = *policyInfos;
370 } else {
371 getMmapPolicyInfosFromSystemProperty(policyType, policyInfos);
372 mPolicyInfos[policyType] = *policyInfos;
373 }
374 return NO_ERROR;
375}
376
jiabine504e7b2021-09-18 00:27:08 +0000377int32_t AudioFlinger::getAAudioMixerBurstCount() {
378 Mutex::Autolock _l(mLock);
379 return mAAudioBurstsPerBuffer;
380}
381
382int32_t AudioFlinger::getAAudioHardwareBurstMinUsec() {
383 Mutex::Autolock _l(mLock);
384 return mAAudioHwBurstMinMicros;
385}
386
jiabin1319f5a2021-03-30 22:21:24 +0000387// getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
Lais Andradebc3f37a2021-07-02 00:13:19 +0100388std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() {
jiabin1319f5a2021-03-30 22:21:24 +0000389 if (mAudioVibratorInfos.empty()) {
Lais Andradebc3f37a2021-07-02 00:13:19 +0100390 return {};
jiabin1319f5a2021-03-30 22:21:24 +0000391 }
Lais Andradebc3f37a2021-07-02 00:13:19 +0100392 return mAudioVibratorInfos.front();
jiabin1319f5a2021-03-30 22:21:24 +0000393}
394
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395AudioFlinger::~AudioFlinger()
396{
397 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700398 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700399 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400 }
401 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700402 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700403 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 }
Andy Hungb4946b62019-03-14 11:19:28 -0700405 while (!mMmapThreads.isEmpty()) {
406 const audio_io_handle_t io = mMmapThreads.keyAt(0);
407 if (mMmapThreads.valueAt(0)->isOutput()) {
408 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
409 } else {
410 closeInput_nonvirtual(io); // removes entry from mMmapThreads
411 }
412 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700413
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800414 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
415 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700416 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700418
419 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700420 if (sMediaLogService != 0) {
421 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
422 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
423 mUnregisteredWriters.pop();
424 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700425 }
426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427}
428
Eric Laurentfc235202016-12-20 18:48:17 -0800429//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800430__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800431status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
432 const audio_attributes_t *attr,
433 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700434 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800435 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800436 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800437 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700438 sp<MmapStreamInterface>& interface,
439 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800440{
Andy Hung6626a012021-01-12 13:38:00 -0800441 // TODO: Use ServiceManager to get IAudioFlinger instead of by atomic pointer.
442 // This allows moving oboeservice (AAudio) to a separate process in the future.
443 sp<AudioFlinger> af = AudioFlinger::gAudioFlinger.load(); // either nullptr or singleton AF.
Eric Laurentfc235202016-12-20 18:48:17 -0800444 status_t ret = NO_INIT;
445 if (af != 0) {
446 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800447 direction, attr, config, client, deviceId,
448 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800449 }
450 return ret;
451}
452
Eric Laurent6acd1d42017-01-04 14:23:29 -0800453status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
454 const audio_attributes_t *attr,
455 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700456 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800457 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800458 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800459 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700460 sp<MmapStreamInterface>& interface,
461 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800462{
463 status_t ret = initCheck();
464 if (ret != NO_ERROR) {
465 return ret;
466 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800467 audio_session_t actualSessionId = *sessionId;
468 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
469 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
470 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800471 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700472 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800473 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700474 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800475 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
476 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
477 fullConfig.sample_rate = config->sample_rate;
478 fullConfig.channel_mask = config->channel_mask;
479 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800480 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700481
482 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800483 actualSessionId,
Svet Ganov33761132021-05-13 22:51:08 +0000484 &streamType, client.attributionSource,
Ricardo Correa57a37692020-03-23 17:27:25 -0700485 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800486 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
487 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800488 deviceId, &portId, &secondaryOutputs);
489 ALOGW_IF(!secondaryOutputs.empty(),
490 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800491 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700492 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700493 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800494 actualSessionId,
Svet Ganov33761132021-05-13 22:51:08 +0000495 client.attributionSource,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800496 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700497 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800498 }
499 if (ret != NO_ERROR) {
500 return ret;
501 }
502
503 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
504 // audio policy manager and we can retrieve it
505 sp<MmapThread> thread = mMmapThreads.valueFor(io);
506 if (thread != 0) {
507 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700508 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700509 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800510 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800511 config->sample_rate = thread->sampleRate();
512 config->channel_mask = thread->channelMask();
513 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800514 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700515 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700516 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700517 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800518 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700519 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800520 ret = NO_INIT;
521 }
522
523 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
524
Eric Laurentfc235202016-12-20 18:48:17 -0800525 return ret;
526}
527
jiabin57303cc2018-12-18 15:45:57 -0800528/* static */
529int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
530 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
jiabin78dc9c82021-02-22 19:13:29 +0000531 if (evs != nullptr) {
jiabin57303cc2018-12-18 15:45:57 -0800532 int32_t ret;
533 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
534 if (status.isOk()) {
jiabin78dc9c82021-02-22 19:13:29 +0000535 ALOGD("%s, start external vibration with intensity as %d", __func__, ret);
jiabin57303cc2018-12-18 15:45:57 -0800536 return ret;
537 }
538 }
jiabin78dc9c82021-02-22 19:13:29 +0000539 ALOGD("%s, start external vibration with intensity as MUTE due to %s",
540 __func__,
541 evs == nullptr ? "external vibration service not found"
542 : "error when querying intensity");
jiabine70bc7f2020-06-30 22:07:55 -0700543 return static_cast<int>(os::HapticScale::MUTE);
jiabin57303cc2018-12-18 15:45:57 -0800544}
545
546/* static */
547void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
548 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
549 if (evs != 0) {
550 evs->onExternalVibrationStop(*externalVibration);
551 }
552}
553
Eric Laurentb82e6b72019-11-22 17:25:04 -0800554status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
555 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700556 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800557 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
558 if (audioHwDevice == nullptr) {
559 return NO_INIT;
560 }
561 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
562}
563
564status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
565 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700566 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800567 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
568 if (audioHwDevice == nullptr) {
569 return NO_INIT;
570 }
571 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
572}
573
Eric Laurenta4c5a552012-03-29 10:12:40 -0700574static const char * const audio_interfaces[] = {
575 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
576 AUDIO_HARDWARE_MODULE_ID_A2DP,
577 AUDIO_HARDWARE_MODULE_ID_USB,
578};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700579
Phil Burk062e67a2015-02-11 13:40:50 -0800580AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700581 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700582 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700583{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700584 // if module is 0, the request comes from an old policy manager and we should load
585 // well known modules
Eric Laurent00abf0d2020-04-22 19:28:22 -0700586 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700587 if (module == 0) {
588 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700589 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700590 loadHwModule_l(audio_interfaces[i]);
591 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700592 // then try to find a module supporting the requested device.
593 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
594 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700595 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
596 uint32_t supportedDevices;
597 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700598 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700599 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700600 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700601 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700602 } else {
603 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700604 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
605 if (audioHwDevice != NULL) {
606 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700607 }
608 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700609
Dima Zavin799a70e2011-04-18 16:57:27 -0700610 return NULL;
611}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612
Glenn Kasten0f11b512014-01-31 16:18:54 -0800613void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 String8 result;
616
617 result.append("Clients:\n");
Atneyafc18e632021-08-31 18:59:21 -0400618 result.append(" pid heap_size\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800620 sp<Client> client = mClients.valueAt(i).promote();
621 if (client != 0) {
Atneyafc18e632021-08-31 18:59:21 -0400622 result.appendFormat("%6d %12zu\n", client->pid(),
623 client->heap()->getMemoryHeap()->getSize());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 }
625 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700626
Eric Laurentd1b28d42013-09-18 18:47:13 -0700627 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800628 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700629 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800630 const pid_t pid = mNotificationClients[i]->getPid();
631 const uid_t uid = mNotificationClients[i]->getUid();
632 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
633 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700634 }
635
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700636 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800637 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700638 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
639 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800640 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
641 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
642 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645}
646
647
Glenn Kasten0f11b512014-01-31 16:18:54 -0800648void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649{
650 const size_t SIZE = 256;
651 char buffer[SIZE];
652 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800653 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654
John Grossman4ff14ba2012-02-08 16:37:41 -0800655 snprintf(buffer, SIZE, "Hardware status: %d\n"
656 "Standby Time mSec: %u\n",
657 hardwareStatus,
658 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659 result.append(buffer);
660 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661}
662
Glenn Kasten0f11b512014-01-31 16:18:54 -0800663void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664{
665 const size_t SIZE = 256;
666 char buffer[SIZE];
667 String8 result;
668 snprintf(buffer, SIZE, "Permission Denial: "
669 "can't dump AudioFlinger from pid=%d, uid=%d\n",
670 IPCThreadState::self()->getCallingPid(),
671 IPCThreadState::self()->getCallingUid());
672 result.append(buffer);
673 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700674}
675
Eric Laurent81784c32012-11-19 14:55:58 -0800676bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700678 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
679 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680}
681
682status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
683{
Glenn Kasten44deb052012-02-05 18:09:08 -0800684 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685 dumpPermissionDenial(fd, args);
686 } else {
687 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800688 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 if (!hardwareLocked) {
690 String8 result(kHardwareLockedString);
691 write(fd, result.string(), result.size());
692 } else {
693 mHardwareLock.unlock();
694 }
695
Eric Tan7b651152018-07-13 10:17:19 -0700696 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697
698 // failed to lock - AudioFlinger is probably deadlocked
699 if (!locked) {
700 String8 result(kDeadlockedString);
701 write(fd, result.string(), result.size());
702 }
703
Eric Laurent021cf962014-05-13 10:18:14 -0700704 bool clientLocked = dumpTryLock(mClientLock);
705 if (!clientLocked) {
706 String8 result(kClientLockedString);
707 write(fd, result.string(), result.size());
708 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700709
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700710 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700711 mEffectsFactoryHal->dumpEffects(fd);
712 } else {
713 String8 result(kNoEffectsFactory);
714 write(fd, result.string(), result.size());
715 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700716
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700718 if (clientLocked) {
719 mClientLock.unlock();
720 }
721
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722 dumpInternals(fd, args);
723
724 // dump playback threads
725 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
726 mPlaybackThreads.valueAt(i)->dump(fd, args);
727 }
728
729 // dump record threads
730 for (size_t i = 0; i < mRecordThreads.size(); i++) {
731 mRecordThreads.valueAt(i)->dump(fd, args);
732 }
733
Eric Laurent6acd1d42017-01-04 14:23:29 -0800734 // dump mmap threads
735 for (size_t i = 0; i < mMmapThreads.size(); i++) {
736 mMmapThreads.valueAt(i)->dump(fd, args);
737 }
738
Eric Laurentaaa44472014-09-12 17:41:50 -0700739 // dump orphan effect chains
740 if (mOrphanEffectChains.size() != 0) {
741 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
742 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
743 mOrphanEffectChains.valueAt(i)->dump(fd, args);
744 }
745 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700746 // dump all hardware devs
747 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700748 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Andy Hung61589a42021-06-16 09:37:53 -0700749 dev->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700751
Mikhail Naganov201369b2018-05-16 16:52:32 -0700752 mPatchPanel.dump(fd);
753
Eric Laurentb82e6b72019-11-22 17:25:04 -0800754 mDeviceEffectManager.dump(fd);
755
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700756 // dump external setParameters
757 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
758 dprintf(fd, "\n%s setParameters:\n", name);
759 logger.dump(fd, " " /* prefix */);
760 };
761 dumpLogger(mRejectedSetParameterLog, "Rejected");
762 dumpLogger(mAppSetParameterLog, "App");
763 dumpLogger(mSystemSetParameterLog, "System");
764
Andy Hunga8115dc2018-08-24 15:51:59 -0700765 // dump historical threads in the last 10 seconds
766 const std::string threadLog = mThreadLog.dumpToString(
767 "Historical Thread Log ", 0 /* lines */,
768 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
769 write(fd, threadLog.c_str(), threadLog.size());
770
rago3bd1c872016-09-26 12:58:14 -0700771 BUFLOG_RESET;
772
Glenn Kastend65d73c2012-06-22 17:21:07 -0700773 if (locked) {
774 mLock.unlock();
775 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800776
Andy Hung8946a282018-04-19 20:04:56 -0700777#ifdef TEE_SINK
778 // NBAIO_Tee dump is safe to call outside of AF lock.
779 NBAIO_Tee::dumpAll(fd, "_DUMP");
780#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800781 // append a copy of media.log here by forwarding fd to it, but don't attempt
782 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700783 if (sMediaLogServiceAsBinder != 0) {
784 dprintf(fd, "\nmedia.log:\n");
785 Vector<String16> args;
786 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800787 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700788
789 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700790 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700791 bool unreachableMemory = false;
792 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700793 if (arg == String16("-m")) {
794 dumpMem = true;
795 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700796 unreachableMemory = true;
797 }
798 }
799
Andy Hung07b745e2016-05-23 16:21:07 -0700800 if (dumpMem) {
801 dprintf(fd, "\nDumping memory:\n");
802 std::string s = dumpMemoryAddresses(100 /* limit */);
803 write(fd, s.c_str(), s.size());
804 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700805 if (unreachableMemory) {
806 dprintf(fd, "\nDumping unreachable memory:\n");
807 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700808 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700809 write(fd, s.c_str(), s.size());
810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 }
812 return NO_ERROR;
813}
814
Eric Laurent021cf962014-05-13 10:18:14 -0700815sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800816{
Eric Laurent021cf962014-05-13 10:18:14 -0700817 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800818 // If pid is already in the mClients wp<> map, then use that entry
819 // (for which promote() is always != 0), otherwise create a new entry and Client.
820 sp<Client> client = mClients.valueFor(pid).promote();
821 if (client == 0) {
822 client = new Client(this, pid);
823 mClients.add(pid, client);
824 }
825
826 return client;
827}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828
Glenn Kasten9e58b552013-01-18 15:09:48 -0800829sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
830{
Jiabin Huang60766082020-07-28 22:03:56 +0000831 // If there is no memory allocated for logs, return a no-op writer that does nothing.
832 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700833 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800834 return new NBLog::Writer();
835 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700836 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
837 // If allocation fails, consult the vector of previously unregistered writers
838 // and garbage-collect one or more them until an allocation succeeds
839 if (shared == 0) {
840 Mutex::Autolock _l(mUnregisteredWritersLock);
841 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
842 {
843 // Pick the oldest stale writer to garbage-collect
844 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
845 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700846 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700847 // Now the media.log remote reference to IMemory is gone. When our last local
848 // reference to IMemory also drops to zero at end of this block,
849 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
850 }
851 // Re-attempt the allocation
852 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
853 if (shared != 0) {
854 goto success;
855 }
856 }
857 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +0000858 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -0700859 return new NBLog::Writer();
860 }
861success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700862 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800863 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
864 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700865 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800866 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800867}
868
869void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
870{
Glenn Kasten685ef092013-02-04 08:15:34 -0800871 if (writer == 0) {
872 return;
873 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800874 sp<IMemory> iMemory(writer->getIMemory());
875 if (iMemory == 0) {
876 return;
877 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700878 // Rather than removing the writer immediately, append it to a queue of old writers to
879 // be garbage-collected later. This allows us to continue to view old logs for a while.
880 Mutex::Autolock _l(mUnregisteredWritersLock);
881 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800882}
883
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884// IAudioFlinger interface
885
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -0800886status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
887 media::CreateTrackResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888{
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800889 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -0800890 CreateTrackInput input = VALUE_OR_RETURN_STATUS(CreateTrackInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800891 CreateTrackOutput output;
892
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 sp<PlaybackThread::Track> track;
894 sp<TrackHandle> trackHandle;
895 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800897 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800898 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800899 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700901 // TODO b/182392553: refactor or make clearer
902 pid_t clientPid =
Svet Ganov33761132021-05-13 22:51:08 +0000903 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(input.clientInfo.attributionSource.pid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700904 bool updatePid = (clientPid == (pid_t)-1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700905 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700906 uid_t clientUid =
Svet Ganov33761132021-05-13 22:51:08 +0000907 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(input.clientInfo.attributionSource.uid));
Eric Laurent6c796322019-04-09 14:13:17 -0700908 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
909 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700910 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700911
Svet Ganov33761132021-05-13 22:51:08 +0000912 AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700913 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800914 ALOGW_IF(clientUid != callingUid,
915 "%s uid %d tried to pass itself off as %d",
916 __FUNCTION__, callingUid, clientUid);
Svet Ganov33761132021-05-13 22:51:08 +0000917 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Eric Laurent21da6472017-11-09 16:29:26 -0800918 clientUid = callingUid;
919 updatePid = true;
920 }
Eric Laurent09f1ed22019-04-24 17:45:17 -0700921 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800922 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700923 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700924 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800925 __func__, callingUid, callingPid, clientPid);
926 clientPid = callingPid;
Svet Ganov33761132021-05-13 22:51:08 +0000927 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700928 }
929
Eric Laurent21da6472017-11-09 16:29:26 -0800930 audio_session_t sessionId = input.sessionId;
931 if (sessionId == AUDIO_SESSION_ALLOCATE) {
932 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800933 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
934 lStatus = BAD_VALUE;
935 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800936 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800937
Eric Laurent21da6472017-11-09 16:29:26 -0800938 output.sessionId = sessionId;
939 output.outputId = AUDIO_IO_HANDLE_NONE;
940 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700941 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Svet Ganov33761132021-05-13 22:51:08 +0000942 adjAttributionSource, &input.config, input.flags,
Ricardo Correa57a37692020-03-23 17:27:25 -0700943 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800944
945 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
946 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
947 goto Exit;
948 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800949 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
950 // but if someone uses binder directly they could bypass that and cause us to crash
951 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000952 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 lStatus = BAD_VALUE;
954 goto Exit;
955 }
956
Glenn Kasten53b5d092014-02-05 10:00:23 -0800957 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800958 if (!audio_is_output_channel(input.config.channel_mask)) {
959 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800960 lStatus = BAD_VALUE;
961 goto Exit;
962 }
963
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700964 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800965 if (!audio_is_valid_format(input.config.format)) {
966 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700967 lStatus = BAD_VALUE;
968 goto Exit;
969 }
970
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 {
972 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800973 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800975 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 lStatus = BAD_VALUE;
977 goto Exit;
978 }
979
Eric Laurent21da6472017-11-09 16:29:26 -0800980 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981
Glenn Kastene848bd92014-03-13 15:00:32 -0700982 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800983 // check if an effect chain with the same session ID is present on another
984 // output thread and move it here.
985 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
986 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
987 if (mPlaybackThreads.keyAt(i) != output.outputId) {
988 uint32_t sessions = t->hasAudioSession(sessionId);
989 if (sessions & ThreadBase::EFFECT_SESSION) {
990 effectThread = t.get();
991 break;
Eric Laurentde070132010-07-13 04:45:46 -0700992 }
993 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994 }
Eric Laurent21da6472017-11-09 16:29:26 -0800995 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996
Eric Laurent21da6472017-11-09 16:29:26 -0800997 output.sampleRate = input.config.sample_rate;
998 output.frameCount = input.frameCount;
999 output.notificationFrameCount = input.notificationFrameCount;
1000 output.flags = input.flags;
Andy Hunga2159aa2021-07-20 13:01:52 -07001001 output.streamType = streamType;
Eric Laurent21da6472017-11-09 16:29:26 -08001002
Eric Laurent42984412019-05-09 17:57:03 -07001003 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001004 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -08001005 &output.frameCount, &output.notificationFrameCount,
1006 input.notificationsPerBuffer, input.speed,
1007 input.sharedBuffer, sessionId, &output.flags,
Svet Ganov33761132021-05-13 22:51:08 +00001008 callingPid, adjAttributionSource, input.clientInfo.clientTid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001009 &lStatus, portId, input.audioTrackCallback);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001010 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -07001011 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -07001012
Eric Laurent21da6472017-11-09 16:29:26 -08001013 output.afFrameCount = thread->frameCount();
1014 output.afSampleRate = thread->sampleRate();
1015 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -08001016 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -08001017
Kevin Rocard153f92d2018-12-18 18:33:28 -08001018 if (lStatus == NO_ERROR) {
1019 // Connect secondary outputs. Failure on a secondary output must not imped the primary
1020 // Any secondary output setup failure will lead to a desync between the AP and AF until
1021 // the track is destroyed.
jiabinf042b9b2021-05-07 23:46:28 +00001022 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001023 }
1024
Eric Laurent39e94f82010-07-28 01:32:47 -07001025 // move effect chain to this output thread if an effect on same session was waiting
1026 // for a track to be created
1027 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -07001028 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -07001029 Mutex::Autolock _dl(thread->mLock);
1030 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07001031 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
1032 effectThreadId = thread->id();
1033 effectIds = thread->getEffectIds_l(sessionId);
1034 }
Eric Laurent39e94f82010-07-28 01:32:47 -07001035 }
Eric Laurenta011e352012-03-29 15:51:43 -07001036
1037 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001038 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -08001039 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -07001040 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -07001041 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07001042 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -07001043 } else {
1044 mPendingSyncEvents[i]->cancel();
1045 }
Eric Laurenta011e352012-03-29 15:51:43 -07001046 mPendingSyncEvents.removeAt(i);
1047 i--;
1048 }
1049 }
1050 }
Andy Hung6eff0ff2021-07-30 19:01:48 -07001051 if ((output.flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
1052 setAudioHwSyncForSession_l(thread, sessionId);
1053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 }
Glenn Kastene198c362013-08-13 09:13:36 -07001055
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001056 if (lStatus != NO_ERROR) {
1057 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001058 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001059 // Don't hold mClientLock when releasing the reference on the track as the
1060 // destructor will acquire it.
1061 {
1062 Mutex::Autolock _cl(mClientLock);
1063 client.clear();
1064 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001066 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068
Eric Laurent6c796322019-04-09 14:13:17 -07001069 // effectThreadId is not NONE if an effect chain corresponding to the track session
1070 // was found on another thread and must be moved on this thread
1071 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1072 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1073 }
1074
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001075 output.audioTrack = new TrackHandle(track);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001076 _output = VALUE_OR_FATAL(output.toAidl());
1077
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001079 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001080 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001081 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001082 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083}
1084
Glenn Kasten2c073da2016-02-26 09:14:08 -08001085uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086{
1087 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001088 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001090 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 return 0;
1092 }
1093 return thread->sampleRate();
1094}
1095
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001096audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097{
1098 Mutex::Autolock _l(mLock);
1099 PlaybackThread *thread = checkPlaybackThread_l(output);
1100 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001101 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001102 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 }
1104 return thread->format();
1105}
1106
Glenn Kasten2c073da2016-02-26 09:14:08 -08001107size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108{
1109 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001110 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001112 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 return 0;
1114 }
Glenn Kasten58912562012-04-03 10:45:00 -07001115 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1116 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 return thread->frameCount();
1118}
1119
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001120size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1121{
1122 Mutex::Autolock _l(mLock);
1123 ThreadBase *thread = checkThread_l(ioHandle);
1124 if (thread == NULL) {
1125 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1126 return 0;
1127 }
1128 return thread->frameCountHAL();
1129}
1130
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001131uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132{
1133 Mutex::Autolock _l(mLock);
1134 PlaybackThread *thread = checkPlaybackThread_l(output);
1135 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001136 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 return 0;
1138 }
1139 return thread->latency();
1140}
1141
1142status_t AudioFlinger::setMasterVolume(float value)
1143{
Eric Laurenta1884f92011-08-23 08:25:03 -07001144 status_t ret = initCheck();
1145 if (ret != NO_ERROR) {
1146 return ret;
1147 }
1148
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149 // check calling permissions
1150 if (!settingsAllowed()) {
1151 return PERMISSION_DENIED;
1152 }
1153
Eric Laurenta4c5a552012-03-29 10:12:40 -07001154 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001155 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001156
John Grossmanee578c02012-07-23 17:05:46 -07001157 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001158 {
John Grossmanee578c02012-07-23 17:05:46 -07001159 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001160 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1161 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001162
Eric Laurent00abf0d2020-04-22 19:28:22 -07001163 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1164 if (dev->canSetMasterVolume()) {
1165 dev->hwDevice()->setMasterVolume(value);
1166 }
1167 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 }
John Grossmanee578c02012-07-23 17:05:46 -07001170 // Now set the master volume in each playback thread. Playback threads
1171 // assigned to HALs which do not have master volume support will apply
1172 // master volume during the mix operation. Threads with HALs which do
1173 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001174 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1175 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1176 continue;
1177 }
John Grossmanee578c02012-07-23 17:05:46 -07001178 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001179 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180
1181 return NO_ERROR;
1182}
1183
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001184status_t AudioFlinger::setMasterBalance(float balance)
1185{
1186 status_t ret = initCheck();
1187 if (ret != NO_ERROR) {
1188 return ret;
1189 }
1190
1191 // check calling permissions
1192 if (!settingsAllowed()) {
1193 return PERMISSION_DENIED;
1194 }
1195
1196 // check range
1197 if (isnan(balance) || fabs(balance) > 1.f) {
1198 return BAD_VALUE;
1199 }
1200
1201 Mutex::Autolock _l(mLock);
1202
1203 // short cut.
1204 if (mMasterBalance == balance) return NO_ERROR;
1205
1206 mMasterBalance = balance;
1207
1208 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1209 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1210 continue;
1211 }
1212 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1213 }
1214
1215 return NO_ERROR;
1216}
1217
Glenn Kastenf78aee72012-01-04 11:00:47 -08001218status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219{
Eric Laurenta1884f92011-08-23 08:25:03 -07001220 status_t ret = initCheck();
1221 if (ret != NO_ERROR) {
1222 return ret;
1223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224
1225 // check calling permissions
1226 if (!settingsAllowed()) {
1227 return PERMISSION_DENIED;
1228 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001229 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001230 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 return BAD_VALUE;
1232 }
1233
1234 { // scope for the lock
1235 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001236 if (mPrimaryHardwareDev == nullptr) {
1237 return INVALID_OPERATION;
1238 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001239 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001241 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 mHardwareStatus = AUDIO_HW_IDLE;
1243 }
1244
1245 if (NO_ERROR == ret) {
1246 Mutex::Autolock _l(mLock);
1247 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001248 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001249 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250 }
1251
Joey Poomarin52989982020-03-05 17:40:49 +08001252 mediametrics::LogItem(mMetricsId)
1253 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1254 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1255 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 return ret;
1257}
1258
1259status_t AudioFlinger::setMicMute(bool state)
1260{
Eric Laurenta1884f92011-08-23 08:25:03 -07001261 status_t ret = initCheck();
1262 if (ret != NO_ERROR) {
1263 return ret;
1264 }
1265
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266 // check calling permissions
1267 if (!settingsAllowed()) {
1268 return PERMISSION_DENIED;
1269 }
1270
1271 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001272 if (mPrimaryHardwareDev == nullptr) {
1273 return INVALID_OPERATION;
1274 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001275 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1276 if (primaryDev == nullptr) {
1277 ALOGW("%s: no primary HAL device", __func__);
1278 return INVALID_OPERATION;
1279 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001281 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001282 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001283 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001284 if (dev != primaryDev) {
1285 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001286 }
1287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001289 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290 return ret;
1291}
1292
1293bool AudioFlinger::getMicMute() const
1294{
Eric Laurenta1884f92011-08-23 08:25:03 -07001295 status_t ret = initCheck();
1296 if (ret != NO_ERROR) {
1297 return false;
1298 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001299 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001300 if (mPrimaryHardwareDev == nullptr) {
1301 return false;
1302 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001303 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1304 if (primaryDev == nullptr) {
1305 ALOGW("%s: no primary HAL device", __func__);
1306 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001307 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001308 bool state;
1309 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1310 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001311 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001312 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1313 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001314}
1315
Eric Laurent5ada82e2019-08-29 17:53:54 -07001316void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001317{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001318 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001319
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001320 AutoMutex lock(mLock);
1321 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001322 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001323 }
1324 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001325 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001326 }
1327}
1328
Mathias Agopian65ab4712010-07-14 17:59:35 -07001329status_t AudioFlinger::setMasterMute(bool muted)
1330{
John Grossmand8f178d2012-07-20 14:51:35 -07001331 status_t ret = initCheck();
1332 if (ret != NO_ERROR) {
1333 return ret;
1334 }
1335
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336 // check calling permissions
1337 if (!settingsAllowed()) {
1338 return PERMISSION_DENIED;
1339 }
1340
John Grossmanee578c02012-07-23 17:05:46 -07001341 Mutex::Autolock _l(mLock);
1342 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001343
John Grossmanee578c02012-07-23 17:05:46 -07001344 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001345 {
John Grossmanee578c02012-07-23 17:05:46 -07001346 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001347 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1348 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001349
Eric Laurent00abf0d2020-04-22 19:28:22 -07001350 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1351 if (dev->canSetMasterMute()) {
1352 dev->hwDevice()->setMasterMute(muted);
1353 }
1354 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001355 }
John Grossmand8f178d2012-07-20 14:51:35 -07001356 }
1357
John Grossmanee578c02012-07-23 17:05:46 -07001358 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001359 // assigned to HALs which do not have master mute support will apply master mute
1360 // during the mix operation. Threads with HALs which do support master mute
1361 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001362 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1363 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1364 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366
1367 return NO_ERROR;
1368}
1369
1370float AudioFlinger::masterVolume() const
1371{
Glenn Kasten98067102011-12-13 11:47:54 -08001372 Mutex::Autolock _l(mLock);
1373 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374}
1375
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001376status_t AudioFlinger::getMasterBalance(float *balance) const
1377{
1378 Mutex::Autolock _l(mLock);
1379 *balance = getMasterBalance_l();
1380 return NO_ERROR; // if called through binder, may return a transactional error
1381}
1382
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383bool AudioFlinger::masterMute() const
1384{
Glenn Kasten98067102011-12-13 11:47:54 -08001385 Mutex::Autolock _l(mLock);
1386 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387}
1388
John Grossman4ff14ba2012-02-08 16:37:41 -08001389float AudioFlinger::masterVolume_l() const
1390{
John Grossman4ff14ba2012-02-08 16:37:41 -08001391 return mMasterVolume;
1392}
1393
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001394float AudioFlinger::getMasterBalance_l() const
1395{
1396 return mMasterBalance;
1397}
1398
John Grossmand8f178d2012-07-20 14:51:35 -07001399bool AudioFlinger::masterMute_l() const
1400{
John Grossmanee578c02012-07-23 17:05:46 -07001401 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001402}
1403
Eric Laurent223fd5c2014-11-11 13:43:36 -08001404status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1405{
1406 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001407 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001408 return BAD_VALUE;
1409 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001410 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1411 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1412 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001413 return PERMISSION_DENIED;
1414 }
1415
1416 return NO_ERROR;
1417}
1418
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001419status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1420 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421{
1422 // check calling permissions
1423 if (!settingsAllowed()) {
1424 return PERMISSION_DENIED;
1425 }
1426
Eric Laurent223fd5c2014-11-11 13:43:36 -08001427 status_t status = checkStreamType(stream);
1428 if (status != NO_ERROR) {
1429 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001430 }
Eric Laurent98e38192018-02-15 18:31:53 -08001431 if (output == AUDIO_IO_HANDLE_NONE) {
1432 return BAD_VALUE;
1433 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001434 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1435 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436
1437 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001438 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1439 if (volumeInterface == NULL) {
1440 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441 }
Eric Laurent98e38192018-02-15 18:31:53 -08001442 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443
1444 return NO_ERROR;
1445}
1446
Glenn Kastenfff6d712012-01-12 16:38:12 -08001447status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448{
1449 // check calling permissions
1450 if (!settingsAllowed()) {
1451 return PERMISSION_DENIED;
1452 }
1453
Eric Laurent223fd5c2014-11-11 13:43:36 -08001454 status_t status = checkStreamType(stream);
1455 if (status != NO_ERROR) {
1456 return status;
1457 }
1458 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1459
1460 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001461 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001462 return BAD_VALUE;
1463 }
1464
Eric Laurent93575202011-01-18 18:39:02 -08001465 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001467 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1468 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1469 volumeInterfaces[i]->setStreamMute(stream, muted);
1470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471
1472 return NO_ERROR;
1473}
1474
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001475float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001477 status_t status = checkStreamType(stream);
1478 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 return 0.0f;
1480 }
Eric Laurent98e38192018-02-15 18:31:53 -08001481 if (output == AUDIO_IO_HANDLE_NONE) {
1482 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 }
1484
Eric Laurent98e38192018-02-15 18:31:53 -08001485 AutoMutex lock(mLock);
1486 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1487 if (volumeInterface == NULL) {
1488 return 0.0f;
1489 }
1490
1491 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492}
1493
Glenn Kastenfff6d712012-01-12 16:38:12 -08001494bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001496 status_t status = checkStreamType(stream);
1497 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498 return true;
1499 }
1500
Glenn Kasten6637baa2012-01-09 09:40:36 -08001501 AutoMutex lock(mLock);
1502 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503}
1504
Eric Laurent054d9d32015-04-24 08:48:48 -07001505
Andy Hungd9ef4b12020-11-11 15:13:18 -08001506void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
Eric Laurent054d9d32015-04-24 08:48:48 -07001507{
1508 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1509 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1510 }
1511}
1512
jiabinc52b1ff2019-10-31 17:20:42 -07001513void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1514{
1515 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1516 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1517 }
1518}
1519
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001520// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1521void AudioFlinger::forwardParametersToDownstreamPatches_l(
1522 audio_io_handle_t upStream, const String8& keyValuePairs,
1523 std::function<bool(const sp<PlaybackThread>&)> useThread)
1524{
1525 std::vector<PatchPanel::SoftwarePatch> swPatches;
1526 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1527 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1528 __func__, swPatches.size(), upStream);
1529 for (const auto& swPatch : swPatches) {
1530 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1531 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1532 downStream->setParameters(keyValuePairs);
1533 }
1534 }
1535}
1536
Eric Laurent74c38dc2020-12-23 18:19:44 +01001537// Update downstream patches for all playback threads attached to an MSD module
1538void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
1539 const std::set<audio_io_handle_t> streams)
1540{
1541 for (const audio_io_handle_t stream : streams) {
1542 PlaybackThread *playbackThread = checkPlaybackThread_l(stream);
1543 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1544 continue;
1545 }
1546 playbackThread->setDownStreamPatch(patch);
1547 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1548 }
1549}
1550
Eric Laurentf1047e82018-04-16 19:18:20 -07001551// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1552// Some keys are used for audio routing and audio path configuration and should be reserved for use
1553// by audio policy and audio flinger for functional, privacy and security reasons.
1554void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1555{
1556 static const String8 kReservedParameters[] = {
1557 String8(AudioParameter::keyRouting),
1558 String8(AudioParameter::keySamplingRate),
1559 String8(AudioParameter::keyFormat),
1560 String8(AudioParameter::keyChannels),
1561 String8(AudioParameter::keyFrameCount),
1562 String8(AudioParameter::keyInputSource),
1563 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001564 String8(AudioParameter::keyDeviceConnect),
1565 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001566 String8(AudioParameter::keyStreamSupportedFormats),
1567 String8(AudioParameter::keyStreamSupportedChannels),
1568 String8(AudioParameter::keyStreamSupportedSamplingRates),
1569 };
1570
Andy Hung4ef19fa2018-05-15 19:35:29 -07001571 if (isAudioServerUid(callingUid)) {
1572 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001573 }
1574
1575 AudioParameter param = AudioParameter(keyValuePairs);
1576 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001577 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001578 for (auto& key : kReservedParameters) {
1579 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001580 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001581 param.remove(key);
1582 }
1583 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001584 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1585 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001586 keyValuePairs = param.toString();
1587}
1588
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001589void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1590 size_t rejectedKVPSize, const String8& rejectedKVPs,
1591 uid_t callingUid) {
1592 auto prefix = String8::format("UID %5d", callingUid);
1593 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1594 if (rejectedKVPSize != 0) {
1595 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1596 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1597 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1598 } else {
1599 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1600 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1601 }
1602}
1603
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001604status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605{
Eric Laurentf1047e82018-04-16 19:18:20 -07001606 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1607 ioHandle, keyValuePairs.string(),
1608 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001609
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 // check calling permissions
1611 if (!settingsAllowed()) {
1612 return PERMISSION_DENIED;
1613 }
1614
Eric Laurentf1047e82018-04-16 19:18:20 -07001615 String8 filteredKeyValuePairs = keyValuePairs;
1616 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1617
1618 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1619
Glenn Kasten142f5192014-03-25 17:44:59 -07001620 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1621 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001622 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001623 // result will remain NO_INIT if no audio device is present
1624 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001625 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001626 AutoMutex lock(mHardwareLock);
1627 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1628 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001629 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001630 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001631 // return success if at least one audio device accepts the parameters as not all
1632 // HALs are requested to support all parameters. If no audio device supports the
1633 // requested parameters, the last error is reported.
1634 if (final_result != NO_ERROR) {
1635 final_result = result;
1636 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001637 }
1638 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001639 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001640 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001641 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001642 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001643 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1644 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001645 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001646 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001647 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001648 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001649 }
1650 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001651 String8 screenState;
1652 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001653 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001654 if (isOff != (AudioFlinger::mScreenState & 1)) {
1655 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001656 }
1657 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001658 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 }
1660
1661 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1662 // and the thread is exited once the lock is released
1663 sp<ThreadBase> thread;
1664 {
1665 Mutex::Autolock _l(mLock);
1666 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001667 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001669 if (thread == 0) {
1670 thread = checkMmapThread_l(ioHandle);
1671 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001672 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001673 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001674 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001675 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001676 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1677 (value != 0)) {
Andy Hungd9ef4b12020-11-11 15:13:18 -08001678 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 }
1681 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001682 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001683 status_t result = thread->setParameters(filteredKeyValuePairs);
1684 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1685 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 }
1687 return BAD_VALUE;
1688}
1689
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001690String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001692 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1693 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694
Eric Laurenta4c5a552012-03-29 10:12:40 -07001695 Mutex::Autolock _l(mLock);
1696
Glenn Kasten142f5192014-03-25 17:44:59 -07001697 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001698 String8 out_s8;
1699
Eric Laurent00abf0d2020-04-22 19:28:22 -07001700 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001701 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001702 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001703 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001704 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07001705 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001706 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001707 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001708 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001709 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 }
1711
Eric Laurent6acd1d42017-01-04 14:23:29 -08001712 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1713 if (thread == NULL) {
1714 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1715 if (thread == NULL) {
1716 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1717 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001718 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001719 }
1720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001722 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723}
1724
Glenn Kastendd8104c2012-07-02 12:42:44 -07001725size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1726 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727{
Eric Laurenta1884f92011-08-23 08:25:03 -07001728 status_t ret = initCheck();
1729 if (ret != NO_ERROR) {
1730 return 0;
1731 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001732 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001733 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001734 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001735 return 0;
1736 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001737
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001738 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001739 if (mPrimaryHardwareDev == nullptr) {
1740 return 0;
1741 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001742 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001743
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001744 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001745 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1746 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1747 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1748 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1749 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1750
1751 std::vector<audio_format_t> formats = {format};
1752 if (format != AUDIO_FORMAT_PCM_16_BIT)
1753 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1754
1755 std::vector<uint32_t> sampleRates = {sampleRate};
1756 static const uint32_t SR_44100 = 44100;
1757 static const uint32_t SR_48000 = 48000;
1758
1759 if (sampleRate != SR_48000)
1760 sampleRates.push_back(SR_48000);
1761 if (sampleRate != SR_44100)
1762 sampleRates.push_back(SR_44100);
1763
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001764 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001765
Robin Lee9899ff72019-12-24 22:02:08 +01001766 // Change parameters of the configuration each iteration until we find a
1767 // configuration that the device will support.
1768 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001769 for (auto testChannelMask : channelMasks) {
1770 config.channel_mask = testChannelMask;
1771 for (auto testFormat : formats) {
1772 config.format = testFormat;
1773 for (auto testSampleRate : sampleRates) {
1774 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001775
Judy Hsiaoabab5222019-11-09 18:14:58 +08001776 size_t bytes = 0;
1777 status_t result = dev->getInputBufferSize(&config, &bytes);
1778 if (result != OK || bytes == 0) {
1779 continue;
1780 }
1781
1782 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1783 config.format != format) {
1784 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1785 uint32_t srcChannelCount =
1786 audio_channel_count_from_in_mask(config.channel_mask);
1787 size_t srcFrames =
1788 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1789 size_t dstFrames = destinationFramesPossible(
1790 srcFrames, config.sample_rate, sampleRate);
1791 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1792 }
1793 return bytes;
1794 }
1795 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001796 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001797
1798 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1799 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1800 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801}
1802
Glenn Kasten5f972c02014-01-13 09:59:31 -08001803uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 Mutex::Autolock _l(mLock);
1806
1807 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1808 if (recordThread != NULL) {
1809 return recordThread->getInputFramesLost();
1810 }
1811 return 0;
1812}
1813
1814status_t AudioFlinger::setVoiceVolume(float value)
1815{
Eric Laurenta1884f92011-08-23 08:25:03 -07001816 status_t ret = initCheck();
1817 if (ret != NO_ERROR) {
1818 return ret;
1819 }
1820
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 // check calling permissions
1822 if (!settingsAllowed()) {
1823 return PERMISSION_DENIED;
1824 }
1825
1826 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001827 if (mPrimaryHardwareDev == nullptr) {
1828 return INVALID_OPERATION;
1829 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001830 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001831 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001832 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 mHardwareStatus = AUDIO_HW_IDLE;
1834
Joey Poomarin52989982020-03-05 17:40:49 +08001835 mediametrics::LogItem(mMetricsId)
1836 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
1837 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
1838 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 return ret;
1840}
1841
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001842status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001843 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 Mutex::Autolock _l(mLock);
1846
1847 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1848 if (playbackThread != NULL) {
1849 return playbackThread->getRenderPosition(halFrames, dspFrames);
1850 }
1851
1852 return BAD_VALUE;
1853}
1854
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001855void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001858 if (client == 0) {
1859 return;
1860 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001861 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001862 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001863 {
1864 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001865 if (mNotificationClients.indexOfKey(pid) < 0) {
1866 sp<NotificationClient> notificationClient = new NotificationClient(this,
1867 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001868 pid,
1869 uid);
1870 ALOGV("registerClient() client %p, pid %d, uid %u",
1871 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872
Eric Laurent021cf962014-05-13 10:18:14 -07001873 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874
Marco Nelissen06b46062014-11-14 07:58:25 -08001875 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001876 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001877 }
1878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879
Eric Laurent021cf962014-05-13 10:18:14 -07001880 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001881 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001882 // the config change is always sent from playback or record threads to avoid deadlock
1883 // with AudioSystem::gLock
1884 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001885 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001888 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001889 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890 }
1891}
1892
1893void AudioFlinger::removeNotificationClient(pid_t pid)
1894{
Eric Laurent6c796322019-04-09 14:13:17 -07001895 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001896 {
Eric Laurent6c796322019-04-09 14:13:17 -07001897 Mutex::Autolock _l(mLock);
1898 {
1899 Mutex::Autolock _cl(mClientLock);
1900 mNotificationClients.removeItem(pid);
1901 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001902
Eric Laurent6c796322019-04-09 14:13:17 -07001903 ALOGV("%d died, releasing its sessions", pid);
1904 size_t num = mAudioSessionRefs.size();
1905 bool removed = false;
1906 for (size_t i = 0; i < num; ) {
1907 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1908 ALOGV(" pid %d @ %zu", ref->mPid, i);
1909 if (ref->mPid == pid) {
1910 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1911 mAudioSessionRefs.removeAt(i);
1912 delete ref;
1913 removed = true;
1914 num--;
1915 } else {
1916 i++;
1917 }
1918 }
1919 if (removed) {
1920 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001921 }
1922 }
Eric Laurent6c796322019-04-09 14:13:17 -07001923 for (auto& effect : removedEffects) {
1924 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001925 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926}
1927
Mikhail Naganov88536df2021-07-26 17:30:29 -07001928void AudioFlinger::ioConfigChanged(audio_io_config_event_t event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001929 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001930 pid_t pid) {
Andy Hungb75b6242021-07-29 16:46:14 +00001931 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
1932 legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07001933 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
1934 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001935
Eric Laurent021cf962014-05-13 10:18:14 -07001936 Mutex::Autolock _l(mClientLock);
1937 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001939 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001940 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(eventAidl,
1941 descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001942 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 }
1944}
1945
Eric Laurent021cf962014-05-13 10:18:14 -07001946// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947void AudioFlinger::removeClient_l(pid_t pid)
1948{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001949 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001950 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 mClients.removeItem(pid);
1952}
1953
Eric Laurent717e1282012-06-29 16:36:52 -07001954// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001955sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1956 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001957{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001958 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001959
1960 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001961 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001962 ALOG_ASSERT(thread == 0);
1963 thread = mPlaybackThreads.valueAt(i);
1964 }
1965 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001966 if (thread != nullptr) {
1967 return thread;
1968 }
1969 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1970 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1971 ALOG_ASSERT(thread == 0);
1972 thread = mRecordThreads.valueAt(i);
1973 }
1974 }
1975 if (thread != nullptr) {
1976 return thread;
1977 }
1978 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1979 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1980 ALOG_ASSERT(thread == 0);
1981 thread = mMmapThreads.valueAt(i);
1982 }
1983 }
Eric Laurent717e1282012-06-29 16:36:52 -07001984 return thread;
1985}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988
1989// ----------------------------------------------------------------------------
1990
1991AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1992 : RefBase(),
1993 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001994 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995{
Andy Hung6f248bb2018-01-23 14:04:37 -08001996 mMemoryDealer = new MemoryDealer(
1997 audioFlinger->getClientSharedHeapSize(),
1998 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999}
2000
Eric Laurent021cf962014-05-13 10:18:14 -07002001// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002AudioFlinger::Client::~Client()
2003{
2004 mAudioFlinger->removeClient_l(mPid);
2005}
2006
Glenn Kasten435dbe62012-01-30 10:15:48 -08002007sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008{
2009 return mMemoryDealer;
2010}
2011
2012// ----------------------------------------------------------------------------
2013
2014AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002015 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08002016 pid_t pid,
2017 uid_t uid)
2018 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019{
2020}
2021
2022AudioFlinger::NotificationClient::~NotificationClient()
2023{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024}
2025
Glenn Kasten0f11b512014-01-31 16:18:54 -08002026void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027{
2028 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08002029 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030}
2031
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002032// ----------------------------------------------------------------------------
2033AudioFlinger::MediaLogNotifier::MediaLogNotifier()
2034 : mPendingRequests(false) {}
2035
2036
2037void AudioFlinger::MediaLogNotifier::requestMerge() {
2038 AutoMutex _l(mMutex);
2039 mPendingRequests = true;
2040 mCond.signal();
2041}
2042
2043bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002044 // Should already have been checked, but just in case
2045 if (sMediaLogService == 0) {
2046 return false;
2047 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002048 // Wait until there are pending requests
2049 {
2050 AutoMutex _l(mMutex);
2051 mPendingRequests = false; // to ignore past requests
2052 while (!mPendingRequests) {
2053 mCond.wait(mMutex);
2054 // TODO may also need an exitPending check
2055 }
2056 mPendingRequests = false;
2057 }
2058 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002059 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002060 usleep(kPostTriggerSleepPeriod);
2061 return true;
2062}
2063
2064void AudioFlinger::requestLogMerge() {
2065 mMediaLogNotifier->requestMerge();
2066}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067
2068// ----------------------------------------------------------------------------
2069
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002070status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2071 media::CreateRecordResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072{
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002073 CreateRecordInput input = VALUE_OR_RETURN_STATUS(CreateRecordInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002074 CreateRecordOutput output;
2075
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 sp<RecordThread::RecordTrack> recordTrack;
2077 sp<RecordHandle> recordHandle;
2078 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002080 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002081 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082
Eric Laurentf14db3c2017-12-08 14:20:36 -08002083 output.cblk.clear();
2084 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002085 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002086
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002087 // TODO b/182392553: refactor or clean up
Svet Ganov33761132021-05-13 22:51:08 +00002088 AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource;
2089 bool updatePid = (adjAttributionSource.pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002090 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Svet Ganov33761132021-05-13 22:51:08 +00002091 const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(
2092 adjAttributionSource.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -07002093 if (!isAudioServerOrMediaServerUid(callingUid)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002094 ALOGW_IF(currentUid != callingUid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002095 "%s uid %d tried to pass itself off as %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002096 __FUNCTION__, callingUid, currentUid);
Svet Ganov33761132021-05-13 22:51:08 +00002097 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002098 updatePid = true;
2099 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07002100 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Svet Ganov33761132021-05-13 22:51:08 +00002101 const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
2102 adjAttributionSource.pid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002103 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002104 ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002105 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002106 __func__, callingUid, callingPid, currentPid);
Svet Ganov33761132021-05-13 22:51:08 +00002107 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Marco Nelissendcb346b2015-09-09 10:47:29 -07002108 }
2109
Andy Hung6770c6f2015-04-07 13:43:36 -07002110 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08002111 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2112 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002113 lStatus = BAD_VALUE;
2114 goto Exit;
2115 }
2116
Glenn Kasten53b5d092014-02-05 10:00:23 -08002117 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002118 if (!audio_is_input_channel(input.config.channel_mask)) {
2119 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002120 lStatus = BAD_VALUE;
2121 goto Exit;
2122 }
2123
Eric Laurentf14db3c2017-12-08 14:20:36 -08002124 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2125 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2126 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2127 lStatus = BAD_VALUE;
2128 goto Exit;
2129 }
2130
2131 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002132 output.selectedDeviceId = input.selectedDeviceId;
2133 output.flags = input.flags;
2134
Svet Ganov33761132021-05-13 22:51:08 +00002135 client = registerPid(VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid)));
Eric Laurentf14db3c2017-12-08 14:20:36 -08002136
2137 // Not a conventional loop, but a retry loop for at most two iterations total.
2138 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2139 // Exits loop via break on no error of got exit on error
2140 // The sp<> references will be dropped when re-entering scope.
2141 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2142 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002143 // release previously opened input if retrying.
2144 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2145 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002146 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002147 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002148 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002149 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002150 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002151 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002152 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002153 sessionId,
2154 // FIXME compare to AudioTrack
Svet Ganov33761132021-05-13 22:51:08 +00002155 adjAttributionSource,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002156 &input.config,
2157 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002158 if (lStatus != NO_ERROR) {
2159 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2160 goto Exit;
2161 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002162
Glenn Kasten05997e22014-03-13 15:08:33 -07002163 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002165 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002167 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2168 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 goto Exit;
2170 }
2171
Eric Laurentf14db3c2017-12-08 14:20:36 -08002172 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173
Eric Laurentf14db3c2017-12-08 14:20:36 -08002174 output.sampleRate = input.config.sample_rate;
2175 output.frameCount = input.frameCount;
2176 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002177
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002178 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002179 input.config.format, input.config.channel_mask,
2180 &output.frameCount, sessionId,
2181 &output.notificationFrameCount,
Svet Ganov33761132021-05-13 22:51:08 +00002182 callingPid, adjAttributionSource, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002183 input.clientInfo.clientTid,
Eric Laurentec376dc2021-04-08 20:41:22 +02002184 &lStatus, portId, input.maxSharedAudioHistoryMs);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002185 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002186
Eric Laurentf14db3c2017-12-08 14:20:36 -08002187 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2188 // audio policy manager without FAST constraint
2189 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002190 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002191 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002192
2193 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002194 goto Exit;
2195 }
2196
jiabinb00edc32021-08-16 16:27:54 +00002197 if (recordTrack->isFastTrack()) {
2198 output.serverConfig = {
2199 thread->sampleRate(),
2200 thread->channelMask(),
2201 thread->format()
2202 };
2203 } else {
2204 output.serverConfig = {
2205 recordTrack->sampleRate(),
2206 recordTrack->channelMask(),
2207 recordTrack->format()
2208 };
2209 }
2210
Eric Laurentf14db3c2017-12-08 14:20:36 -08002211 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2212 // session and move it to this thread.
2213 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2214 if (chain != 0) {
2215 Mutex::Autolock _l(thread->mLock);
2216 thread->addEffectChain_l(chain);
2217 }
2218 break;
2219 }
2220 // End of retry loop.
2221 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 }
Glenn Kastene198c362013-08-13 09:13:36 -07002223
Eric Laurentf14db3c2017-12-08 14:20:36 -08002224 output.cblk = recordTrack->getCblk();
2225 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002226 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002227
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002228 output.audioRecord = new RecordHandle(recordTrack);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002229 _output = VALUE_OR_FATAL(output.toAidl());
2230
Eric Laurentf14db3c2017-12-08 14:20:36 -08002231Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002232 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002233 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002234 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002235 // Don't hold mClientLock when releasing the reference on the track as the
2236 // destructor will acquire it.
2237 {
2238 Mutex::Autolock _cl(mClientLock);
2239 client.clear();
2240 }
Eric Laurent896c9672017-12-08 14:08:45 -08002241 recordTrack.clear();
2242 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002243 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 }
2246
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002247 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248}
2249
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002250
2251
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252// ----------------------------------------------------------------------------
2253
Eric Laurenta4c5a552012-03-29 10:12:40 -07002254audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2255{
Eric Laurent44622db2014-08-01 19:00:33 -07002256 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002257 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002258 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002259 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002260 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002261 }
2262 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002263 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002264 return loadHwModule_l(name);
2265}
2266
Eric Laurent00abf0d2020-04-22 19:28:22 -07002267// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002268audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2269{
2270 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2271 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2272 ALOGW("loadHwModule() module %s already loaded", name);
2273 return mAudioHwDevs.keyAt(i);
2274 }
2275 }
2276
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002277 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002278
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002279 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002280 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002281 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002282 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002283 }
2284
2285 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002286 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002287 mHardwareStatus = AUDIO_HW_IDLE;
2288 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002289 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002290 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002291 }
2292
John Grossmanee578c02012-07-23 17:05:46 -07002293 // Check and cache this HAL's level of support for master mute and master
2294 // volume. If this is the first HAL opened, and it supports the get
2295 // methods, use the initial values provided by the HAL as the current
2296 // master mute and volume settings.
2297
2298 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002299 if (0 == mAudioHwDevs.size()) {
2300 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2301 float mv;
2302 if (OK == dev->getMasterVolume(&mv)) {
2303 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002304 }
2305
Eric Laurent00abf0d2020-04-22 19:28:22 -07002306 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2307 bool mm;
2308 if (OK == dev->getMasterMute(&mm)) {
2309 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002310 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002311 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002312
2313 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2314 if (OK == dev->setMasterVolume(mMasterVolume)) {
2315 flags = static_cast<AudioHwDevice::Flags>(flags |
2316 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2317 }
2318
2319 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2320 if (OK == dev->setMasterMute(mMasterMute)) {
2321 flags = static_cast<AudioHwDevice::Flags>(flags |
2322 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2323 }
2324
2325 mHardwareStatus = AUDIO_HW_IDLE;
2326
Mikhail Naganov97373b02018-07-23 13:27:24 -07002327 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002328 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2329 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2330 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002331
Glenn Kastena13cde92016-03-28 15:26:02 -07002332 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002333 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2334 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2335 mPrimaryHardwareDev = audioDevice;
2336 mHardwareStatus = AUDIO_HW_SET_MODE;
2337 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2338 mHardwareStatus = AUDIO_HW_IDLE;
2339 }
2340
jiabine504e7b2021-09-18 00:27:08 +00002341 if (mDevicesFactoryHal->getHalVersion() > MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION) {
2342 if (int32_t mixerBursts = dev->getAAudioMixerBurstCount();
2343 mixerBursts > mAAudioBurstsPerBuffer) {
2344 mAAudioBurstsPerBuffer = mixerBursts;
2345 }
2346 if (int32_t hwBurstMinMicros = dev->getAAudioHardwareBurstMinUsec();
2347 hwBurstMinMicros < mAAudioHwBurstMinMicros || mAAudioHwBurstMinMicros == 0) {
2348 mAAudioHwBurstMinMicros = hwBurstMinMicros;
2349 }
2350 }
2351
Eric Laurent00abf0d2020-04-22 19:28:22 -07002352 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002353
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002354 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002355
2356 return handle;
2357
2358}
2359
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002360// ----------------------------------------------------------------------------
2361
Glenn Kasten3b16c762012-11-14 08:44:39 -08002362uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002363{
2364 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002365 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002366 return thread != NULL ? thread->sampleRate() : 0;
2367}
2368
Glenn Kastene33054e2012-11-14 12:54:39 -08002369size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002370{
2371 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002372 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002373 return thread != NULL ? thread->frameCountHAL() : 0;
2374}
2375
2376// ----------------------------------------------------------------------------
2377
Andy Hung6f248bb2018-01-23 14:04:37 -08002378status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002379{
2380 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002381 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002382 return PERMISSION_DENIED;
2383 }
2384 Mutex::Autolock _l(mLock);
2385 if (mIsDeviceTypeKnown) {
2386 return INVALID_OPERATION;
2387 }
2388 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002389 mTotalMemory = totalMemory;
2390 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2391 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2392 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2393 // though actual setting is determined through device configuration.
2394 constexpr int64_t GB = 1024 * 1024 * 1024;
2395 mClientSharedHeapSize =
2396 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2397 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2398 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2399 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2400 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002401 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002402
2403 // TODO: Cache the client shared heap size in a persistent property.
2404 // It's possible that a native process or Java service or app accesses audioserver
2405 // after it is registered by system server, but before AudioService updates
2406 // the memory info. This would occur immediately after boot or an audioserver
2407 // crash and restore. Before update from AudioService, the client would get the
2408 // minimum heap size.
2409
2410 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2411 (isLowRamDevice ? "true" : "false"),
2412 (long long)mTotalMemory,
2413 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002414 return NO_ERROR;
2415}
2416
Andy Hung6f248bb2018-01-23 14:04:37 -08002417size_t AudioFlinger::getClientSharedHeapSize() const
2418{
2419 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2420 if (heapSizeInBytes != 0) { // read-only property overrides all.
2421 return heapSizeInBytes;
2422 }
2423 return mClientSharedHeapSize;
2424}
2425
Mikhail Naganovdea53042018-04-26 13:10:21 -07002426status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2427{
2428 ALOGV(__func__);
2429
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08002430 status_t status = AudioValidator::validateAudioPortConfig(*config);
2431 if (status != NO_ERROR) {
2432 return status;
2433 }
2434
Mikhail Naganovdea53042018-04-26 13:10:21 -07002435 audio_module_handle_t module;
2436 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2437 module = config->ext.device.hw_module;
2438 } else {
2439 module = config->ext.mix.hw_module;
2440 }
2441
2442 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002443 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002444 ssize_t index = mAudioHwDevs.indexOfKey(module);
2445 if (index < 0) {
2446 ALOGW("%s() bad hw module %d", __func__, module);
2447 return BAD_VALUE;
2448 }
2449
2450 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2451 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2452}
2453
Eric Laurent93c3d412014-08-01 14:48:35 -07002454audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2455{
2456 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002457
2458 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2459 if (index >= 0) {
2460 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2461 mHwAvSyncIds.valueAt(index), sessionId);
2462 return mHwAvSyncIds.valueAt(index);
2463 }
2464
Eric Laurent00abf0d2020-04-22 19:28:22 -07002465 sp<DeviceHalInterface> dev;
2466 {
2467 AutoMutex lock(mHardwareLock);
2468 if (mPrimaryHardwareDev == nullptr) {
2469 return AUDIO_HW_SYNC_INVALID;
2470 }
2471 dev = mPrimaryHardwareDev->hwDevice();
2472 }
2473 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002474 return AUDIO_HW_SYNC_INVALID;
2475 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002476 String8 reply;
2477 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002478 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002479 param = AudioParameter(reply);
2480 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002481
2482 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002483 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002484 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2485 return AUDIO_HW_SYNC_INVALID;
2486 }
2487
2488 // allow only one session for a given HW A/V sync ID.
2489 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2490 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2491 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2492 value, mHwAvSyncIds.keyAt(i));
2493 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002494 break;
2495 }
2496 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002497
2498 mHwAvSyncIds.add(sessionId, value);
2499
2500 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2501 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2502 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002503 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002504 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002505 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002506 String8 keyValuePairs = param.toString();
2507 thread->setParameters(keyValuePairs);
2508 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2509 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002510 break;
2511 }
2512 }
2513
2514 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2515 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002516}
2517
Eric Laurent72e3f392015-05-20 14:43:50 -07002518status_t AudioFlinger::systemReady()
2519{
2520 Mutex::Autolock _l(mLock);
2521 ALOGI("%s", __FUNCTION__);
2522 if (mSystemReady) {
2523 ALOGW("%s called twice", __FUNCTION__);
2524 return NO_ERROR;
2525 }
2526 mSystemReady = true;
2527 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2528 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2529 thread->systemReady();
2530 }
2531 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2532 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2533 thread->systemReady();
2534 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02002535 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2536 ThreadBase *thread = (ThreadBase *)mMmapThreads.valueAt(i).get();
2537 thread->systemReady();
2538 }
Eric Laurent72e3f392015-05-20 14:43:50 -07002539 return NO_ERROR;
2540}
2541
jiabin46a76fa2018-01-05 10:18:21 -08002542status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2543{
jiabin9ff780e2018-03-19 18:19:52 -07002544 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002545 status_t status = INVALID_OPERATION;
2546
2547 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2548 std::vector<media::MicrophoneInfo> mics;
2549 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2550 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2551 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2552 mHardwareStatus = AUDIO_HW_IDLE;
2553 if (devStatus == NO_ERROR) {
2554 microphones->insert(microphones->begin(), mics.begin(), mics.end());
2555 // report success if at least one HW module supports the function.
2556 status = NO_ERROR;
2557 }
2558 }
2559
jiabin9ff780e2018-03-19 18:19:52 -07002560 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002561}
2562
Eric Laurentfa90e842014-10-17 18:12:31 -07002563// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2564void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2565{
2566 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2567 if (index >= 0) {
2568 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2569 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2570 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002571 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002572 String8 keyValuePairs = param.toString();
2573 thread->setParameters(keyValuePairs);
2574 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2575 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002576 }
2577}
2578
2579
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002580// ----------------------------------------------------------------------------
2581
Eric Laurent83b88082014-06-20 18:31:16 -07002582
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002584 audio_io_handle_t *output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002585 audio_config_t *halConfig,
2586 audio_config_base_t *mixerConfig __unused,
jiabin43810402019-10-24 14:58:31 -07002587 audio_devices_t deviceType,
2588 const String8& address,
2589 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002590{
jiabin43810402019-10-24 14:58:31 -07002591 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002592 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002593 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002594 }
2595
Eric Laurentcf2c0212014-07-25 16:20:43 -07002596 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002597 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2598 } else {
2599 // Audio Policy does not currently request a specific output handle.
2600 // If this is ever needed, see openInput_l() for example code.
2601 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2602 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002603 }
Eric Laurent83b88082014-06-20 18:31:16 -07002604
2605 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2606
Eric Laurent83b88082014-06-20 18:31:16 -07002607 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002608 // This if statement allows overriding the audio policy settings
2609 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2610 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2611 // Check only for Normal Mixing mode
2612 if (kEnableExtendedPrecision) {
2613 // Specify format (uncomment one below to choose)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002614 //halConfig->format = AUDIO_FORMAT_PCM_FLOAT;
2615 //halConfig->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2616 //halConfig->format = AUDIO_FORMAT_PCM_32_BIT;
2617 //halConfig->format = AUDIO_FORMAT_PCM_8_24_BIT;
2618 // ALOGV("openOutput_l() upgrading format to %#08x", halConfig->format);
Andy Hung9a592762014-07-21 21:56:01 -07002619 }
2620 if (kEnableExtendedChannels) {
2621 // Specify channel mask (uncomment one below to choose)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002622 //halConfig->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2623 //halConfig->channel_mask = audio_channel_mask_from_representation_and_bits(
Andy Hung9a592762014-07-21 21:56:01 -07002624 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2625 }
Eric Laurent83b88082014-06-20 18:31:16 -07002626 }
2627
Phil Burk062e67a2015-02-11 13:40:50 -08002628 AudioStreamOut *outputStream = NULL;
2629 status_t status = outHwDev->openOutputStream(
2630 &outputStream,
2631 *output,
jiabin43810402019-10-24 14:58:31 -07002632 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002633 flags,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002634 halConfig,
Phil Burk062e67a2015-02-11 13:40:50 -08002635 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002636
2637 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002638
Phil Burk062e67a2015-02-11 13:40:50 -08002639 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002640 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2641 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002642 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002643 mMmapThreads.add(*output, thread);
2644 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2645 *output, thread.get());
2646 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002647 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002648 sp<PlaybackThread> thread;
Eric Laurentfa0f6742021-08-17 18:39:44 +02002649 //TODO: b/193496180 use spatializer flag at audio HAL when available
Eric Laurentb3f315a2021-07-13 15:09:05 +02002650 if (flags == (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_FAST
2651 | AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02002652 thread = new SpatializerThread(this, outputStream, *output,
Eric Laurentb3f315a2021-07-13 15:09:05 +02002653 mSystemReady, mixerConfig);
2654 ALOGD("openOutput_l() created virtualizer output: ID %d thread %p",
2655 *output, thread.get());
2656 } else if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002657 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002658 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2659 *output, thread.get());
2660 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002661 || !isValidPcmSinkFormat(halConfig->format)
2662 || !isValidPcmSinkChannelMask(halConfig->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002663 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002664 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2665 *output, thread.get());
2666 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002667 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002668 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2669 *output, thread.get());
2670 }
2671 mPlaybackThreads.add(*output, thread);
Eric Laurent74c38dc2020-12-23 18:19:44 +01002672 struct audio_patch patch;
2673 mPatchPanel.notifyStreamOpened(outHwDev, *output, &patch);
2674 if (thread->isMsdDevice()) {
2675 thread->setDownStreamPatch(&patch);
2676 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002677 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002678 }
Eric Laurent83b88082014-06-20 18:31:16 -07002679 }
2680
2681 return 0;
2682}
2683
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002684status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request,
2685 media::OpenOutputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686{
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002687 audio_module_handle_t module = VALUE_OR_RETURN_STATUS(
2688 aidl2legacy_int32_t_audio_module_handle_t(request.module));
Eric Laurentf1f22e72021-07-13 14:04:14 +02002689 audio_config_t halConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002690 aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/));
Eric Laurentf1f22e72021-07-13 14:04:14 +02002691 audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002692 aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002693 sp<DeviceDescriptorBase> device = VALUE_OR_RETURN_STATUS(
2694 aidl2legacy_DeviceDescriptorBase(request.device));
2695 audio_output_flags_t flags = VALUE_OR_RETURN_STATUS(
Andy Hung973638a2020-12-08 20:47:45 -08002696 aidl2legacy_int32_t_audio_output_flags_t_mask(request.flags));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002697
2698 audio_io_handle_t output;
2699 uint32_t latencyMs;
2700
jiabin43810402019-10-24 14:58:31 -07002701 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002702 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002703 this, module,
jiabin43810402019-10-24 14:58:31 -07002704 device->toString().c_str(),
Eric Laurentf1f22e72021-07-13 14:04:14 +02002705 halConfig.sample_rate,
2706 halConfig.format,
2707 halConfig.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002708 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709
jiabin43810402019-10-24 14:58:31 -07002710 audio_devices_t deviceType = device->type();
2711 const String8 address = String8(device->address().c_str());
2712
2713 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002714 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002716
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 Mutex::Autolock _l(mLock);
2718
Eric Laurentf1f22e72021-07-13 14:04:14 +02002719 sp<ThreadBase> thread = openOutput_l(module, &output, &halConfig,
2720 &mixerConfig, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002721 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002722 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2723 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002724 latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725
Eric Laurent6acd1d42017-01-04 14:23:29 -08002726 // notify client processes of the new output creation
2727 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002728
Eric Laurent00abf0d2020-04-22 19:28:22 -07002729 // the first primary output opened designates the primary hw device if no HW module
2730 // named "primary" was already loaded.
2731 AutoMutex lock(mHardwareLock);
2732 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002733 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002734 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002735
Eric Laurent6acd1d42017-01-04 14:23:29 -08002736 mHardwareStatus = AUDIO_HW_SET_MODE;
2737 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2738 mHardwareStatus = AUDIO_HW_IDLE;
2739 }
2740 } else {
2741 MmapThread *mmapThread = (MmapThread *)thread.get();
2742 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002743 }
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002744 response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002745 response->config = VALUE_OR_RETURN_STATUS(
2746 legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002747 response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(latencyMs));
Andy Hung973638a2020-12-08 20:47:45 -08002748 response->flags = VALUE_OR_RETURN_STATUS(
2749 legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
Eric Laurentcf2c0212014-07-25 16:20:43 -07002750 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751 }
2752
Eric Laurentcf2c0212014-07-25 16:20:43 -07002753 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754}
2755
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002756audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2757 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758{
2759 Mutex::Autolock _l(mLock);
2760 MixerThread *thread1 = checkMixerThread_l(output1);
2761 MixerThread *thread2 = checkMixerThread_l(output2);
2762
2763 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002764 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2765 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002766 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 }
2768
Glenn Kasteneeecb982016-02-26 10:44:04 -08002769 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002770 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 thread->addOutputTrack(thread2);
2772 mPlaybackThreads.add(id, thread);
2773 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002774 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 return id;
2776}
2777
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002778status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779{
Glenn Kastend96c5722012-04-25 13:44:49 -07002780 return closeOutput_nonvirtual(output);
2781}
2782
2783status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2784{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785 // keep strong reference on the playback thread so that
2786 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002787 sp<PlaybackThread> playbackThread;
2788 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 {
2790 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002791 playbackThread = checkPlaybackThread_l(output);
2792 if (playbackThread != NULL) {
2793 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794
Andy Hungdc099c22018-09-18 13:46:39 -07002795 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002796
Eric Laurent6acd1d42017-01-04 14:23:29 -08002797 if (playbackThread->type() == ThreadBase::MIXER) {
2798 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2799 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2800 DuplicatingThread *dupThread =
2801 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2802 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2803 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002804 }
2805 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002806
2807
Eric Laurent6acd1d42017-01-04 14:23:29 -08002808 mPlaybackThreads.removeItem(output);
2809 // save all effects to the default thread
2810 if (mPlaybackThreads.size()) {
2811 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2812 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002813 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002814 Mutex::Autolock _dl(dstThread->mLock);
2815 Mutex::Autolock _sl(playbackThread->mLock);
2816 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2817 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002818 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002819 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 }
2822 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002823 } else {
2824 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2825 if (mmapThread == 0) {
2826 return BAD_VALUE;
2827 }
Andy Hungdc099c22018-09-18 13:46:39 -07002828 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002829 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002830 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 }
Mikhail Naganov88536df2021-07-26 17:30:29 -07002832 ioConfigChanged(AUDIO_OUTPUT_CLOSED, sp<AudioIoDescriptor>::make(output));
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002833 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002835 // The thread entity (active unit of execution) is no longer running here,
2836 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837
Eric Laurent6acd1d42017-01-04 14:23:29 -08002838 if (playbackThread != 0) {
2839 playbackThread->exit();
2840 if (!playbackThread->isDuplicating()) {
2841 closeOutputFinish(playbackThread);
2842 }
2843 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002844 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002845 mmapThread->exit();
2846 AudioStreamOut *out = mmapThread->clearOutput();
2847 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2848 // from now on thread->mOutput is NULL
2849 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 }
2851 return NO_ERROR;
2852}
2853
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002854void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002855{
2856 AudioStreamOut *out = thread->clearOutput();
2857 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2858 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002859 delete out;
2860}
2861
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002862void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002863{
2864 mPlaybackThreads.removeItem(thread->mId);
2865 thread->exit();
2866 closeOutputFinish(thread);
2867}
2868
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002869status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870{
2871 Mutex::Autolock _l(mLock);
2872 PlaybackThread *thread = checkPlaybackThread_l(output);
2873
2874 if (thread == NULL) {
2875 return BAD_VALUE;
2876 }
2877
Steve Block3856b092011-10-20 11:56:00 +01002878 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 thread->suspend();
2880
2881 return NO_ERROR;
2882}
2883
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002884status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885{
2886 Mutex::Autolock _l(mLock);
2887 PlaybackThread *thread = checkPlaybackThread_l(output);
2888
2889 if (thread == NULL) {
2890 return BAD_VALUE;
2891 }
2892
Steve Block3856b092011-10-20 11:56:00 +01002893 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894
2895 thread->restore();
2896
2897 return NO_ERROR;
2898}
2899
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002900status_t AudioFlinger::openInput(const media::OpenInputRequest& request,
2901 media::OpenInputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902{
Eric Laurent83b88082014-06-20 18:31:16 -07002903 Mutex::Autolock _l(mLock);
2904
Mikhail Naganov21a32ec2021-07-08 14:40:12 -07002905 AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
2906 aidl2legacy_AudioDeviceTypeAddress(request.device));
2907 if (device.mType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002908 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002909 }
2910
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002911 audio_io_handle_t input = VALUE_OR_RETURN_STATUS(
2912 aidl2legacy_int32_t_audio_io_handle_t(request.input));
2913 audio_config_t config = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002914 aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002915
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002916 sp<ThreadBase> thread = openInput_l(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002917 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)),
2918 &input,
2919 &config,
2920 device.mType,
2921 device.address().c_str(),
Mikhail Naganovddceecc2021-09-03 13:58:56 -07002922 VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSource_audio_source_t(request.source)),
Andy Hung973638a2020-12-08 20:47:45 -08002923 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)),
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002924 AUDIO_DEVICE_NONE,
2925 String8{});
2926
2927 response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002928 response->config = VALUE_OR_RETURN_STATUS(
2929 legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002930 response->device = request.device;
Eric Laurent83b88082014-06-20 18:31:16 -07002931
2932 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002933 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002934 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002935 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002937 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002938}
Dima Zavin799a70e2011-04-18 16:57:27 -07002939
Eric Laurent6acd1d42017-01-04 14:23:29 -08002940sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002941 audio_io_handle_t *input,
2942 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002943 audio_devices_t devices,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002944 const char* address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002945 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002946 audio_input_flags_t flags,
2947 audio_devices_t outputDevice,
2948 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002949{
Glenn Kastene7d66712015-03-05 13:46:52 -08002950 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002951 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002952 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002953 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002954 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002955
Glenn Kasteneeecb982016-02-26 10:44:04 -08002956 // Audio Policy can request a specific handle for hardware hotword.
2957 // The goal here is not to re-open an already opened input.
2958 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002959 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002960 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2961 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2962 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2963 return 0;
2964 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2965 // This should not happen in a transient state with current design.
2966 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2967 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002968 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002969
Eric Laurentcf2c0212014-07-25 16:20:43 -07002970 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002971 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002972 sp<StreamInHalInterface> inStream;
2973 status_t status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002974 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002975 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002976 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2977 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002978 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002979 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002980 halconfig.sample_rate,
2981 halconfig.format,
2982 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002983 flags,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002984 status, address);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002986 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002987 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002988 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002989 audio_is_linear_pcm(config->format) &&
2990 audio_is_linear_pcm(halconfig.format) &&
2991 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
Andy Hung936845a2021-06-08 00:09:06 -07002992 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_LIMIT) &&
2993 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_LIMIT)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002994 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002995 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002996 inStream.clear();
2997 status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002998 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002999 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07003000 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 }
3002
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003003 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07003004 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003005 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
3006 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07003007 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003008 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08003009 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
3010 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003011 return thread;
3012 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003013 // Start record thread
3014 // RecordThread requires both input and output device indication to forward to audio
3015 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07003016 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003017 mRecordThreads.add(*input, thread);
3018 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
3019 return thread;
3020 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 }
3022
Eric Laurentcf2c0212014-07-25 16:20:43 -07003023 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 return 0;
3025}
3026
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003027status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028{
Glenn Kastend96c5722012-04-25 13:44:49 -07003029 return closeInput_nonvirtual(input);
3030}
3031
3032status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
3033{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034 // keep strong reference on the record thread so that
3035 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08003036 sp<RecordThread> recordThread;
3037 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038 {
3039 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003040 recordThread = checkRecordThread_l(input);
3041 if (recordThread != 0) {
3042 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043
Andy Hungdc099c22018-09-18 13:46:39 -07003044 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07003045
Eric Laurent6acd1d42017-01-04 14:23:29 -08003046 // If we still have effect chains, it means that a client still holds a handle
3047 // on at least one effect. We must either move the chain to an existing thread with the
3048 // same session ID or put it aside in case a new record thread is opened for a
3049 // new capture on the same session
3050 sp<EffectChain> chain;
3051 {
3052 Mutex::Autolock _sl(recordThread->mLock);
3053 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
3054 // Note: maximum one chain per record thread
3055 if (effectChains.size() != 0) {
3056 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07003057 }
3058 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003059 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003060 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08003061 // This should only happen in case of overlap between one thread tear down and the
3062 // creation of its replacement
3063 size_t i;
3064 for (i = 0; i < mRecordThreads.size(); i++) {
3065 sp<RecordThread> t = mRecordThreads.valueAt(i);
3066 if (t == recordThread) {
3067 continue;
3068 }
3069 if (t->hasAudioSession(chain->sessionId()) != 0) {
3070 Mutex::Autolock _l(t->mLock);
3071 ALOGV("closeInput() found thread %d for effect session %d",
3072 t->id(), chain->sessionId());
3073 t->addEffectChain_l(chain);
3074 break;
3075 }
3076 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08003077 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08003078 if (i == mRecordThreads.size()) {
3079 putOrphanEffectChain_l(chain);
3080 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003081 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003082 mRecordThreads.removeItem(input);
3083 } else {
3084 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
3085 if (mmapThread == 0) {
3086 return BAD_VALUE;
3087 }
Andy Hungdc099c22018-09-18 13:46:39 -07003088 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003089 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07003090 }
Mikhail Naganov88536df2021-07-26 17:30:29 -07003091 ioConfigChanged(AUDIO_INPUT_CLOSED, sp<AudioIoDescriptor>::make(input));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092 }
Eric Laurent83b88082014-06-20 18:31:16 -07003093 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
3094 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08003095 if (recordThread != 0) {
3096 closeInputFinish(recordThread);
3097 } else if (mmapThread != 0) {
3098 mmapThread->exit();
3099 AudioStreamIn *in = mmapThread->clearInput();
3100 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3101 // from now on thread->mInput is NULL
3102 delete in;
3103 }
Eric Laurent83b88082014-06-20 18:31:16 -07003104 return NO_ERROR;
3105}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003106
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003107void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003108{
3109 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003110 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003111 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003112 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07003113 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07003114}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115
Mikhail Naganov444ecc32018-05-01 17:40:05 -07003116void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003117{
3118 mRecordThreads.removeItem(thread->mId);
3119 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120}
3121
Glenn Kastend2304db2014-02-03 07:40:31 -08003122status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123{
3124 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08003125 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126
3127 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3128 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07003129 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07003130 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003131 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3132 mMmapThreads[i]->invalidateTracks(stream);
3133 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134 return NO_ERROR;
3135}
3136
3137
Glenn Kasteneeecb982016-02-26 10:44:04 -08003138audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139{
Glenn Kasten9d003132016-04-06 14:38:09 -07003140 // This is a binder API, so a malicious client could pass in a bad parameter.
3141 // Check for that before calling the internal API nextUniqueId().
3142 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3143 ALOGE("newAudioUniqueId invalid use %d", use);
3144 return AUDIO_UNIQUE_ID_ALLOCATE;
3145 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003146 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147}
3148
Andy Hung8b0bfd92019-12-23 13:11:11 -08003149void AudioFlinger::acquireAudioSessionId(
3150 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003151{
3152 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08003153 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003154 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003155 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003156 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3157 caller = pid; // check must match releaseAudioSessionId()
3158 }
3159 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3160 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003161 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003162
Eric Laurent021cf962014-05-13 10:18:14 -07003163 {
3164 Mutex::Autolock _cl(mClientLock);
3165 // Ignore requests received from processes not known as notification client. The request
3166 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3167 // called from a different pid leaving a stale session reference. Also we don't know how
3168 // to clear this reference if the client process dies.
3169 if (mNotificationClients.indexOfKey(caller) < 0) {
3170 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3171 return;
3172 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003173 }
3174
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003175 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003176 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003177 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003178 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3179 ref->mCnt++;
3180 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003181 return;
3182 }
3183 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003184 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003185 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003186}
3187
Glenn Kastend848eb42016-03-08 13:42:11 -08003188void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003189{
Eric Laurent6c796322019-04-09 14:13:17 -07003190 std::vector< sp<EffectModule> > removedEffects;
3191 {
3192 Mutex::Autolock _l(mLock);
3193 pid_t caller = IPCThreadState::self()->getCallingPid();
3194 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3195 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003196 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3197 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003198 }
Eric Laurent6c796322019-04-09 14:13:17 -07003199 size_t num = mAudioSessionRefs.size();
3200 for (size_t i = 0; i < num; i++) {
3201 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3202 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3203 ref->mCnt--;
3204 ALOGV(" decremented refcount to %d", ref->mCnt);
3205 if (ref->mCnt == 0) {
3206 mAudioSessionRefs.removeAt(i);
3207 delete ref;
3208 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3209 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3210 }
3211 goto Exit;
3212 }
3213 }
3214 // If the caller is audioserver it is likely that the session being released was acquired
3215 // on behalf of a process not in notification clients and we ignore the warning.
3216 ALOGW_IF(!isAudioServerUid(callerUid),
3217 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003218 }
Eric Laurent6c796322019-04-09 14:13:17 -07003219
3220Exit:
3221 for (auto& effect : removedEffects) {
3222 effect->updatePolicyState();
3223 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003224}
3225
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003226bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3227{
3228 size_t num = mAudioSessionRefs.size();
3229 for (size_t i = 0; i < num; i++) {
3230 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3231 if (ref->mSessionid == audioSession) {
3232 return true;
3233 }
3234 }
3235 return false;
3236}
3237
Eric Laurent6c796322019-04-09 14:13:17 -07003238std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003239
Steve Block3856b092011-10-20 11:56:00 +01003240 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003241
3242 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003243 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003244
3245 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3246 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003247 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003248 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3249 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003250 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003251 chains.push(ec);
3252 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003253 }
3254 }
Eric Laurent6c796322019-04-09 14:13:17 -07003255
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003256 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3257 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003258 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003259 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3260 sp<EffectChain> ec = t->mEffectChains[j];
3261 chains.push(ec);
3262 }
3263 }
3264
Eric Laurent6c796322019-04-09 14:13:17 -07003265 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3266 sp<MmapThread> t = mMmapThreads.valueAt(i);
3267 Mutex::Autolock _l(t->mLock);
3268 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3269 sp<EffectChain> ec = t->mEffectChains[j];
3270 chains.push(ec);
3271 }
3272 }
3273
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003274 for (size_t i = 0; i < chains.size(); i++) {
3275 sp<EffectChain> ec = chains[i];
3276 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003277 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003278 if (t == 0) {
3279 continue;
3280 }
3281 size_t numsessionrefs = mAudioSessionRefs.size();
3282 bool found = false;
3283 for (size_t k = 0; k < numsessionrefs; k++) {
3284 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003285 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003286 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003287 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003288 found = true;
3289 break;
3290 }
3291 }
3292 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003293 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003294 // remove all effects from the chain
3295 while (ec->mEffects.size()) {
3296 sp<EffectModule> effect = ec->mEffects[0];
3297 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003298 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003299 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003300 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003301 }
Eric Laurent6c796322019-04-09 14:13:17 -07003302 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003303 }
3304 }
3305 }
Eric Laurent6c796322019-04-09 14:13:17 -07003306 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003307}
3308
Andy Hungdc099c22018-09-18 13:46:39 -07003309// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3310void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3311{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303312 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
3313 audio_utils::FdToString fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
Andy Hungdc099c22018-09-18 13:46:39 -07003314 const int fd = fdToString.fd();
3315 if (fd >= 0) {
3316 thread->dump(fd, {} /* args */);
3317 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3318 }
3319}
3320
Glenn Kasteneeecb982016-02-26 10:44:04 -08003321// checkThread_l() must be called with AudioFlinger::mLock held
3322AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3323{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003324 ThreadBase *thread = checkMmapThread_l(ioHandle);
3325 if (thread == 0) {
3326 switch (audio_unique_id_get_use(ioHandle)) {
3327 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3328 thread = checkPlaybackThread_l(ioHandle);
3329 break;
3330 case AUDIO_UNIQUE_ID_USE_INPUT:
3331 thread = checkRecordThread_l(ioHandle);
3332 break;
3333 default:
3334 break;
3335 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003336 }
3337 return thread;
3338}
3339
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003341AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342{
Glenn Kastena1117922012-01-26 10:53:32 -08003343 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344}
3345
3346// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003347AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348{
3349 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003350 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351}
3352
3353// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003354AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355{
Glenn Kastena1117922012-01-26 10:53:32 -08003356 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357}
3358
Eric Laurent6acd1d42017-01-04 14:23:29 -08003359// checkMmapThread_l() must be called with AudioFlinger::mLock held
3360AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3361{
3362 return mMmapThreads.valueFor(io).get();
3363}
3364
3365
3366// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3367AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3368{
Eric Laurent7459b902017-04-19 18:10:41 -07003369 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003370 if (volumeInterface == nullptr) {
3371 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3372 if (mmapThread != nullptr) {
3373 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003374 MmapPlaybackThread *mmapPlaybackThread =
3375 static_cast<MmapPlaybackThread *>(mmapThread);
3376 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003377 }
3378 }
3379 }
3380 return volumeInterface;
3381}
3382
3383Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3384{
3385 Vector <VolumeInterface *> volumeInterfaces;
3386 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003387 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003388 }
3389 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3390 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003391 MmapPlaybackThread *mmapPlaybackThread =
3392 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3393 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003394 }
3395 }
3396 return volumeInterfaces;
3397}
3398
Glenn Kasteneeecb982016-02-26 10:44:04 -08003399audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400{
Glenn Kasten9d003132016-04-06 14:38:09 -07003401 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003402 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003403 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3404 for (int retry = 0; retry < maxRetries; retry++) {
3405 // The cast allows wraparound from max positive to min negative instead of abort
3406 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3407 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3408 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3409 // allow wrap by skipping 0 and -1 for session ids
3410 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3411 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3412 return (audio_unique_id_t) (base | use);
3413 }
3414 }
3415 // We have no way of recovering from wraparound
3416 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3417 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418}
3419
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003420AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003421{
Eric Laurent00abf0d2020-04-22 19:28:22 -07003422 AutoMutex lock(mHardwareLock);
3423 if (mPrimaryHardwareDev == nullptr) {
3424 return nullptr;
3425 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003426 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3427 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003428 if(thread->isDuplicating()) {
3429 continue;
3430 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003431 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003432 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003433 return thread;
3434 }
3435 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07003436 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003437}
3438
jiabinc52b1ff2019-10-31 17:20:42 -07003439DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003440{
3441 PlaybackThread *thread = primaryPlaybackThread_l();
3442
3443 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003444 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003445 }
3446
jiabinc52b1ff2019-10-31 17:20:42 -07003447 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003448}
3449
Glenn Kastena7335632016-06-09 17:09:53 -07003450AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3451{
3452 size_t minFrameCount = 0;
3453 PlaybackThread *minThread = NULL;
3454 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3455 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3456 if (!thread->isDuplicating()) {
3457 size_t frameCount = thread->frameCountHAL();
3458 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3459 (frameCount == minFrameCount && thread->hasFastMixer() &&
3460 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3461 minFrameCount = frameCount;
3462 minThread = thread;
3463 }
3464 }
3465 }
3466 return minThread;
3467}
3468
jiabineb3bda02020-06-30 14:07:03 -07003469AudioFlinger::ThreadBase *AudioFlinger::hapticPlaybackThread_l() const {
3470 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
3471 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3472 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
3473 return thread;
3474 }
3475 }
3476 return nullptr;
3477}
3478
jiabinf042b9b2021-05-07 23:46:28 +00003479void AudioFlinger::updateSecondaryOutputsForTrack_l(
3480 PlaybackThread::Track* track,
3481 PlaybackThread* thread,
3482 const std::vector<audio_io_handle_t> &secondaryOutputs) const {
3483 TeePatches teePatches;
3484 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
3485 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
3486 if (secondaryThread == nullptr) {
3487 ALOGE("no playback thread found for secondary output %d", thread->id());
3488 continue;
3489 }
3490
3491 size_t sourceFrameCount = thread->frameCount() * track->sampleRate()
3492 / thread->sampleRate();
3493 size_t sinkFrameCount = secondaryThread->frameCount() * track->sampleRate()
3494 / secondaryThread->sampleRate();
3495 // If the secondary output has just been opened, the first secondaryThread write
3496 // will not block as it will fill the empty startup buffer of the HAL,
3497 // so a second sink buffer needs to be ready for the immediate next blocking write.
3498 // Additionally, have a margin of one main thread buffer as the scheduling jitter
3499 // can reorder the writes (eg if thread A&B have the same write intervale,
3500 // the scheduler could schedule AB...BA)
3501 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
3502 // Total secondary output buffer must be at least as the read frames plus
3503 // the margin of a few buffers on both sides in case the
3504 // threads scheduling has some jitter.
3505 // That value should not impact latency as the secondary track is started before
3506 // its buffer is full, see frameCountToBeReady.
3507 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
3508 // The frameCount should also not be smaller than the secondary thread min frame
3509 // count
3510 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
3511 [&] { Mutex::Autolock _l(secondaryThread->mLock);
3512 return secondaryThread->latency_l(); }(),
3513 secondaryThread->mNormalFrameCount,
3514 secondaryThread->mSampleRate,
3515 track->sampleRate(),
3516 track->getSpeed());
3517 frameCount = std::max(frameCount, minFrameCount);
3518
3519 using namespace std::chrono_literals;
3520 auto inChannelMask = audio_channel_mask_out_to_in(track->channelMask());
3521 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
3522 track->sampleRate(),
3523 inChannelMask,
3524 track->format(),
3525 frameCount,
3526 nullptr /* buffer */,
3527 (size_t)0 /* bufferSize */,
3528 AUDIO_INPUT_FLAG_DIRECT,
3529 0ns /* timeout */);
3530 status_t status = patchRecord->initCheck();
3531 if (status != NO_ERROR) {
3532 ALOGE("Secondary output patchRecord init failed: %d", status);
3533 continue;
3534 }
3535
3536 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
3537 // for fast usage: thread has fast mixer, sample rate matches, etc.;
3538 // for now, we exclude fast tracks by removing the Fast flag.
3539 const audio_output_flags_t outputFlags =
3540 (audio_output_flags_t)(track->getOutputFlags() & ~AUDIO_OUTPUT_FLAG_FAST);
3541 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
3542 track->streamType(),
3543 track->sampleRate(),
3544 track->channelMask(),
3545 track->format(),
3546 frameCount,
3547 patchRecord->buffer(),
3548 patchRecord->bufferSize(),
3549 outputFlags,
3550 0ns /* timeout */,
3551 frameCountToBeReady);
3552 status = patchTrack->initCheck();
3553 if (status != NO_ERROR) {
3554 ALOGE("Secondary output patchTrack init failed: %d", status);
3555 continue;
3556 }
3557 teePatches.push_back({patchRecord, patchTrack});
3558 secondaryThread->addPatchTrack(patchTrack);
3559 // In case the downstream patchTrack on the secondaryThread temporarily outlives
3560 // our created track, ensure the corresponding patchRecord is still alive.
3561 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
3562 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
3563 }
3564 track->setTeePatches(std::move(teePatches));
3565}
3566
Eric Laurenta011e352012-03-29 15:51:43 -07003567sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003568 audio_session_t triggerSession,
3569 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003570 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003571 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003572{
3573 Mutex::Autolock _l(mLock);
3574
3575 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3576 status_t playStatus = NAME_NOT_FOUND;
3577 status_t recStatus = NAME_NOT_FOUND;
3578 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3579 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3580 if (playStatus == NO_ERROR) {
3581 return event;
3582 }
3583 }
3584 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3585 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3586 if (recStatus == NO_ERROR) {
3587 return event;
3588 }
3589 }
3590 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3591 mPendingSyncEvents.add(event);
3592 } else {
3593 ALOGV("createSyncEvent() invalid event %d", event->type());
3594 event.clear();
3595 }
3596 return event;
3597}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003598
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599// ----------------------------------------------------------------------------
3600// Effect management
3601// ----------------------------------------------------------------------------
3602
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003603sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3604 return mEffectsFactoryHal;
3605}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606
Glenn Kastenf587ba52012-01-26 16:25:10 -08003607status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608{
3609 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003610 if (mEffectsFactoryHal.get()) {
3611 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3612 } else {
3613 return -ENODEV;
3614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615}
3616
Glenn Kastenf587ba52012-01-26 16:25:10 -08003617status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618{
3619 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003620 if (mEffectsFactoryHal.get()) {
3621 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3622 } else {
3623 return -ENODEV;
3624 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625}
3626
Glenn Kasten5e92a782012-01-30 07:40:52 -08003627status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003628 const effect_uuid_t *pTypeUuid,
3629 uint32_t preferredTypeFlag,
3630 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003632 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3633 return BAD_VALUE;
3634 }
3635
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003637
3638 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003639 return -ENODEV;
3640 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003642 status_t status = NO_ERROR;
3643 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3644 // If uuid is specified, request effect descriptor from that.
3645 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3646 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3647 // If uuid is not specified, look for an available implementation
3648 // of the required type instead.
3649
3650 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3651 effect_descriptor_t desc;
3652 desc.flags = 0; // prevent compiler warning
3653
3654 uint32_t numEffects = 0;
3655 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3656 if (status < 0) {
3657 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3658 return status;
3659 }
3660
3661 bool found = false;
3662 for (uint32_t i = 0; i < numEffects; i++) {
3663 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3664 if (status < 0) {
3665 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3666 continue;
3667 }
3668 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3669 // If matching type found save effect descriptor.
3670 found = true;
3671 *descriptor = desc;
3672
3673 // If there's no preferred flag or this descriptor matches the preferred
3674 // flag, success! If this descriptor doesn't match the preferred
3675 // flag, continue enumeration in case a better matching version of this
3676 // effect type is available. Note that this means if no effect with a
3677 // correct flag is found, the descriptor returned will correspond to the
3678 // last effect that at least had a matching type uuid (if any).
3679 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3680 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3681 break;
3682 }
3683 }
3684 }
3685
3686 if (!found) {
3687 status = NAME_NOT_FOUND;
3688 ALOGW("getEffectDescriptor(): Effect not found by type.");
3689 }
3690 } else {
3691 status = BAD_VALUE;
3692 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3693 }
3694 return status;
3695}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003697status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request,
3698 media::CreateEffectResponse* response) {
3699 const sp<IEffectClient>& effectClient = request.client;
3700 const int32_t priority = request.priority;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003701 const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003702 aidl2legacy_AudioDeviceTypeAddress(request.device));
Svet Ganov33761132021-05-13 22:51:08 +00003703 AttributionSourceState adjAttributionSource = request.attributionSource;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003704 const audio_session_t sessionId = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003705 aidl2legacy_int32_t_audio_session_t(request.sessionId));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003706 audio_io_handle_t io = VALUE_OR_RETURN_STATUS(
3707 aidl2legacy_int32_t_audio_io_handle_t(request.output));
3708 const effect_descriptor_t descIn = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003709 aidl2legacy_EffectDescriptor_effect_descriptor_t(request.desc));
3710 const bool probe = request.probe;
3711
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712 sp<EffectHandle> handle;
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003713 effect_descriptor_t descOut;
3714 int enabledOut = 0;
3715 int idOut = -1;
3716
3717 status_t lStatus = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003719 // TODO b/182392553: refactor or make clearer
Eric Laurentb6436272016-12-07 19:24:50 -08003720 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Svet Ganov33761132021-05-13 22:51:08 +00003721 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
3722 pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003723 if (currentPid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003724 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003725 ALOGW_IF(currentPid != -1 && currentPid != callingPid,
Eric Laurentb6436272016-12-07 19:24:50 -08003726 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003727 __func__, callingUid, callingPid, currentPid);
Svet Ganov33761132021-05-13 22:51:08 +00003728 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003729 currentPid = callingPid;
Eric Laurentb6436272016-12-07 19:24:50 -08003730 }
3731
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003732 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
Svet Ganov33761132021-05-13 22:51:08 +00003733 adjAttributionSource.pid, effectClient.get(), priority, sessionId, io,
3734 mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003736 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003737 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003738 lStatus = NO_INIT;
3739 goto Exit;
3740 }
3741
Andy Hung6096dcd2019-03-13 13:20:30 -07003742 // check audio settings permission for global effects
3743 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3744 if (!settingsAllowed()) {
3745 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3746 lStatus = PERMISSION_DENIED;
3747 goto Exit;
3748 }
3749 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3750 if (!isAudioServerUid(callingUid)) {
3751 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3752 lStatus = PERMISSION_DENIED;
3753 goto Exit;
3754 }
3755
3756 if (io == AUDIO_IO_HANDLE_NONE) {
3757 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3758 lStatus = BAD_VALUE;
3759 goto Exit;
3760 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003761 } else if (sessionId == AUDIO_SESSION_DEVICE) {
Svet Ganov33761132021-05-13 22:51:08 +00003762 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)) {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003763 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3764 lStatus = PERMISSION_DENIED;
3765 goto Exit;
3766 }
Eric Laurent94876032019-11-13 12:45:28 -08003767 if (io != AUDIO_IO_HANDLE_NONE) {
3768 ALOGE("%s: io handle should not be specified for device effect", __func__);
3769 lStatus = BAD_VALUE;
3770 goto Exit;
3771 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003772 } else {
3773 // general sessionId.
3774
3775 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3776 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3777 lStatus = BAD_VALUE;
3778 goto Exit;
3779 }
3780
3781 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3782 // to prevent creating an effect when one doesn't actually have track with that session?
3783 }
3784
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003786 // Get the full effect descriptor from the uuid/type.
3787 // If the session is the output mix, prefer an auxiliary effect,
3788 // otherwise no preference.
3789 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3790 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003791 lStatus = getEffectDescriptor(&descIn.uuid, &descIn.type, preferredType, &descOut);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003792 if (lStatus < 0) {
3793 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3794 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795 }
3796
3797 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003798 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003799 (descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003800 lStatus = INVALID_OPERATION;
3801 goto Exit;
3802 }
3803
Eric Laurent59255e42011-07-27 19:49:51 -07003804 // check recording permission for visualizer
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003805 if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003806 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Svet Ganov33761132021-05-13 22:51:08 +00003807 !recordingAllowed(adjAttributionSource)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003808 lStatus = PERMISSION_DENIED;
3809 goto Exit;
3810 }
3811
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003812 const bool hapticPlaybackRequired = EffectModule::isHapticGenerator(&descOut.type);
jiabineb3bda02020-06-30 14:07:03 -07003813 if (hapticPlaybackRequired
3814 && (sessionId == AUDIO_SESSION_DEVICE
3815 || sessionId == AUDIO_SESSION_OUTPUT_MIX
3816 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
3817 // haptic-generating effect is only valid when the session id is a general session id
3818 lStatus = INVALID_OPERATION;
3819 goto Exit;
3820 }
3821
Eric Laurentf690c462021-09-17 14:47:03 +02003822 // Only audio policy service can create a spatializer effect
3823 if ((memcmp(&descOut.type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0) &&
3824 (callingUid != AID_AUDIOSERVER || currentPid != getpid())) {
3825 ALOGW("%s: attempt to create a spatializer effect from uid/pid %d/%d",
3826 __func__, callingUid, currentPid);
3827 lStatus = PERMISSION_DENIED;
3828 goto Exit;
3829 }
3830
Glenn Kasten142f5192014-03-25 17:44:59 -07003831 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003832 // if the output returned by getOutputForEffect() is removed before we lock the
3833 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3834 // and we will exit safely
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003835 io = AudioSystem::getOutputForEffect(&descOut);
Eric Laurenteb3c3372013-09-25 12:25:29 -07003836 ALOGV("createEffect got output %d", io);
3837 }
3838
3839 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840
Eric Laurentb82e6b72019-11-22 17:25:04 -08003841 if (sessionId == AUDIO_SESSION_DEVICE) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003842 sp<Client> client = registerPid(currentPid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003843 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Eric Laurentb82e6b72019-11-22 17:25:04 -08003844 handle = mDeviceEffectManager.createEffect_l(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003845 &descOut, device, client, effectClient, mPatchPanel.patches_l(),
Eric Laurentde8caf42021-08-11 17:19:25 +02003846 &enabledOut, &lStatus, probe, request.notifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003847 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3848 // remove local strong reference to Client with mClientLock held
3849 Mutex::Autolock _cl(mClientLock);
3850 client.clear();
3851 } else {
3852 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003853 if (handle.get() != nullptr) idOut = handle->id();
Eric Laurentb82e6b72019-11-22 17:25:04 -08003854 }
3855 goto Register;
3856 }
3857
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 // If output is not specified try to find a matching audio session ID in one of the
3859 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003860 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3861 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003862 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3863 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003864 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003865 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003866 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3867 if (io == AUDIO_IO_HANDLE_NONE) {
3868 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003870 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003871 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003872 }
Andy Hung444bb552019-03-14 17:06:39 -07003873
3874 // If you wish to create a Record preprocessing AudioEffect in Java,
3875 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3876 // Otherwise it will fail when created on a Playback thread by legacy
3877 // handling below. Ditto with Mmap, the associated Mmap track must be created
3878 // before creating the AudioEffect or the io handle must be specified.
3879 //
3880 // Detect if the effect is created after an AudioRecord is destroyed.
3881 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3882 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003883 " for session %d no longer exists",
3884 __func__, descOut.name, sessionId);
Andy Hung444bb552019-03-14 17:06:39 -07003885 lStatus = PERMISSION_DENIED;
3886 goto Exit;
3887 }
3888
3889 // Legacy handling of creating an effect on an expired or made-up
3890 // session id. We think that it is a Playback effect.
3891 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003892 // If no output thread contains the requested session ID, default to
3893 // first output. The effect chain will be moved to the correct output
3894 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003895 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003896 io = mPlaybackThreads.keyAt(0);
3897 }
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003898 ALOGV("createEffect() got io %d for effect %s", io, descOut.name);
Eric Laurentb3f315a2021-07-13 15:09:05 +02003899 } else if (checkPlaybackThread_l(io) != nullptr
3900 && sessionId != AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung1631f062019-03-12 19:39:03 -07003901 // allow only one effect chain per sessionId on mPlaybackThreads.
3902 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3903 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07003904 if (io == checkIo) {
3905 if (hapticPlaybackRequired
3906 && mPlaybackThreads.valueAt(i)
3907 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3908 ALOGE("%s: haptic playback thread is required while the required playback "
3909 "thread(io=%d) doesn't support", __func__, (int)io);
3910 lStatus = BAD_VALUE;
3911 goto Exit;
3912 }
3913 continue;
3914 }
Andy Hung1631f062019-03-12 19:39:03 -07003915 const uint32_t sessionType =
3916 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3917 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3918 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003919 __func__, descOut.name, (int) io, (int) sessionId, (int) checkIo);
Andy Hung1631f062019-03-12 19:39:03 -07003920 android_errorWriteLog(0x534e4554, "123237974");
3921 lStatus = BAD_VALUE;
3922 goto Exit;
3923 }
3924 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003925 }
3926 ThreadBase *thread = checkRecordThread_l(io);
3927 if (thread == NULL) {
3928 thread = checkPlaybackThread_l(io);
3929 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003930 thread = checkMmapThread_l(io);
3931 if (thread == NULL) {
3932 ALOGE("createEffect() unknown output thread");
3933 lStatus = BAD_VALUE;
3934 goto Exit;
3935 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003936 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003937 } else {
3938 // Check if one effect chain was awaiting for an effect to be created on this
3939 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003940 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003941 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003942 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003943 thread->addEffectChain_l(chain);
3944 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003946
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003947 sp<Client> client = registerPid(currentPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003949 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003950 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
jiabineb3bda02020-06-30 14:07:03 -07003951 ThreadBase *oriThread = nullptr;
3952 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3953 ThreadBase *hapticThread = hapticPlaybackThread_l();
3954 if (hapticThread == nullptr) {
3955 ALOGE("%s haptic thread not found while it is required", __func__);
3956 lStatus = INVALID_OPERATION;
3957 goto Exit;
3958 }
3959 if (hapticThread != thread) {
3960 // Force to use haptic thread for haptic-generating effect.
3961 oriThread = thread;
3962 thread = hapticThread;
3963 }
3964 }
Eric Laurentde070132010-07-13 04:45:46 -07003965 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurentde8caf42021-08-11 17:19:25 +02003966 &descOut, &enabledOut, &lStatus, pinned, probe,
3967 request.notifyFramesProcessed);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003968 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003969 // remove local strong reference to Client with mClientLock held
3970 Mutex::Autolock _cl(mClientLock);
3971 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003972 } else {
3973 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003974 if (handle.get() != nullptr) idOut = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07003975 // Invalidate audio session when haptic playback is created.
3976 if (hapticPlaybackRequired && oriThread != nullptr) {
3977 // invalidateTracksForAudioSession will trigger locking the thread.
3978 oriThread->invalidateTracksForAudioSession(sessionId);
3979 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981 }
3982
Eric Laurentb82e6b72019-11-22 17:25:04 -08003983Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003984 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent6c796322019-04-09 14:13:17 -07003985 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003986 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003987 if (effect != nullptr) {
3988 status_t rStatus = effect->updatePolicyState();
3989 if (rStatus != NO_ERROR) {
3990 lStatus = rStatus;
3991 }
3992 }
3993 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003994 handle.clear();
3995 }
3996
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003997 response->id = idOut;
3998 response->enabled = enabledOut != 0;
3999 response->effect = handle;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004000 response->desc = VALUE_OR_RETURN_STATUS(
4001 legacy2aidl_effect_descriptor_t_EffectDescriptor(descOut));
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004002
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003Exit:
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004004 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005}
4006
Glenn Kastend848eb42016-03-08 13:42:11 -08004007status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004008 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07004009{
Steve Block3856b092011-10-20 11:56:00 +01004010 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07004011 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004012 Mutex::Autolock _l(mLock);
4013 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004014 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004015 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004016 }
Eric Laurentde070132010-07-13 04:45:46 -07004017 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4018 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004019 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004020 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 }
Eric Laurentde070132010-07-13 04:45:46 -07004022 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4023 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004024 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004025 return BAD_VALUE;
4026 }
4027
4028 Mutex::Autolock _dl(dstThread->mLock);
4029 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07004030 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031}
4032
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004033
4034void AudioFlinger::setEffectSuspended(int effectId,
4035 audio_session_t sessionId,
4036 bool suspended)
4037{
4038 Mutex::Autolock _l(mLock);
4039
4040 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
4041 if (thread == nullptr) {
4042 return;
4043 }
4044 Mutex::Autolock _sl(thread->mLock);
4045 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
4046 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
4047}
4048
4049
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004050// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08004051status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07004052 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07004053 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07004054{
Steve Block3856b092011-10-20 11:56:00 +01004055 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07004056 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07004057
Eric Laurent59255e42011-07-27 19:49:51 -07004058 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07004059 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004060 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07004061 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07004062 return INVALID_OPERATION;
4063 }
4064
Eric Laurent4c415062016-06-17 16:14:16 -07004065 // Check whether the destination thread and all effects in the chain are compatible
4066 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07004067 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07004068 " destination thread %p is not compatible with effects in the chain",
4069 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07004070 return INVALID_OPERATION;
4071 }
4072
Eric Laurent39e94f82010-07-28 01:32:47 -07004073 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004074 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07004075 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07004076 // removed.
4077 srcThread->removeEffectChain_l(chain);
4078
4079 // transfer all effects one by one so that new effect chain is created on new thread with
4080 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07004081 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004082 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07004083 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004084 Vector< sp<EffectModule> > removed;
4085 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07004086 while (effect != 0) {
4087 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004088 removed.add(effect);
4089 status = dstThread->addEffect_l(effect);
4090 if (status != NO_ERROR) {
4091 break;
4092 }
Eric Laurentec35a142011-10-05 17:42:25 -07004093 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4094 if (effect->state() == EffectModule::ACTIVE ||
4095 effect->state() == EffectModule::STOPPING) {
4096 effect->start();
4097 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004098 // if the move request is not received from audio policy manager, the effect must be
4099 // re-registered with the new strategy and output
4100 if (dstChain == 0) {
Andy Hungfda44002021-06-03 17:23:16 -07004101 dstChain = effect->getCallback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07004102 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004103 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004104 status = NO_INIT;
4105 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004106 }
4107 strategy = dstChain->strategy();
4108 }
Eric Laurentde070132010-07-13 04:45:46 -07004109 effect = chain->getEffectFromId_l(0);
4110 }
4111
Eric Laurent5baf2af2013-09-12 17:37:00 -07004112 if (status != NO_ERROR) {
4113 for (size_t i = 0; i < removed.size(); i++) {
4114 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004115 }
4116 }
4117
4118 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119}
4120
Eric Laurent6c796322019-04-09 14:13:17 -07004121status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
4122 const sp<PlaybackThread>& dstThread,
4123 sp<PlaybackThread> *srcThread)
4124{
4125 status_t status = NO_ERROR;
4126 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004127 sp<PlaybackThread> thread =
4128 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07004129
4130 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
4131 Mutex::Autolock _dl(dstThread->mLock);
4132 Mutex::Autolock _sl(thread->mLock);
4133 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4134 sp<EffectChain> dstChain;
4135 if (srcChain == 0) {
4136 return INVALID_OPERATION;
4137 }
4138
4139 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
4140 if (effect == 0) {
4141 return INVALID_OPERATION;
4142 }
4143 thread->removeEffect_l(effect);
4144 status = dstThread->addEffect_l(effect);
4145 if (status != NO_ERROR) {
4146 thread->addEffect_l(effect);
4147 status = INVALID_OPERATION;
4148 goto Exit;
4149 }
4150
Andy Hungfda44002021-06-03 17:23:16 -07004151 dstChain = effect->getCallback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004152 if (dstChain == 0) {
4153 thread->addEffect_l(effect);
4154 status = INVALID_OPERATION;
4155 }
4156
4157Exit:
4158 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4159 if (effect->state() == EffectModule::ACTIVE ||
4160 effect->state() == EffectModule::STOPPING) {
4161 effect->start();
4162 }
4163 }
4164
4165 if (status == NO_ERROR && srcThread != nullptr) {
4166 *srcThread = thread;
4167 }
4168 return status;
4169}
4170
Eric Laurent5baf2af2013-09-12 17:37:00 -07004171bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07004172{
4173 if (mGlobalEffectEnableTime != 0 &&
4174 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
4175 return true;
4176 }
4177
4178 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4179 sp<EffectChain> ec =
4180 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004181 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07004182 return true;
4183 }
4184 }
4185 return false;
4186}
4187
Eric Laurent5baf2af2013-09-12 17:37:00 -07004188void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07004189{
4190 Mutex::Autolock _l(mLock);
4191
4192 mGlobalEffectEnableTime = systemTime();
4193
4194 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4195 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
4196 if (t->mType == ThreadBase::OFFLOAD) {
4197 t->invalidateTracks(AUDIO_STREAM_MUSIC);
4198 }
4199 }
4200
4201}
4202
Eric Laurentaaa44472014-09-12 17:41:50 -07004203status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
4204{
Eric Laurentd8365c52017-07-16 15:27:05 -07004205 // clear possible suspended state before parking the chain so that it starts in default state
4206 // when attached to a new record thread
4207 chain->setEffectSuspended_l(FX_IID_AEC, false);
4208 chain->setEffectSuspended_l(FX_IID_NS, false);
4209
Glenn Kastend848eb42016-03-08 13:42:11 -08004210 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004211 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004212 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004213 if (index >= 0) {
4214 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
4215 return ALREADY_EXISTS;
4216 }
4217 mOrphanEffectChains.add(session, chain);
4218 return NO_ERROR;
4219}
4220
4221sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
4222{
4223 sp<EffectChain> chain;
4224 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004225 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004226 if (index >= 0) {
4227 chain = mOrphanEffectChains.valueAt(index);
4228 mOrphanEffectChains.removeItemsAt(index);
4229 }
4230 return chain;
4231}
4232
4233bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
4234{
4235 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08004236 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004237 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004238 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004239 if (index >= 0) {
4240 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08004241 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004242 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004243 mOrphanEffectChains.removeItemsAt(index);
4244 }
4245 return true;
4246 }
4247 return false;
4248}
4249
4250
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251// ----------------------------------------------------------------------------
4252
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004253status_t AudioFlinger::onTransactWrapper(TransactionCode code,
4254 const Parcel& data,
4255 uint32_t flags,
4256 const std::function<status_t()>& delegate) {
4257 (void) data;
4258 (void) flags;
4259
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004260 // make sure transactions reserved to AudioPolicyManager do not come from other processes
4261 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004262 case TransactionCode::SET_STREAM_VOLUME:
4263 case TransactionCode::SET_STREAM_MUTE:
4264 case TransactionCode::OPEN_OUTPUT:
4265 case TransactionCode::OPEN_DUPLICATE_OUTPUT:
4266 case TransactionCode::CLOSE_OUTPUT:
4267 case TransactionCode::SUSPEND_OUTPUT:
4268 case TransactionCode::RESTORE_OUTPUT:
4269 case TransactionCode::OPEN_INPUT:
4270 case TransactionCode::CLOSE_INPUT:
4271 case TransactionCode::INVALIDATE_STREAM:
4272 case TransactionCode::SET_VOICE_VOLUME:
4273 case TransactionCode::MOVE_EFFECTS:
4274 case TransactionCode::SET_EFFECT_SUSPENDED:
4275 case TransactionCode::LOAD_HW_MODULE:
4276 case TransactionCode::GET_AUDIO_PORT:
4277 case TransactionCode::CREATE_AUDIO_PATCH:
4278 case TransactionCode::RELEASE_AUDIO_PATCH:
4279 case TransactionCode::LIST_AUDIO_PATCHES:
4280 case TransactionCode::SET_AUDIO_PORT_CONFIG:
4281 case TransactionCode::SET_RECORD_SILENCED:
Eric Laurentd66d7a12021-07-13 13:35:32 +02004282 case TransactionCode::AUDIO_POLICY_READY:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004283 ALOGW("%s: transaction %d received from PID %d",
4284 __func__, code, IPCThreadState::self()->getCallingPid());
4285 // return status only for non void methods
4286 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004287 case TransactionCode::SET_RECORD_SILENCED:
4288 case TransactionCode::SET_EFFECT_SUSPENDED:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004289 break;
4290 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004291 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004292 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004293 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004294 return OK;
4295 default:
4296 break;
4297 }
4298
4299 // make sure the following transactions come from system components
4300 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004301 case TransactionCode::SET_MASTER_VOLUME:
4302 case TransactionCode::SET_MASTER_MUTE:
Jean-Michel Trivie4f113b2020-11-16 11:50:33 -08004303 case TransactionCode::MASTER_MUTE:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004304 case TransactionCode::SET_MODE:
4305 case TransactionCode::SET_MIC_MUTE:
4306 case TransactionCode::SET_LOW_RAM_DEVICE:
4307 case TransactionCode::SYSTEM_READY:
jiabin1319f5a2021-03-30 22:21:24 +00004308 case TransactionCode::SET_AUDIO_HAL_PIDS:
jiabinf042b9b2021-05-07 23:46:28 +00004309 case TransactionCode::SET_VIBRATOR_INFOS:
4310 case TransactionCode::UPDATE_SECONDARY_OUTPUTS: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004311 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
4312 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
4313 __func__, code, IPCThreadState::self()->getCallingPid(),
4314 IPCThreadState::self()->getCallingUid());
4315 // return status only for non void methods
4316 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004317 case TransactionCode::SYSTEM_READY:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004318 break;
4319 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004320 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004321 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004322 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004323 return OK;
4324 }
4325 } break;
4326 default:
4327 break;
4328 }
4329
4330 // List of relevant events that trigger log merging.
4331 // Log merging should activate during audio activity of any kind. This are considered the
4332 // most relevant events.
4333 // TODO should select more wisely the items from the list
4334 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004335 case TransactionCode::CREATE_TRACK:
4336 case TransactionCode::CREATE_RECORD:
4337 case TransactionCode::SET_MASTER_VOLUME:
4338 case TransactionCode::SET_MASTER_MUTE:
4339 case TransactionCode::SET_MIC_MUTE:
4340 case TransactionCode::SET_PARAMETERS:
4341 case TransactionCode::CREATE_EFFECT:
4342 case TransactionCode::SYSTEM_READY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004343 requestLogMerge();
4344 break;
4345 }
4346 default:
4347 break;
4348 }
4349
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004350 std::string tag("IAudioFlinger command " +
4351 std::to_string(static_cast<std::underlying_type_t<TransactionCode>>(code)));
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004352 TimeCheck check(tag.c_str());
4353
4354 // Make sure we connect to Audio Policy Service before calling into AudioFlinger:
4355 // - AudioFlinger can call into Audio Policy Service with its global mutex held
4356 // - If this is the first time Audio Policy Service is queried from inside audioserver process
4357 // this will trigger Audio Policy Manager initialization.
4358 // - Audio Policy Manager initialization calls into AudioFlinger which will try to lock
4359 // its global mutex and a deadlock will occur.
4360 if (IPCThreadState::self()->getCallingPid() != getpid()) {
4361 AudioSystem::get_audio_policy_service();
4362 }
4363
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004364 return delegate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365}
4366
Glenn Kasten63238ef2015-03-02 15:50:29 -08004367} // namespace android