blob: f69307be0ab5b6c387d7f1c2bbe244778e710a0f [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
Andy Hung03410c02022-01-27 08:24:31 -080034#include <android-base/stringprintf.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080035#include <android/media/IAudioPolicyService.h>
jiabin57303cc2018-12-18 15:45:57 -080036#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080037#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <binder/IServiceManager.h>
39#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070040#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/Parcel.h>
Shunkai Yao2b8fed42022-12-09 01:12:02 +000042#include <media/audiohal/AudioHalVersionInfo.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070043#include <media/audiohal/DeviceHalInterface.h>
44#include <media/audiohal/DevicesFactoryHalInterface.h>
45#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070046#include <media/AudioParameter.h>
Andy Hungb68f5eb2019-12-03 16:49:17 -080047#include <media/MediaMetricsItem.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070048#include <media/TypeConverter.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080049#include <mediautils/TimeCheck.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070050#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <utils/String16.h>
52#include <utils/threads.h>
53
Steven Morelandf0c02ce2018-02-23 14:53:55 -080054#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <cutils/properties.h>
56
Dima Zavin64760242011-05-11 14:15:23 -070057#include <system/audio.h>
Vlad Popae8d99472022-06-30 16:02:48 +020058#include <audiomanager/IAudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070061#include "NBAIO_Tee.h"
Jiabin Huangebe64102021-09-07 20:01:07 +000062#include "PropertyUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070063
Andy Hung6770c6f2015-04-07 13:43:36 -070064#include <media/AudioResamplerPublic.h>
65
Mikhail Naganov9fe94012016-10-14 14:57:40 -070066#include <system/audio_effects/effect_visualizer.h>
67#include <system/audio_effects/effect_ns.h>
68#include <system/audio_effects/effect_aec.h>
jiabineb3bda02020-06-30 14:07:03 -070069#include <system/audio_effects/effect_hapticgenerator.h>
Eric Laurentf690c462021-09-17 14:47:03 +020070#include <system/audio_effects/effect_spatializer.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
Glenn Kasten3b21c502011-12-15 09:52:39 -080072#include <audio_utils/primitives.h>
73
Eric Laurentfeb0db62011-07-22 09:04:31 -070074#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080075
Glenn Kasten9e58b552013-01-18 15:09:48 -080076#include <media/IMediaLogService.h>
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070077#include <media/AidlConversion.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080078#include <media/AudioValidator.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080079#include <media/nbaio/Pipe.h>
80#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080081#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070082#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungc747c532022-03-07 21:41:14 -080083#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070084#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070085#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070086#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080087
rago3bd1c872016-09-26 12:58:14 -070088//#define BUFLOG_NDEBUG 0
89#include <BufLog.h>
90
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080091#include "TypedLogger.h"
92
Mathias Agopian65ab4712010-07-14 17:59:35 -070093// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
John Grossman1c345192012-03-27 14:00:17 -070095// Note: the following macro is used for extremely verbose logging message. In
96// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
97// 0; but one side effect of this is to turn all LOGV's as well. Some messages
98// are so verbose that we want to suppress them even when we have ALOG_ASSERT
99// turned on. Do not uncomment the #def below unless you really know what you
100// are doing and want to see all of the extremely verbose messages.
101//#define VERY_VERY_VERBOSE_LOGGING
102#ifdef VERY_VERY_VERBOSE_LOGGING
103#define ALOGVV ALOGV
104#else
105#define ALOGVV(a...) do { } while(0)
106#endif
Eric Laurentde070132010-07-13 04:45:46 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108namespace android {
109
Andy Hung03410c02022-01-27 08:24:31 -0800110using ::android::base::StringPrintf;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700111using media::IEffectClient;
jiabine99d0882021-09-17 05:21:25 +0000112using media::audio::common::AudioMMapPolicyInfo;
113using media::audio::common::AudioMMapPolicyType;
Svet Ganov33761132021-05-13 22:51:08 +0000114using android::content::AttributionSourceState;
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000115using android::detail::AudioHalVersionInfo;
116
117static const AudioHalVersionInfo kMaxAAudioPropertyDeviceHalVersion =
118 AudioHalVersionInfo(AudioHalVersionInfo::Type::HIDL, 7, 1);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700119
Vlad Popae8d99472022-06-30 16:02:48 +0200120static constexpr char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
121static constexpr char kHardwareLockedString[] = "Hardware lock is taken\n";
122static constexpr char kClientLockedString[] = "Client lock is taken\n";
123static constexpr char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124
Vlad Popae8d99472022-06-30 16:02:48 +0200125static constexpr char kAudioServiceName[] = "audio";
Glenn Kasten58912562012-04-03 10:45:00 -0700126
John Grossman4ff14ba2012-02-08 16:37:41 -0800127nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800128
Eric Laurent81784c32012-11-19 14:55:58 -0800129uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700130
Eric Laurent813e2a72013-08-31 12:59:48 -0700131// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
132// we define a minimum time during which a global effect is considered enabled.
133static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
134
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700135// Keep a strong reference to media.log service around forever.
136// The service is within our parent process so it can never die in a way that we could observe.
137// These two variables are const after initialization.
138static sp<IBinder> sMediaLogServiceAsBinder;
139static sp<IMediaLogService> sMediaLogService;
140
141static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
142
143static void sMediaLogInit()
144{
145 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
146 if (sMediaLogServiceAsBinder != 0) {
147 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
148 }
149}
150
jiabin57303cc2018-12-18 15:45:57 -0800151// Keep a strong reference to external vibrator service
152static sp<os::IExternalVibratorService> sExternalVibratorService;
153
154static sp<os::IExternalVibratorService> getExternalVibratorService() {
155 if (sExternalVibratorService == 0) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700156 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800157 String16("external_vibrator_service"));
158 if (binder != 0) {
159 sExternalVibratorService =
160 interface_cast<os::IExternalVibratorService>(binder);
161 }
162 }
163 return sExternalVibratorService;
164}
165
Andy Hungc747c532022-03-07 21:41:14 -0800166// Creates association between Binder code to name for IAudioFlinger.
167#define IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST \
168BINDER_METHOD_ENTRY(createTrack) \
169BINDER_METHOD_ENTRY(createRecord) \
170BINDER_METHOD_ENTRY(sampleRate) \
171BINDER_METHOD_ENTRY(format) \
172BINDER_METHOD_ENTRY(frameCount) \
173BINDER_METHOD_ENTRY(latency) \
174BINDER_METHOD_ENTRY(setMasterVolume) \
175BINDER_METHOD_ENTRY(setMasterMute) \
176BINDER_METHOD_ENTRY(masterVolume) \
177BINDER_METHOD_ENTRY(masterMute) \
178BINDER_METHOD_ENTRY(setStreamVolume) \
179BINDER_METHOD_ENTRY(setStreamMute) \
180BINDER_METHOD_ENTRY(streamVolume) \
181BINDER_METHOD_ENTRY(streamMute) \
182BINDER_METHOD_ENTRY(setMode) \
183BINDER_METHOD_ENTRY(setMicMute) \
184BINDER_METHOD_ENTRY(getMicMute) \
185BINDER_METHOD_ENTRY(setRecordSilenced) \
186BINDER_METHOD_ENTRY(setParameters) \
187BINDER_METHOD_ENTRY(getParameters) \
188BINDER_METHOD_ENTRY(registerClient) \
189BINDER_METHOD_ENTRY(getInputBufferSize) \
190BINDER_METHOD_ENTRY(openOutput) \
191BINDER_METHOD_ENTRY(openDuplicateOutput) \
192BINDER_METHOD_ENTRY(closeOutput) \
193BINDER_METHOD_ENTRY(suspendOutput) \
194BINDER_METHOD_ENTRY(restoreOutput) \
195BINDER_METHOD_ENTRY(openInput) \
196BINDER_METHOD_ENTRY(closeInput) \
Andy Hungc747c532022-03-07 21:41:14 -0800197BINDER_METHOD_ENTRY(setVoiceVolume) \
198BINDER_METHOD_ENTRY(getRenderPosition) \
199BINDER_METHOD_ENTRY(getInputFramesLost) \
200BINDER_METHOD_ENTRY(newAudioUniqueId) \
201BINDER_METHOD_ENTRY(acquireAudioSessionId) \
202BINDER_METHOD_ENTRY(releaseAudioSessionId) \
203BINDER_METHOD_ENTRY(queryNumberEffects) \
204BINDER_METHOD_ENTRY(queryEffect) \
205BINDER_METHOD_ENTRY(getEffectDescriptor) \
206BINDER_METHOD_ENTRY(createEffect) \
207BINDER_METHOD_ENTRY(moveEffects) \
208BINDER_METHOD_ENTRY(loadHwModule) \
209BINDER_METHOD_ENTRY(getPrimaryOutputSamplingRate) \
210BINDER_METHOD_ENTRY(getPrimaryOutputFrameCount) \
211BINDER_METHOD_ENTRY(setLowRamDevice) \
212BINDER_METHOD_ENTRY(getAudioPort) \
213BINDER_METHOD_ENTRY(createAudioPatch) \
214BINDER_METHOD_ENTRY(releaseAudioPatch) \
215BINDER_METHOD_ENTRY(listAudioPatches) \
216BINDER_METHOD_ENTRY(setAudioPortConfig) \
217BINDER_METHOD_ENTRY(getAudioHwSyncForSession) \
218BINDER_METHOD_ENTRY(systemReady) \
219BINDER_METHOD_ENTRY(audioPolicyReady) \
220BINDER_METHOD_ENTRY(frameCountHAL) \
221BINDER_METHOD_ENTRY(getMicrophones) \
222BINDER_METHOD_ENTRY(setMasterBalance) \
223BINDER_METHOD_ENTRY(getMasterBalance) \
224BINDER_METHOD_ENTRY(setEffectSuspended) \
225BINDER_METHOD_ENTRY(setAudioHalPids) \
226BINDER_METHOD_ENTRY(setVibratorInfos) \
227BINDER_METHOD_ENTRY(updateSecondaryOutputs) \
228BINDER_METHOD_ENTRY(getMmapPolicyInfos) \
229BINDER_METHOD_ENTRY(getAAudioMixerBurstCount) \
230BINDER_METHOD_ENTRY(getAAudioHardwareBurstMinUsec) \
231BINDER_METHOD_ENTRY(setDeviceConnectedState) \
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700232BINDER_METHOD_ENTRY(setSimulateDeviceConnections) \
Eric Laurent076e7c72022-05-03 18:12:28 +0200233BINDER_METHOD_ENTRY(setRequestedLatencyMode) \
234BINDER_METHOD_ENTRY(getSupportedLatencyModes) \
Eric Laurent50d72582022-12-20 20:20:23 +0100235BINDER_METHOD_ENTRY(setBluetoothVariableLatencyEnabled) \
236BINDER_METHOD_ENTRY(isBluetoothVariableLatencyEnabled) \
237BINDER_METHOD_ENTRY(supportsBluetoothVariableLatency) \
Vlad Popae3fd1c22022-11-07 21:03:18 +0100238BINDER_METHOD_ENTRY(getSoundDoseInterface) \
Andy Hungc747c532022-03-07 21:41:14 -0800239
240// singleton for Binder Method Statistics for IAudioFlinger
241static auto& getIAudioFlingerStatistics() {
242 using Code = android::AudioFlingerServerAdapter::Delegate::TransactionCode;
243
244#pragma push_macro("BINDER_METHOD_ENTRY")
245#undef BINDER_METHOD_ENTRY
246#define BINDER_METHOD_ENTRY(ENTRY) \
247 {(Code)media::BnAudioFlingerService::TRANSACTION_##ENTRY, #ENTRY},
248
249 static mediautils::MethodStatistics<Code> methodStatistics{
250 IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST
251 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
252 };
253#pragma pop_macro("BINDER_METHOD_ENTRY")
254
255 return methodStatistics;
256}
257
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000258class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
259 public:
260 void onNewDevicesAvailable() override {
261 // Start a detached thread to execute notification in parallel.
262 // This is done to prevent mutual blocking of audio_flinger and
263 // audio_policy services during system initialization.
264 std::thread notifier([]() {
265 AudioSystem::onNewAudioModulesAvailable();
266 });
267 notifier.detach();
268 }
269};
270
Svet Ganov33761132021-05-13 22:51:08 +0000271// TODO b/182392769: use attribution source util
Eric Laurentec376dc2021-04-08 20:41:22 +0200272/* static */
Svet Ganov33761132021-05-13 22:51:08 +0000273AttributionSourceState AudioFlinger::checkAttributionSourcePackage(
274 const AttributionSourceState& attributionSource) {
Eric Laurentec376dc2021-04-08 20:41:22 +0200275 Vector<String16> packages;
Svet Ganov33761132021-05-13 22:51:08 +0000276 PermissionController{}.getPackagesForUid(attributionSource.uid, packages);
Eric Laurentec376dc2021-04-08 20:41:22 +0200277
Svet Ganov33761132021-05-13 22:51:08 +0000278 AttributionSourceState checkedAttributionSource = attributionSource;
279 if (!attributionSource.packageName.has_value()
280 || attributionSource.packageName.value().size() == 0) {
Eric Laurentec376dc2021-04-08 20:41:22 +0200281 if (!packages.isEmpty()) {
Svet Ganov33761132021-05-13 22:51:08 +0000282 checkedAttributionSource.packageName =
Eric Laurentec376dc2021-04-08 20:41:22 +0200283 std::move(legacy2aidl_String16_string(packages[0]).value());
284 }
285 } else {
286 String16 opPackageLegacy = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000287 aidl2legacy_string_view_String16(attributionSource.packageName.value_or("")));
Eric Laurentec376dc2021-04-08 20:41:22 +0200288 if (std::find_if(packages.begin(), packages.end(),
289 [&opPackageLegacy](const auto& package) {
290 return opPackageLegacy == package; }) == packages.end()) {
291 ALOGW("The package name(%s) provided does not correspond to the uid %d",
Svet Ganov33761132021-05-13 22:51:08 +0000292 attributionSource.packageName.value_or("").c_str(), attributionSource.uid);
Eric Laurentec376dc2021-04-08 20:41:22 +0200293 }
294 }
Svet Ganov33761132021-05-13 22:51:08 +0000295 return checkedAttributionSource;
Eric Laurentec376dc2021-04-08 20:41:22 +0200296}
297
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298// ----------------------------------------------------------------------------
299
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700300std::string formatToString(audio_format_t format) {
301 std::string result;
302 FormatConverter::toString(format, result);
303 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800304}
305
Mathias Agopian65ab4712010-07-14 17:59:35 -0700306// ----------------------------------------------------------------------------
307
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800308void AudioFlinger::instantiate() {
309 sp<IServiceManager> sm(defaultServiceManager());
310 sm->addService(String16(IAudioFlinger::DEFAULT_SERVICE_NAME),
311 new AudioFlingerServerAdapter(new AudioFlinger()), false,
312 IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
313}
314
Mathias Agopian65ab4712010-07-14 17:59:35 -0700315AudioFlinger::AudioFlinger()
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800316 : mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800317 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800318 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700319 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800320 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800321 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700322 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800323 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700324 mBtNrecIsOff(false),
325 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700326 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800327 mTotalMemory(0),
328 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700329 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700330 mPatchPanel(this),
Vlad Popa5161f8a2022-10-10 16:17:20 +0200331 mPatchCommandThread(sp<PatchCommandThread>::make()),
332 mDeviceEffectManager(sp<DeviceEffectManager>::make(*this)),
Vlad Popab042ee62022-10-20 18:05:00 +0200333 mMelReporter(sp<MelReporter>::make(*this)),
Eric Laurent52057642022-12-16 11:45:07 +0100334 mSystemReady(false),
335 mBluetoothLatencyModesEnabled(true)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336{
Eric Laurentf43be0c2021-03-25 10:45:53 +0100337 // Move the audio session unique ID generator start base as time passes to limit risk of
338 // generating the same ID again after an audioserver restart.
339 // This is important because clients will reuse previously allocated audio session IDs
340 // when reconnecting after an audioserver restart and newly allocated IDs may conflict with
341 // active clients.
342 // Moving the base by 1 for each elapsed second is a good compromise between avoiding overlap
343 // between allocation ranges and not reaching wrap around too soon.
344 timespec ts{};
345 clock_gettime(CLOCK_MONOTONIC, &ts);
346 // zero ID has a special meaning, so start allocation at least at AUDIO_UNIQUE_ID_USE_MAX
Eric Laurentf37f1982021-06-01 13:23:27 +0200347 uint32_t movingBase = (uint32_t)std::max((long)1, ts.tv_sec);
Glenn Kastend2e67e12016-04-11 08:26:37 -0700348 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
349 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
Eric Laurentf43be0c2021-03-25 10:45:53 +0100350 mNextUniqueIds[use] =
Eric Laurentf37f1982021-06-01 13:23:27 +0200351 ((use == AUDIO_UNIQUE_ID_USE_SESSION || use == AUDIO_UNIQUE_ID_USE_CLIENT) ?
352 movingBase : 1) * AUDIO_UNIQUE_ID_USE_MAX;
Glenn Kastend2e67e12016-04-11 08:26:37 -0700353 }
354
Eric Laurent94ca1142020-10-07 10:45:20 -0700355#if 1
356 // FIXME See bug 165702394 and bug 168511485
357 const bool doLog = false;
358#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800359 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700360#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800361 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800362 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
363 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700364 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800365 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700366
Wei Jia3f273d12015-11-24 09:06:49 -0800367 // reset battery stats.
368 // if the audio service has crashed, battery stats could be left
369 // in bad state, reset the state upon service start.
370 BatteryNotifier::getInstance().noteResetAudio();
371
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700372 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700373 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
374
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800375 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700376 std::vector<pid_t> halPids;
377 mDevicesFactoryHal->getHalPids(&halPids);
Andy Hung5c6d68a2022-03-09 21:54:59 -0800378 mediautils::TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800379
380 // Notify that we have started (also called when audioserver service restarts)
381 mediametrics::LogItem(mMetricsId)
382 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
383 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700384}
385
386void AudioFlinger::onFirstRef()
387{
Eric Laurent93575202011-01-18 18:39:02 -0800388 Mutex::Autolock _l(mLock);
389
Dima Zavin799a70e2011-04-18 16:57:27 -0700390 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800391 char val_str[PROPERTY_VALUE_MAX] = { 0 };
392 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
393 uint32_t int_val;
394 if (1 == sscanf(val_str, "%u", &int_val)) {
395 mStandbyTimeInNsecs = milliseconds(int_val);
396 ALOGI("Using %u mSec as standby time.", int_val);
397 } else {
398 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
399 ALOGI("Using default %u mSec as standby time.",
400 (uint32_t)(mStandbyTimeInNsecs / 1000000));
401 }
402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403
Eric Laurenta4c5a552012-03-29 10:12:40 -0700404 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800405
Andy Hung6626a012021-01-12 13:38:00 -0800406 gAudioFlinger = this; // we are already refcounted, store into atomic pointer.
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000407
408 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
409 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
jiabine504e7b2021-09-18 00:27:08 +0000410
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000411 if (mDevicesFactoryHal->getHalVersion() <= kMaxAAudioPropertyDeviceHalVersion) {
jiabine504e7b2021-09-18 00:27:08 +0000412 mAAudioBurstsPerBuffer = getAAudioMixerBurstCountFromSystemProperty();
413 mAAudioHwBurstMinMicros = getAAudioHardwareBurstMinUsecFromSystemProperty();
414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415}
416
Eric Laurent42896a02019-09-27 15:40:33 -0700417status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
Andy Hung5c6d68a2022-03-09 21:54:59 -0800418 mediautils::TimeCheck::setAudioHalPids(pids);
Eric Laurent42896a02019-09-27 15:40:33 -0700419 return NO_ERROR;
420}
421
jiabin1319f5a2021-03-30 22:21:24 +0000422status_t AudioFlinger::setVibratorInfos(
423 const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
424 Mutex::Autolock _l(mLock);
425 mAudioVibratorInfos = vibratorInfos;
426 return NO_ERROR;
427}
428
jiabinf042b9b2021-05-07 23:46:28 +0000429status_t AudioFlinger::updateSecondaryOutputs(
430 const TrackSecondaryOutputsMap& trackSecondaryOutputs) {
431 Mutex::Autolock _l(mLock);
432 for (const auto& [trackId, secondaryOutputs] : trackSecondaryOutputs) {
433 size_t i = 0;
434 for (; i < mPlaybackThreads.size(); ++i) {
435 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
436 Mutex::Autolock _tl(thread->mLock);
437 sp<PlaybackThread::Track> track = thread->getTrackById_l(trackId);
438 if (track != nullptr) {
439 ALOGD("%s trackId: %u", __func__, trackId);
440 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
441 break;
442 }
443 }
444 ALOGW_IF(i >= mPlaybackThreads.size(),
445 "%s cannot find track with id %u", __func__, trackId);
446 }
447 return NO_ERROR;
448}
449
Jiabin Huangebe64102021-09-07 20:01:07 +0000450status_t AudioFlinger::getMmapPolicyInfos(
jiabine99d0882021-09-17 05:21:25 +0000451 AudioMMapPolicyType policyType, std::vector<AudioMMapPolicyInfo> *policyInfos) {
jiabine504e7b2021-09-18 00:27:08 +0000452 Mutex::Autolock _l(mLock);
Jiabin Huangebe64102021-09-07 20:01:07 +0000453 if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) {
454 *policyInfos = it->second;
455 return NO_ERROR;
456 }
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000457 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
Jiabin Huangebe64102021-09-07 20:01:07 +0000458 AutoMutex lock(mHardwareLock);
459 for (size_t i = 0; i < mAudioHwDevs.size(); ++i) {
460 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
jiabine99d0882021-09-17 05:21:25 +0000461 std::vector<AudioMMapPolicyInfo> infos;
Jiabin Huangebe64102021-09-07 20:01:07 +0000462 status_t status = dev->getMmapPolicyInfos(policyType, &infos);
463 if (status != NO_ERROR) {
464 ALOGE("Failed to query mmap policy info of %d, error %d",
465 mAudioHwDevs.keyAt(i), status);
466 continue;
467 }
468 policyInfos->insert(policyInfos->end(), infos.begin(), infos.end());
469 }
470 mPolicyInfos[policyType] = *policyInfos;
471 } else {
472 getMmapPolicyInfosFromSystemProperty(policyType, policyInfos);
473 mPolicyInfos[policyType] = *policyInfos;
474 }
475 return NO_ERROR;
476}
477
jiabine504e7b2021-09-18 00:27:08 +0000478int32_t AudioFlinger::getAAudioMixerBurstCount() {
479 Mutex::Autolock _l(mLock);
480 return mAAudioBurstsPerBuffer;
481}
482
483int32_t AudioFlinger::getAAudioHardwareBurstMinUsec() {
484 Mutex::Autolock _l(mLock);
485 return mAAudioHwBurstMinMicros;
486}
487
jiabinc0048632023-04-27 22:04:31 +0000488status_t AudioFlinger::setDeviceConnectedState(const struct audio_port_v7 *port,
489 media::DeviceConnectedState state) {
Mikhail Naganov516d3982022-02-01 23:53:59 +0000490 status_t final_result = NO_INIT;
491 Mutex::Autolock _l(mLock);
492 AutoMutex lock(mHardwareLock);
493 mHardwareStatus = AUDIO_HW_SET_CONNECTED_STATE;
494 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
495 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
jiabinc0048632023-04-27 22:04:31 +0000496 status_t result = state == media::DeviceConnectedState::PREPARE_TO_DISCONNECT
497 ? dev->prepareToDisconnectExternalDevice(port)
498 : dev->setConnectedState(port, state == media::DeviceConnectedState::CONNECTED);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000499 // Same logic as with setParameter: it's a success if at least one
500 // HAL module accepts the update.
501 if (final_result != NO_ERROR) {
502 final_result = result;
503 }
504 }
505 mHardwareStatus = AUDIO_HW_IDLE;
506 return final_result;
507}
508
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700509status_t AudioFlinger::setSimulateDeviceConnections(bool enabled) {
510 bool at_least_one_succeeded = false;
511 status_t last_error = INVALID_OPERATION;
512 Mutex::Autolock _l(mLock);
513 AutoMutex lock(mHardwareLock);
514 mHardwareStatus = AUDIO_HW_SET_SIMULATE_CONNECTIONS;
515 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
516 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
517 status_t result = dev->setSimulateDeviceConnections(enabled);
518 if (result == OK) {
519 at_least_one_succeeded = true;
520 } else {
521 last_error = result;
522 }
523 }
524 mHardwareStatus = AUDIO_HW_IDLE;
525 return at_least_one_succeeded ? OK : last_error;
526}
527
jiabin1319f5a2021-03-30 22:21:24 +0000528// getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
Lais Andradebc3f37a2021-07-02 00:13:19 +0100529std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() {
jiabin1319f5a2021-03-30 22:21:24 +0000530 if (mAudioVibratorInfos.empty()) {
Lais Andradebc3f37a2021-07-02 00:13:19 +0100531 return {};
jiabin1319f5a2021-03-30 22:21:24 +0000532 }
Lais Andradebc3f37a2021-07-02 00:13:19 +0100533 return mAudioVibratorInfos.front();
jiabin1319f5a2021-03-30 22:21:24 +0000534}
535
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536AudioFlinger::~AudioFlinger()
537{
538 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700539 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700540 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 }
542 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700543 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700544 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 }
Andy Hungb4946b62019-03-14 11:19:28 -0700546 while (!mMmapThreads.isEmpty()) {
547 const audio_io_handle_t io = mMmapThreads.keyAt(0);
548 if (mMmapThreads.valueAt(0)->isOutput()) {
549 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
550 } else {
551 closeInput_nonvirtual(io); // removes entry from mMmapThreads
552 }
553 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700554
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800555 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
556 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700557 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700559
560 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700561 if (sMediaLogService != 0) {
562 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
563 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
564 mUnregisteredWriters.pop();
565 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700566 }
567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568}
569
Eric Laurentfc235202016-12-20 18:48:17 -0800570//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800571__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800572status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
573 const audio_attributes_t *attr,
574 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700575 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800576 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800577 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800578 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700579 sp<MmapStreamInterface>& interface,
580 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800581{
Andy Hung6626a012021-01-12 13:38:00 -0800582 // TODO: Use ServiceManager to get IAudioFlinger instead of by atomic pointer.
583 // This allows moving oboeservice (AAudio) to a separate process in the future.
584 sp<AudioFlinger> af = AudioFlinger::gAudioFlinger.load(); // either nullptr or singleton AF.
Eric Laurentfc235202016-12-20 18:48:17 -0800585 status_t ret = NO_INIT;
586 if (af != 0) {
587 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800588 direction, attr, config, client, deviceId,
589 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800590 }
591 return ret;
592}
593
Eric Laurent6acd1d42017-01-04 14:23:29 -0800594status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
595 const audio_attributes_t *attr,
596 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700597 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800598 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800599 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800600 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700601 sp<MmapStreamInterface>& interface,
602 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800603{
604 status_t ret = initCheck();
605 if (ret != NO_ERROR) {
606 return ret;
607 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800608 audio_session_t actualSessionId = *sessionId;
609 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
610 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
611 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800612 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700613 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800614 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700615 audio_attributes_t localAttr = *attr;
Eric Laurent9ff3e532022-11-10 16:04:44 +0100616
617 // TODO b/182392553: refactor or make clearer
618 pid_t clientPid =
619 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(client.attributionSource.pid));
620 bool updatePid = (clientPid == (pid_t)-1);
621 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
622
623 AttributionSourceState adjAttributionSource = client.attributionSource;
624 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
625 uid_t clientUid =
626 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(client.attributionSource.uid));
627 ALOGW_IF(clientUid != callingUid,
628 "%s uid %d tried to pass itself off as %d",
629 __FUNCTION__, callingUid, clientUid);
630 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
631 updatePid = true;
632 }
633 if (updatePid) {
634 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
635 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
636 "%s uid %d pid %d tried to pass itself off as pid %d",
637 __func__, callingUid, callingPid, clientPid);
638 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
639 }
640 adjAttributionSource = AudioFlinger::checkAttributionSourcePackage(
641 adjAttributionSource);
642
Eric Laurent6acd1d42017-01-04 14:23:29 -0800643 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
644 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
645 fullConfig.sample_rate = config->sample_rate;
646 fullConfig.channel_mask = config->channel_mask;
647 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800648 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200649 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +0000650 bool isBitPerfect;
Eric Laurent42984412019-05-09 17:57:03 -0700651 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800652 actualSessionId,
Eric Laurent9ff3e532022-11-10 16:04:44 +0100653 &streamType, adjAttributionSource,
Ricardo Correa57a37692020-03-23 17:27:25 -0700654 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800655 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
656 AUDIO_OUTPUT_FLAG_DIRECT),
jiabinc658e452022-10-21 20:52:21 +0000657 deviceId, &portId, &secondaryOutputs, &isSpatialized,
658 &isBitPerfect);
jiabinf1c73972022-04-14 16:28:52 -0700659 if (ret != NO_ERROR) {
660 config->sample_rate = fullConfig.sample_rate;
661 config->channel_mask = fullConfig.channel_mask;
662 config->format = fullConfig.format;
663 }
Kevin Rocard153f92d2018-12-18 18:33:28 -0800664 ALOGW_IF(!secondaryOutputs.empty(),
665 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800666 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700667 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700668 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800669 actualSessionId,
Eric Laurent9ff3e532022-11-10 16:04:44 +0100670 adjAttributionSource,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800671 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700672 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800673 }
674 if (ret != NO_ERROR) {
675 return ret;
676 }
677
678 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
679 // audio policy manager and we can retrieve it
680 sp<MmapThread> thread = mMmapThreads.valueFor(io);
681 if (thread != 0) {
682 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700683 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700684 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800685 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800686 config->sample_rate = thread->sampleRate();
687 config->channel_mask = thread->channelMask();
688 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800689 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700690 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700691 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700692 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800693 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700694 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800695 ret = NO_INIT;
696 }
697
698 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
699
Eric Laurentfc235202016-12-20 18:48:17 -0800700 return ret;
701}
702
jiabin57303cc2018-12-18 15:45:57 -0800703/* static */
Simon Bowden62823412022-10-17 14:52:26 +0000704os::HapticScale AudioFlinger::onExternalVibrationStart(
705 const sp<os::ExternalVibration>& externalVibration) {
jiabin57303cc2018-12-18 15:45:57 -0800706 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
jiabin78dc9c82021-02-22 19:13:29 +0000707 if (evs != nullptr) {
jiabin57303cc2018-12-18 15:45:57 -0800708 int32_t ret;
709 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
710 if (status.isOk()) {
jiabin78dc9c82021-02-22 19:13:29 +0000711 ALOGD("%s, start external vibration with intensity as %d", __func__, ret);
Simon Bowden62823412022-10-17 14:52:26 +0000712 return os::ExternalVibration::externalVibrationScaleToHapticScale(ret);
jiabin57303cc2018-12-18 15:45:57 -0800713 }
714 }
jiabin78dc9c82021-02-22 19:13:29 +0000715 ALOGD("%s, start external vibration with intensity as MUTE due to %s",
716 __func__,
717 evs == nullptr ? "external vibration service not found"
718 : "error when querying intensity");
Simon Bowden62823412022-10-17 14:52:26 +0000719 return os::HapticScale::MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800720}
721
722/* static */
723void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
724 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
725 if (evs != 0) {
jiabinc47acf22022-04-01 23:47:52 +0000726 ALOGD("%s, stopping external vibration", __func__);
jiabin57303cc2018-12-18 15:45:57 -0800727 evs->onExternalVibrationStop(*externalVibration);
728 }
729}
730
Eric Laurentb82e6b72019-11-22 17:25:04 -0800731status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
Andy Hung920f6572022-10-06 12:09:49 -0700732 audio_module_handle_t hwModuleId, const sp<EffectHalInterface>& effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700733 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800734 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
735 if (audioHwDevice == nullptr) {
736 return NO_INIT;
737 }
738 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
739}
740
741status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
Andy Hung920f6572022-10-06 12:09:49 -0700742 audio_module_handle_t hwModuleId, const sp<EffectHalInterface>& effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700743 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800744 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
745 if (audioHwDevice == nullptr) {
746 return NO_INIT;
747 }
748 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
749}
750
Eric Laurenta4c5a552012-03-29 10:12:40 -0700751static const char * const audio_interfaces[] = {
752 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
753 AUDIO_HARDWARE_MODULE_ID_A2DP,
754 AUDIO_HARDWARE_MODULE_ID_USB,
755};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700756
Phil Burk062e67a2015-02-11 13:40:50 -0800757AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700758 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700759 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700760{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700761 // if module is 0, the request comes from an old policy manager and we should load
762 // well known modules
Eric Laurent00abf0d2020-04-22 19:28:22 -0700763 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700764 if (module == 0) {
765 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700766 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700767 loadHwModule_l(audio_interfaces[i]);
768 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700769 // then try to find a module supporting the requested device.
770 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
771 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700772 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
773 uint32_t supportedDevices;
774 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700775 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700776 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700777 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700778 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700779 } else {
780 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700781 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
782 if (audioHwDevice != NULL) {
783 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700784 }
785 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700786
Dima Zavin799a70e2011-04-18 16:57:27 -0700787 return NULL;
788}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789
Glenn Kasten0f11b512014-01-31 16:18:54 -0800790void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 String8 result;
793
Atneya Nair9ec58d52022-10-03 15:46:20 -0700794 result.append("Client Allocators:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800796 sp<Client> client = mClients.valueAt(i).promote();
797 if (client != 0) {
Atneya Nair9ec58d52022-10-03 15:46:20 -0700798 result.appendFormat("Client: %d\n", client->pid());
Atneya3c61d882021-09-20 14:52:15 -0400799 result.append(client->allocator().dump().c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800 }
Atneya3c61d882021-09-20 14:52:15 -0400801 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700802
Eric Laurentd1b28d42013-09-18 18:47:13 -0700803 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800804 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700805 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800806 const pid_t pid = mNotificationClients[i]->getPid();
807 const uid_t uid = mNotificationClients[i]->getUid();
808 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
809 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700810 }
811
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700812 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800813 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700814 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
815 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800816 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
817 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
818 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821}
822
823
Glenn Kasten0f11b512014-01-31 16:18:54 -0800824void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825{
826 const size_t SIZE = 256;
827 char buffer[SIZE];
828 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800829 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830
John Grossman4ff14ba2012-02-08 16:37:41 -0800831 snprintf(buffer, SIZE, "Hardware status: %d\n"
832 "Standby Time mSec: %u\n",
833 hardwareStatus,
834 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 result.append(buffer);
836 write(fd, result.string(), result.size());
jiabinc47acf22022-04-01 23:47:52 +0000837
838 dprintf(fd, "Vibrator infos(size=%zu):\n", mAudioVibratorInfos.size());
839 for (const auto& vibratorInfo : mAudioVibratorInfos) {
840 dprintf(fd, " - %s\n", vibratorInfo.toString().c_str());
841 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842}
843
Glenn Kasten0f11b512014-01-31 16:18:54 -0800844void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845{
846 const size_t SIZE = 256;
847 char buffer[SIZE];
848 String8 result;
849 snprintf(buffer, SIZE, "Permission Denial: "
850 "can't dump AudioFlinger from pid=%d, uid=%d\n",
851 IPCThreadState::self()->getCallingPid(),
852 IPCThreadState::self()->getCallingUid());
853 result.append(buffer);
854 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855}
856
Eric Laurent81784c32012-11-19 14:55:58 -0800857bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700859 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
860 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861}
862
863status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -0700864NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865{
Glenn Kasten44deb052012-02-05 18:09:08 -0800866 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 dumpPermissionDenial(fd, args);
868 } else {
869 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800870 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 if (!hardwareLocked) {
872 String8 result(kHardwareLockedString);
873 write(fd, result.string(), result.size());
874 } else {
875 mHardwareLock.unlock();
876 }
877
Eric Tan7b651152018-07-13 10:17:19 -0700878 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700879
880 // failed to lock - AudioFlinger is probably deadlocked
881 if (!locked) {
882 String8 result(kDeadlockedString);
883 write(fd, result.string(), result.size());
884 }
885
Eric Laurent021cf962014-05-13 10:18:14 -0700886 bool clientLocked = dumpTryLock(mClientLock);
887 if (!clientLocked) {
888 String8 result(kClientLockedString);
889 write(fd, result.string(), result.size());
890 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700891
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700892 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700893 mEffectsFactoryHal->dumpEffects(fd);
894 } else {
895 String8 result(kNoEffectsFactory);
896 write(fd, result.string(), result.size());
897 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700898
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700900 if (clientLocked) {
901 mClientLock.unlock();
902 }
903
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 dumpInternals(fd, args);
905
906 // dump playback threads
907 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
908 mPlaybackThreads.valueAt(i)->dump(fd, args);
909 }
910
911 // dump record threads
912 for (size_t i = 0; i < mRecordThreads.size(); i++) {
913 mRecordThreads.valueAt(i)->dump(fd, args);
914 }
915
Eric Laurent6acd1d42017-01-04 14:23:29 -0800916 // dump mmap threads
917 for (size_t i = 0; i < mMmapThreads.size(); i++) {
918 mMmapThreads.valueAt(i)->dump(fd, args);
919 }
920
Eric Laurentaaa44472014-09-12 17:41:50 -0700921 // dump orphan effect chains
922 if (mOrphanEffectChains.size() != 0) {
923 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
924 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
925 mOrphanEffectChains.valueAt(i)->dump(fd, args);
926 }
927 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700928 // dump all hardware devs
929 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700930 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Andy Hung61589a42021-06-16 09:37:53 -0700931 dev->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700933
Mikhail Naganov201369b2018-05-16 16:52:32 -0700934 mPatchPanel.dump(fd);
935
Vlad Popa5161f8a2022-10-10 16:17:20 +0200936 mDeviceEffectManager->dump(fd);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800937
Vlad Popab042ee62022-10-20 18:05:00 +0200938 std::string melOutput = mMelReporter->dump();
939 write(fd, melOutput.c_str(), melOutput.size());
940
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700941 // dump external setParameters
942 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
943 dprintf(fd, "\n%s setParameters:\n", name);
944 logger.dump(fd, " " /* prefix */);
945 };
946 dumpLogger(mRejectedSetParameterLog, "Rejected");
947 dumpLogger(mAppSetParameterLog, "App");
948 dumpLogger(mSystemSetParameterLog, "System");
949
Andy Hunga8115dc2018-08-24 15:51:59 -0700950 // dump historical threads in the last 10 seconds
951 const std::string threadLog = mThreadLog.dumpToString(
952 "Historical Thread Log ", 0 /* lines */,
953 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
954 write(fd, threadLog.c_str(), threadLog.size());
955
rago3bd1c872016-09-26 12:58:14 -0700956 BUFLOG_RESET;
957
Glenn Kastend65d73c2012-06-22 17:21:07 -0700958 if (locked) {
959 mLock.unlock();
960 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800961
Andy Hung8946a282018-04-19 20:04:56 -0700962#ifdef TEE_SINK
963 // NBAIO_Tee dump is safe to call outside of AF lock.
964 NBAIO_Tee::dumpAll(fd, "_DUMP");
965#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800966 // append a copy of media.log here by forwarding fd to it, but don't attempt
967 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700968 if (sMediaLogServiceAsBinder != 0) {
969 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700970 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800971 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700972
973 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700974 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700975 bool unreachableMemory = false;
976 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700977 if (arg == String16("-m")) {
978 dumpMem = true;
979 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700980 unreachableMemory = true;
981 }
982 }
983
Andy Hung07b745e2016-05-23 16:21:07 -0700984 if (dumpMem) {
985 dprintf(fd, "\nDumping memory:\n");
986 std::string s = dumpMemoryAddresses(100 /* limit */);
987 write(fd, s.c_str(), s.size());
988 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700989 if (unreachableMemory) {
990 dprintf(fd, "\nDumping unreachable memory:\n");
991 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700992 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700993 write(fd, s.c_str(), s.size());
994 }
Andy Hungc747c532022-03-07 21:41:14 -0800995 {
996 std::string timeCheckStats = getIAudioFlingerStatistics().dump();
Andy Hung224f82f2022-03-22 00:00:49 -0700997 dprintf(fd, "\nIAudioFlinger binder call profile:\n");
Andy Hungc747c532022-03-07 21:41:14 -0800998 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
999
1000 extern mediautils::MethodStatistics<int>& getIEffectStatistics();
1001 timeCheckStats = getIEffectStatistics().dump();
Andy Hung224f82f2022-03-22 00:00:49 -07001002 dprintf(fd, "\nIEffect binder call profile:\n");
Andy Hungc747c532022-03-07 21:41:14 -08001003 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
Andy Hung224f82f2022-03-22 00:00:49 -07001004
1005 // Automatically fetch HIDL statistics.
1006 std::shared_ptr<std::vector<std::string>> hidlClassNames =
1007 mediautils::getStatisticsClassesForModule(
1008 METHOD_STATISTICS_MODULE_NAME_AUDIO_HIDL);
1009 if (hidlClassNames) {
1010 for (const auto& className : *hidlClassNames) {
1011 auto stats = mediautils::getStatisticsForClass(className);
1012 if (stats) {
1013 timeCheckStats = stats->dump();
1014 dprintf(fd, "\n%s binder call profile:\n", className.c_str());
1015 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1016 }
1017 }
1018 }
1019
1020 timeCheckStats = mediautils::TimeCheck::toString();
1021 dprintf(fd, "\nTimeCheck:\n");
1022 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1023 dprintf(fd, "\n");
Andy Hungc747c532022-03-07 21:41:14 -08001024 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 }
1026 return NO_ERROR;
1027}
1028
Eric Laurent021cf962014-05-13 10:18:14 -07001029sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -08001030{
Eric Laurent021cf962014-05-13 10:18:14 -07001031 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -08001032 // If pid is already in the mClients wp<> map, then use that entry
1033 // (for which promote() is always != 0), otherwise create a new entry and Client.
1034 sp<Client> client = mClients.valueFor(pid).promote();
1035 if (client == 0) {
1036 client = new Client(this, pid);
1037 mClients.add(pid, client);
1038 }
1039
1040 return client;
1041}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042
Glenn Kasten9e58b552013-01-18 15:09:48 -08001043sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
1044{
Jiabin Huang60766082020-07-28 22:03:56 +00001045 // If there is no memory allocated for logs, return a no-op writer that does nothing.
1046 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001047 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -08001048 return new NBLog::Writer();
1049 }
Glenn Kasten481fb672013-09-30 14:39:28 -07001050 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
1051 // If allocation fails, consult the vector of previously unregistered writers
1052 // and garbage-collect one or more them until an allocation succeeds
1053 if (shared == 0) {
1054 Mutex::Autolock _l(mUnregisteredWritersLock);
1055 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
1056 {
1057 // Pick the oldest stale writer to garbage-collect
1058 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
1059 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001060 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -07001061 // Now the media.log remote reference to IMemory is gone. When our last local
1062 // reference to IMemory also drops to zero at end of this block,
1063 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
1064 }
1065 // Re-attempt the allocation
1066 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
1067 if (shared != 0) {
1068 goto success;
1069 }
1070 }
1071 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +00001072 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -07001073 return new NBLog::Writer();
1074 }
1075success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001076 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -08001077 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
1078 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001079 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -08001080 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001081}
1082
1083void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
1084{
Glenn Kasten685ef092013-02-04 08:15:34 -08001085 if (writer == 0) {
1086 return;
1087 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08001088 sp<IMemory> iMemory(writer->getIMemory());
1089 if (iMemory == 0) {
1090 return;
1091 }
Glenn Kasten481fb672013-09-30 14:39:28 -07001092 // Rather than removing the writer immediately, append it to a queue of old writers to
1093 // be garbage-collected later. This allows us to continue to view old logs for a while.
1094 Mutex::Autolock _l(mUnregisteredWritersLock);
1095 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001096}
1097
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098// IAudioFlinger interface
1099
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001100status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
1101 media::CreateTrackResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102{
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001103 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08001104 CreateTrackInput input = VALUE_OR_RETURN_STATUS(CreateTrackInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001105 CreateTrackOutput output;
1106
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 sp<PlaybackThread::Track> track;
1108 sp<TrackHandle> trackHandle;
1109 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -08001111 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -08001112 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001113 std::vector<audio_io_handle_t> secondaryOutputs;
jiabinc658e452022-10-21 20:52:21 +00001114 bool isSpatialized = false;
1115 bool isBitPerfect = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001117 // TODO b/182392553: refactor or make clearer
1118 pid_t clientPid =
Svet Ganov33761132021-05-13 22:51:08 +00001119 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(input.clientInfo.attributionSource.pid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001120 bool updatePid = (clientPid == (pid_t)-1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001121 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001122 uid_t clientUid =
Svet Ganov33761132021-05-13 22:51:08 +00001123 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(input.clientInfo.attributionSource.uid));
Eric Laurent6c796322019-04-09 14:13:17 -07001124 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
1125 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -07001126 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -07001127
Svet Ganov33761132021-05-13 22:51:08 +00001128 AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource;
Eric Laurent9ff3e532022-11-10 16:04:44 +01001129 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -08001130 ALOGW_IF(clientUid != callingUid,
1131 "%s uid %d tried to pass itself off as %d",
1132 __FUNCTION__, callingUid, clientUid);
Svet Ganov33761132021-05-13 22:51:08 +00001133 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Eric Laurent21da6472017-11-09 16:29:26 -08001134 clientUid = callingUid;
1135 updatePid = true;
1136 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07001137 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -08001138 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001139 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001140 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -08001141 __func__, callingUid, callingPid, clientPid);
1142 clientPid = callingPid;
Svet Ganov33761132021-05-13 22:51:08 +00001143 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001144 }
Eric Laurent9ff3e532022-11-10 16:04:44 +01001145 adjAttributionSource = AudioFlinger::checkAttributionSourcePackage(
1146 adjAttributionSource);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001147
Eric Laurent21da6472017-11-09 16:29:26 -08001148 audio_session_t sessionId = input.sessionId;
1149 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1150 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001151 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1152 lStatus = BAD_VALUE;
1153 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -08001154 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001155
Eric Laurent21da6472017-11-09 16:29:26 -08001156 output.sessionId = sessionId;
1157 output.outputId = AUDIO_IO_HANDLE_NONE;
1158 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -07001159 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Svet Ganov33761132021-05-13 22:51:08 +00001160 adjAttributionSource, &input.config, input.flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001161 &output.selectedDeviceId, &portId, &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +00001162 &isSpatialized, &isBitPerfect);
Eric Laurent21da6472017-11-09 16:29:26 -08001163
1164 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1165 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
1166 goto Exit;
1167 }
Glenn Kasten263709e2012-01-06 08:40:01 -08001168 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
1169 // but if someone uses binder directly they could bypass that and cause us to crash
1170 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001171 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 lStatus = BAD_VALUE;
1173 goto Exit;
1174 }
1175
Glenn Kasten53b5d092014-02-05 10:00:23 -08001176 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -08001177 if (!audio_is_output_channel(input.config.channel_mask)) {
1178 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001179 lStatus = BAD_VALUE;
1180 goto Exit;
1181 }
1182
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001183 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -08001184 if (!audio_is_valid_format(input.config.format)) {
1185 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -07001186 lStatus = BAD_VALUE;
1187 goto Exit;
1188 }
1189
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 {
1191 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -08001192 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -08001194 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 lStatus = BAD_VALUE;
1196 goto Exit;
1197 }
1198
Eric Laurent21da6472017-11-09 16:29:26 -08001199 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200
Glenn Kastene848bd92014-03-13 15:00:32 -07001201 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -08001202 // check if an effect chain with the same session ID is present on another
1203 // output thread and move it here.
1204 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1205 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
1206 if (mPlaybackThreads.keyAt(i) != output.outputId) {
1207 uint32_t sessions = t->hasAudioSession(sessionId);
1208 if (sessions & ThreadBase::EFFECT_SESSION) {
1209 effectThread = t.get();
1210 break;
Eric Laurentde070132010-07-13 04:45:46 -07001211 }
1212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213 }
Eric Laurent21da6472017-11-09 16:29:26 -08001214 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215
Eric Laurent21da6472017-11-09 16:29:26 -08001216 output.sampleRate = input.config.sample_rate;
1217 output.frameCount = input.frameCount;
1218 output.notificationFrameCount = input.notificationFrameCount;
1219 output.flags = input.flags;
Andy Hunga2159aa2021-07-20 13:01:52 -07001220 output.streamType = streamType;
Eric Laurent21da6472017-11-09 16:29:26 -08001221
Eric Laurent42984412019-05-09 17:57:03 -07001222 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001223 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -08001224 &output.frameCount, &output.notificationFrameCount,
1225 input.notificationsPerBuffer, input.speed,
1226 input.sharedBuffer, sessionId, &output.flags,
Svet Ganov33761132021-05-13 22:51:08 +00001227 callingPid, adjAttributionSource, input.clientInfo.clientTid,
jiabinc658e452022-10-21 20:52:21 +00001228 &lStatus, portId, input.audioTrackCallback, isSpatialized,
1229 isBitPerfect);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001230 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -07001231 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -07001232
Eric Laurent21da6472017-11-09 16:29:26 -08001233 output.afFrameCount = thread->frameCount();
1234 output.afSampleRate = thread->sampleRate();
Robert Wu310037a2022-09-06 21:48:18 +00001235 output.afChannelMask = static_cast<audio_channel_mask_t>(thread->channelMask() |
1236 thread->hapticChannelMask());
1237 output.afFormat = thread->format();
Eric Laurent21da6472017-11-09 16:29:26 -08001238 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -08001239 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -08001240
Kevin Rocard153f92d2018-12-18 18:33:28 -08001241 if (lStatus == NO_ERROR) {
jiabin87991352023-04-25 20:59:55 +00001242 // no risk of deadlock because AudioFlinger::mLock is held
1243 Mutex::Autolock _dl(thread->mLock);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001244 // Connect secondary outputs. Failure on a secondary output must not imped the primary
1245 // Any secondary output setup failure will lead to a desync between the AP and AF until
1246 // the track is destroyed.
jiabinf042b9b2021-05-07 23:46:28 +00001247 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
jiabin87991352023-04-25 20:59:55 +00001248 // move effect chain to this output thread if an effect on same session was waiting
1249 // for a track to be created
1250 if (effectThread != nullptr) {
1251 Mutex::Autolock _sl(effectThread->mLock);
1252 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
1253 effectThreadId = thread->id();
1254 effectIds = thread->getEffectIds_l(sessionId);
1255 }
Eric Laurent6c796322019-04-09 14:13:17 -07001256 }
Eric Laurent39e94f82010-07-28 01:32:47 -07001257 }
Eric Laurenta011e352012-03-29 15:51:43 -07001258
1259 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001260 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -08001261 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -07001262 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -07001263 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07001264 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -07001265 } else {
1266 mPendingSyncEvents[i]->cancel();
1267 }
Eric Laurenta011e352012-03-29 15:51:43 -07001268 mPendingSyncEvents.removeAt(i);
1269 i--;
1270 }
1271 }
1272 }
Andy Hung6eff0ff2021-07-30 19:01:48 -07001273 if ((output.flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
1274 setAudioHwSyncForSession_l(thread, sessionId);
1275 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276 }
Glenn Kastene198c362013-08-13 09:13:36 -07001277
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001278 if (lStatus != NO_ERROR) {
1279 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001280 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001281 // Don't hold mClientLock when releasing the reference on the track as the
1282 // destructor will acquire it.
1283 {
1284 Mutex::Autolock _cl(mClientLock);
1285 client.clear();
1286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001288 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289 }
1290
Eric Laurent6c796322019-04-09 14:13:17 -07001291 // effectThreadId is not NONE if an effect chain corresponding to the track session
1292 // was found on another thread and must be moved on this thread
1293 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1294 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1295 }
1296
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001297 output.audioTrack = new TrackHandle(track);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001298 _output = VALUE_OR_FATAL(output.toAidl());
1299
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001301 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001302 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001303 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001304 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305}
1306
Glenn Kasten2c073da2016-02-26 09:14:08 -08001307uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001308{
1309 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001310 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001311 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001312 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313 return 0;
1314 }
1315 return thread->sampleRate();
1316}
1317
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001318audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001319{
1320 Mutex::Autolock _l(mLock);
1321 PlaybackThread *thread = checkPlaybackThread_l(output);
1322 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001323 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001324 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325 }
1326 return thread->format();
1327}
1328
Glenn Kasten2c073da2016-02-26 09:14:08 -08001329size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330{
1331 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001332 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001333 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001334 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001335 return 0;
1336 }
Glenn Kasten58912562012-04-03 10:45:00 -07001337 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1338 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339 return thread->frameCount();
1340}
1341
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001342size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1343{
1344 Mutex::Autolock _l(mLock);
1345 ThreadBase *thread = checkThread_l(ioHandle);
1346 if (thread == NULL) {
1347 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1348 return 0;
1349 }
1350 return thread->frameCountHAL();
1351}
1352
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001353uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354{
1355 Mutex::Autolock _l(mLock);
1356 PlaybackThread *thread = checkPlaybackThread_l(output);
1357 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001358 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359 return 0;
1360 }
1361 return thread->latency();
1362}
1363
1364status_t AudioFlinger::setMasterVolume(float value)
1365{
Eric Laurenta1884f92011-08-23 08:25:03 -07001366 status_t ret = initCheck();
1367 if (ret != NO_ERROR) {
1368 return ret;
1369 }
1370
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371 // check calling permissions
1372 if (!settingsAllowed()) {
1373 return PERMISSION_DENIED;
1374 }
1375
Eric Laurenta4c5a552012-03-29 10:12:40 -07001376 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001377 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001378
John Grossmanee578c02012-07-23 17:05:46 -07001379 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001380 {
John Grossmanee578c02012-07-23 17:05:46 -07001381 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001382 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1383 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001384
Eric Laurent00abf0d2020-04-22 19:28:22 -07001385 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1386 if (dev->canSetMasterVolume()) {
1387 dev->hwDevice()->setMasterVolume(value);
1388 }
1389 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 }
John Grossmanee578c02012-07-23 17:05:46 -07001392 // Now set the master volume in each playback thread. Playback threads
1393 // assigned to HALs which do not have master volume support will apply
1394 // master volume during the mix operation. Threads with HALs which do
1395 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001396 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1397 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1398 continue;
1399 }
John Grossmanee578c02012-07-23 17:05:46 -07001400 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402
1403 return NO_ERROR;
1404}
1405
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001406status_t AudioFlinger::setMasterBalance(float balance)
1407{
1408 status_t ret = initCheck();
1409 if (ret != NO_ERROR) {
1410 return ret;
1411 }
1412
1413 // check calling permissions
1414 if (!settingsAllowed()) {
1415 return PERMISSION_DENIED;
1416 }
1417
1418 // check range
1419 if (isnan(balance) || fabs(balance) > 1.f) {
1420 return BAD_VALUE;
1421 }
1422
1423 Mutex::Autolock _l(mLock);
1424
1425 // short cut.
1426 if (mMasterBalance == balance) return NO_ERROR;
1427
1428 mMasterBalance = balance;
1429
1430 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1431 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1432 continue;
1433 }
1434 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1435 }
1436
1437 return NO_ERROR;
1438}
1439
Glenn Kastenf78aee72012-01-04 11:00:47 -08001440status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441{
Eric Laurenta1884f92011-08-23 08:25:03 -07001442 status_t ret = initCheck();
1443 if (ret != NO_ERROR) {
1444 return ret;
1445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446
1447 // check calling permissions
1448 if (!settingsAllowed()) {
1449 return PERMISSION_DENIED;
1450 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001451 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001452 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 return BAD_VALUE;
1454 }
1455
1456 { // scope for the lock
1457 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001458 if (mPrimaryHardwareDev == nullptr) {
1459 return INVALID_OPERATION;
1460 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001461 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001462 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001463 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464 mHardwareStatus = AUDIO_HW_IDLE;
1465 }
1466
1467 if (NO_ERROR == ret) {
1468 Mutex::Autolock _l(mLock);
1469 mMode = mode;
Andy Hung920f6572022-10-06 12:09:49 -07001470 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001471 mPlaybackThreads.valueAt(i)->setMode(mode);
Andy Hung920f6572022-10-06 12:09:49 -07001472 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 }
1474
Joey Poomarin52989982020-03-05 17:40:49 +08001475 mediametrics::LogItem(mMetricsId)
1476 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1477 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1478 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 return ret;
1480}
1481
1482status_t AudioFlinger::setMicMute(bool state)
1483{
Eric Laurenta1884f92011-08-23 08:25:03 -07001484 status_t ret = initCheck();
1485 if (ret != NO_ERROR) {
1486 return ret;
1487 }
1488
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 // check calling permissions
1490 if (!settingsAllowed()) {
1491 return PERMISSION_DENIED;
1492 }
1493
1494 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001495 if (mPrimaryHardwareDev == nullptr) {
1496 return INVALID_OPERATION;
1497 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001498 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1499 if (primaryDev == nullptr) {
1500 ALOGW("%s: no primary HAL device", __func__);
1501 return INVALID_OPERATION;
1502 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001504 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001505 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001506 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001507 if (dev != primaryDev) {
1508 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001509 }
1510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001512 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 return ret;
1514}
1515
1516bool AudioFlinger::getMicMute() const
1517{
Eric Laurenta1884f92011-08-23 08:25:03 -07001518 status_t ret = initCheck();
1519 if (ret != NO_ERROR) {
1520 return false;
1521 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001522 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001523 if (mPrimaryHardwareDev == nullptr) {
1524 return false;
1525 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001526 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1527 if (primaryDev == nullptr) {
1528 ALOGW("%s: no primary HAL device", __func__);
1529 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001530 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001531 bool state;
1532 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1533 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001535 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1536 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537}
1538
Eric Laurent5ada82e2019-08-29 17:53:54 -07001539void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001540{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001541 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001542
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001543 AutoMutex lock(mLock);
1544 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001545 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001546 }
1547 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001548 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001549 }
1550}
1551
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552status_t AudioFlinger::setMasterMute(bool muted)
1553{
John Grossmand8f178d2012-07-20 14:51:35 -07001554 status_t ret = initCheck();
1555 if (ret != NO_ERROR) {
1556 return ret;
1557 }
1558
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559 // check calling permissions
1560 if (!settingsAllowed()) {
1561 return PERMISSION_DENIED;
1562 }
1563
John Grossmanee578c02012-07-23 17:05:46 -07001564 Mutex::Autolock _l(mLock);
1565 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001566
John Grossmanee578c02012-07-23 17:05:46 -07001567 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001568 {
John Grossmanee578c02012-07-23 17:05:46 -07001569 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001570 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1571 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001572
Eric Laurent00abf0d2020-04-22 19:28:22 -07001573 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1574 if (dev->canSetMasterMute()) {
1575 dev->hwDevice()->setMasterMute(muted);
1576 }
1577 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001578 }
John Grossmand8f178d2012-07-20 14:51:35 -07001579 }
1580
John Grossmanee578c02012-07-23 17:05:46 -07001581 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001582 // assigned to HALs which do not have master mute support will apply master mute
1583 // during the mix operation. Threads with HALs which do support master mute
1584 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001585 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1586 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1587 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001588 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589
1590 return NO_ERROR;
1591}
1592
1593float AudioFlinger::masterVolume() const
1594{
Glenn Kasten98067102011-12-13 11:47:54 -08001595 Mutex::Autolock _l(mLock);
1596 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597}
1598
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001599status_t AudioFlinger::getMasterBalance(float *balance) const
1600{
1601 Mutex::Autolock _l(mLock);
1602 *balance = getMasterBalance_l();
1603 return NO_ERROR; // if called through binder, may return a transactional error
1604}
1605
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606bool AudioFlinger::masterMute() const
1607{
Glenn Kasten98067102011-12-13 11:47:54 -08001608 Mutex::Autolock _l(mLock);
1609 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610}
1611
John Grossman4ff14ba2012-02-08 16:37:41 -08001612float AudioFlinger::masterVolume_l() const
1613{
John Grossman4ff14ba2012-02-08 16:37:41 -08001614 return mMasterVolume;
1615}
1616
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001617float AudioFlinger::getMasterBalance_l() const
1618{
1619 return mMasterBalance;
1620}
1621
John Grossmand8f178d2012-07-20 14:51:35 -07001622bool AudioFlinger::masterMute_l() const
1623{
John Grossmanee578c02012-07-23 17:05:46 -07001624 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001625}
1626
Eric Laurent223fd5c2014-11-11 13:43:36 -08001627status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1628{
1629 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001630 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001631 return BAD_VALUE;
1632 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001633 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1634 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1635 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001636 return PERMISSION_DENIED;
1637 }
1638
1639 return NO_ERROR;
1640}
1641
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001642status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1643 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644{
1645 // check calling permissions
1646 if (!settingsAllowed()) {
1647 return PERMISSION_DENIED;
1648 }
1649
Eric Laurent223fd5c2014-11-11 13:43:36 -08001650 status_t status = checkStreamType(stream);
1651 if (status != NO_ERROR) {
1652 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 }
Eric Laurent98e38192018-02-15 18:31:53 -08001654 if (output == AUDIO_IO_HANDLE_NONE) {
1655 return BAD_VALUE;
1656 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001657 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1658 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659
1660 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001661 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1662 if (volumeInterface == NULL) {
1663 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 }
Eric Laurent98e38192018-02-15 18:31:53 -08001665 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666
1667 return NO_ERROR;
1668}
1669
Eric Laurent076e7c72022-05-03 18:12:28 +02001670status_t AudioFlinger::setRequestedLatencyMode(
Eric Laurent68a40a82022-05-03 18:15:04 +02001671 audio_io_handle_t output, audio_latency_mode_t mode) {
Eric Laurent076e7c72022-05-03 18:12:28 +02001672 if (output == AUDIO_IO_HANDLE_NONE) {
1673 return BAD_VALUE;
1674 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001675 AutoMutex lock(mLock);
1676 PlaybackThread *thread = checkPlaybackThread_l(output);
1677 if (thread == nullptr) {
1678 return BAD_VALUE;
1679 }
1680 return thread->setRequestedLatencyMode(mode);
Eric Laurent076e7c72022-05-03 18:12:28 +02001681}
1682
1683status_t AudioFlinger::getSupportedLatencyModes(audio_io_handle_t output,
Eric Laurent68a40a82022-05-03 18:15:04 +02001684 std::vector<audio_latency_mode_t>* modes) {
Eric Laurent076e7c72022-05-03 18:12:28 +02001685 if (output == AUDIO_IO_HANDLE_NONE) {
1686 return BAD_VALUE;
1687 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001688 AutoMutex lock(mLock);
1689 PlaybackThread *thread = checkPlaybackThread_l(output);
1690 if (thread == nullptr) {
1691 return BAD_VALUE;
1692 }
1693 return thread->getSupportedLatencyModes(modes);
Eric Laurent076e7c72022-05-03 18:12:28 +02001694}
1695
Eric Laurent50d72582022-12-20 20:20:23 +01001696status_t AudioFlinger::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurent52057642022-12-16 11:45:07 +01001697 Mutex::Autolock _l(mLock);
1698 status_t status = INVALID_OPERATION;
1699 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1700 // Success if at least one PlaybackThread supports Bluetooth latency modes
Eric Laurent50d72582022-12-20 20:20:23 +01001701 if (mPlaybackThreads.valueAt(i)->setBluetoothVariableLatencyEnabled(enabled) == NO_ERROR) {
Eric Laurent52057642022-12-16 11:45:07 +01001702 status = NO_ERROR;
1703 }
1704 }
1705 if (status == NO_ERROR) {
1706 mBluetoothLatencyModesEnabled.store(enabled);
1707 }
1708 return status;
1709}
1710
Eric Laurent50d72582022-12-20 20:20:23 +01001711status_t AudioFlinger::isBluetoothVariableLatencyEnabled(bool *enabled) {
1712 if (enabled == nullptr) {
1713 return BAD_VALUE;
1714 }
1715 *enabled = mBluetoothLatencyModesEnabled.load();
1716 return NO_ERROR;
1717}
1718
1719status_t AudioFlinger::supportsBluetoothVariableLatency(bool* support) {
Eric Laurent52057642022-12-16 11:45:07 +01001720 if (support == nullptr) {
1721 return BAD_VALUE;
1722 }
1723 Mutex::Autolock _l(mLock);
1724 *support = false;
1725 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurent50d72582022-12-20 20:20:23 +01001726 if (mAudioHwDevs.valueAt(i)->supportsBluetoothVariableLatency()) {
Eric Laurent52057642022-12-16 11:45:07 +01001727 *support = true;
1728 break;
1729 }
1730 }
1731 return NO_ERROR;
1732}
1733
Vlad Popae3fd1c22022-11-07 21:03:18 +01001734status_t AudioFlinger::getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback,
1735 sp<media::ISoundDose>* soundDose) {
1736 if (soundDose == nullptr) {
1737 return BAD_VALUE;
1738 }
1739
1740 *soundDose = mMelReporter->getSoundDoseInterface(callback);
Vlad Popa63f047e2022-11-05 14:09:19 +01001741 return NO_ERROR;
1742}
1743
Glenn Kastenfff6d712012-01-12 16:38:12 -08001744status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745{
1746 // check calling permissions
1747 if (!settingsAllowed()) {
1748 return PERMISSION_DENIED;
1749 }
1750
Eric Laurent223fd5c2014-11-11 13:43:36 -08001751 status_t status = checkStreamType(stream);
1752 if (status != NO_ERROR) {
1753 return status;
1754 }
1755 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1756
1757 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001758 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 return BAD_VALUE;
1760 }
1761
Eric Laurent93575202011-01-18 18:39:02 -08001762 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001764 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1765 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1766 volumeInterfaces[i]->setStreamMute(stream, muted);
1767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768
1769 return NO_ERROR;
1770}
1771
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001772float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001774 status_t status = checkStreamType(stream);
1775 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 return 0.0f;
1777 }
Eric Laurent98e38192018-02-15 18:31:53 -08001778 if (output == AUDIO_IO_HANDLE_NONE) {
1779 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 }
1781
Eric Laurent98e38192018-02-15 18:31:53 -08001782 AutoMutex lock(mLock);
1783 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1784 if (volumeInterface == NULL) {
1785 return 0.0f;
1786 }
1787
1788 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789}
1790
Glenn Kastenfff6d712012-01-12 16:38:12 -08001791bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001793 status_t status = checkStreamType(stream);
1794 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 return true;
1796 }
1797
Glenn Kasten6637baa2012-01-09 09:40:36 -08001798 AutoMutex lock(mLock);
1799 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800}
1801
Eric Laurent054d9d32015-04-24 08:48:48 -07001802
Andy Hungd9ef4b12020-11-11 15:13:18 -08001803void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
Eric Laurent054d9d32015-04-24 08:48:48 -07001804{
1805 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1806 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1807 }
1808}
1809
jiabinc52b1ff2019-10-31 17:20:42 -07001810void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1811{
1812 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1813 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1814 }
1815}
1816
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001817// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1818void AudioFlinger::forwardParametersToDownstreamPatches_l(
1819 audio_io_handle_t upStream, const String8& keyValuePairs,
Andy Hung920f6572022-10-06 12:09:49 -07001820 const std::function<bool(const sp<PlaybackThread>&)>& useThread)
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001821{
1822 std::vector<PatchPanel::SoftwarePatch> swPatches;
1823 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1824 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1825 __func__, swPatches.size(), upStream);
1826 for (const auto& swPatch : swPatches) {
1827 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1828 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1829 downStream->setParameters(keyValuePairs);
1830 }
1831 }
1832}
1833
Eric Laurent74c38dc2020-12-23 18:19:44 +01001834// Update downstream patches for all playback threads attached to an MSD module
1835void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
Andy Hung920f6572022-10-06 12:09:49 -07001836 const std::set<audio_io_handle_t>& streams)
Eric Laurent74c38dc2020-12-23 18:19:44 +01001837{
1838 for (const audio_io_handle_t stream : streams) {
1839 PlaybackThread *playbackThread = checkPlaybackThread_l(stream);
1840 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1841 continue;
1842 }
1843 playbackThread->setDownStreamPatch(patch);
1844 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1845 }
1846}
1847
Eric Laurentf1047e82018-04-16 19:18:20 -07001848// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1849// Some keys are used for audio routing and audio path configuration and should be reserved for use
1850// by audio policy and audio flinger for functional, privacy and security reasons.
1851void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1852{
1853 static const String8 kReservedParameters[] = {
1854 String8(AudioParameter::keyRouting),
1855 String8(AudioParameter::keySamplingRate),
1856 String8(AudioParameter::keyFormat),
1857 String8(AudioParameter::keyChannels),
1858 String8(AudioParameter::keyFrameCount),
1859 String8(AudioParameter::keyInputSource),
1860 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001861 String8(AudioParameter::keyDeviceConnect),
1862 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001863 String8(AudioParameter::keyStreamSupportedFormats),
1864 String8(AudioParameter::keyStreamSupportedChannels),
1865 String8(AudioParameter::keyStreamSupportedSamplingRates),
Andy Hungdda7aed2023-03-27 15:53:06 -07001866 String8(AudioParameter::keyClosing),
1867 String8(AudioParameter::keyExiting),
Eric Laurentf1047e82018-04-16 19:18:20 -07001868 };
1869
Andy Hung4ef19fa2018-05-15 19:35:29 -07001870 if (isAudioServerUid(callingUid)) {
1871 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001872 }
1873
1874 AudioParameter param = AudioParameter(keyValuePairs);
1875 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001876 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001877 for (auto& key : kReservedParameters) {
1878 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001879 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001880 param.remove(key);
1881 }
1882 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001883 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1884 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001885 keyValuePairs = param.toString();
1886}
1887
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001888void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1889 size_t rejectedKVPSize, const String8& rejectedKVPs,
1890 uid_t callingUid) {
1891 auto prefix = String8::format("UID %5d", callingUid);
1892 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1893 if (rejectedKVPSize != 0) {
1894 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1895 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1896 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1897 } else {
1898 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1899 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1900 }
1901}
1902
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001903status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904{
Eric Laurentf1047e82018-04-16 19:18:20 -07001905 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1906 ioHandle, keyValuePairs.string(),
1907 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001908
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 // check calling permissions
1910 if (!settingsAllowed()) {
1911 return PERMISSION_DENIED;
1912 }
1913
Eric Laurentf1047e82018-04-16 19:18:20 -07001914 String8 filteredKeyValuePairs = keyValuePairs;
1915 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1916
1917 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1918
Glenn Kasten142f5192014-03-25 17:44:59 -07001919 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1920 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001921 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001922 // result will remain NO_INIT if no audio device is present
1923 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001924 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001925 AutoMutex lock(mHardwareLock);
1926 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1927 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001928 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001929 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001930 // return success if at least one audio device accepts the parameters as not all
1931 // HALs are requested to support all parameters. If no audio device supports the
1932 // requested parameters, the last error is reported.
1933 if (final_result != NO_ERROR) {
1934 final_result = result;
1935 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001936 }
1937 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001938 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001939 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001940 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001941 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001942 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1943 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001944 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001945 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001946 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001947 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001948 }
1949 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001950 String8 screenState;
1951 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001952 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001953 if (isOff != (AudioFlinger::mScreenState & 1)) {
1954 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001955 }
1956 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001957 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 }
1959
1960 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1961 // and the thread is exited once the lock is released
1962 sp<ThreadBase> thread;
1963 {
1964 Mutex::Autolock _l(mLock);
1965 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001966 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001968 if (thread == 0) {
1969 thread = checkMmapThread_l(ioHandle);
1970 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001971 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001972 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001973 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001974 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001975 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1976 (value != 0)) {
Andy Hungd9ef4b12020-11-11 15:13:18 -08001977 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001978 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979 }
1980 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001981 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001982 status_t result = thread->setParameters(filteredKeyValuePairs);
1983 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1984 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 }
1986 return BAD_VALUE;
1987}
1988
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001989String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001991 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1992 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993
Eric Laurenta4c5a552012-03-29 10:12:40 -07001994 Mutex::Autolock _l(mLock);
1995
Glenn Kasten142f5192014-03-25 17:44:59 -07001996 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001997 String8 out_s8;
1998
Eric Laurent00abf0d2020-04-22 19:28:22 -07001999 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07002000 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002001 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08002002 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002003 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07002004 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08002005 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002006 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07002007 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002008 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 }
2010
Eric Laurent6acd1d42017-01-04 14:23:29 -08002011 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
2012 if (thread == NULL) {
2013 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
2014 if (thread == NULL) {
2015 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
2016 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07002017 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002018 }
2019 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002021 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022}
2023
Glenn Kastendd8104c2012-07-02 12:42:44 -07002024size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
2025 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026{
Eric Laurenta1884f92011-08-23 08:25:03 -07002027 status_t ret = initCheck();
2028 if (ret != NO_ERROR) {
2029 return 0;
2030 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08002031 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08002032 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08002033 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07002034 return 0;
2035 }
Eric Laurenta1884f92011-08-23 08:25:03 -07002036
Glenn Kasten2b213bc2012-02-02 14:05:20 -08002037 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002038 if (mPrimaryHardwareDev == nullptr) {
2039 return 0;
2040 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08002041 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002042
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002043 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung920f6572022-10-06 12:09:49 -07002044
Judy Hsiaoabab5222019-11-09 18:14:58 +08002045 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
Andy Hung920f6572022-10-06 12:09:49 -07002046 if (channelMask != AUDIO_CHANNEL_IN_MONO) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002047 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
Andy Hung920f6572022-10-06 12:09:49 -07002048 }
2049 if (channelMask != AUDIO_CHANNEL_IN_STEREO) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002050 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
Andy Hung920f6572022-10-06 12:09:49 -07002051 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002052
2053 std::vector<audio_format_t> formats = {format};
Andy Hung920f6572022-10-06 12:09:49 -07002054 if (format != AUDIO_FORMAT_PCM_16_BIT) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002055 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
Andy Hung920f6572022-10-06 12:09:49 -07002056 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002057
2058 std::vector<uint32_t> sampleRates = {sampleRate};
2059 static const uint32_t SR_44100 = 44100;
2060 static const uint32_t SR_48000 = 48000;
Andy Hung920f6572022-10-06 12:09:49 -07002061 if (sampleRate != SR_48000) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002062 sampleRates.push_back(SR_48000);
Andy Hung920f6572022-10-06 12:09:49 -07002063 }
2064 if (sampleRate != SR_44100) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002065 sampleRates.push_back(SR_44100);
Andy Hung920f6572022-10-06 12:09:49 -07002066 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002067
Glenn Kasten2b213bc2012-02-02 14:05:20 -08002068 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08002069
Robin Lee9899ff72019-12-24 22:02:08 +01002070 // Change parameters of the configuration each iteration until we find a
2071 // configuration that the device will support.
2072 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08002073 for (auto testChannelMask : channelMasks) {
2074 config.channel_mask = testChannelMask;
2075 for (auto testFormat : formats) {
2076 config.format = testFormat;
2077 for (auto testSampleRate : sampleRates) {
2078 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01002079
Judy Hsiaoabab5222019-11-09 18:14:58 +08002080 size_t bytes = 0;
2081 status_t result = dev->getInputBufferSize(&config, &bytes);
2082 if (result != OK || bytes == 0) {
2083 continue;
2084 }
2085
2086 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
2087 config.format != format) {
2088 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
2089 uint32_t srcChannelCount =
2090 audio_channel_count_from_in_mask(config.channel_mask);
2091 size_t srcFrames =
2092 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
2093 size_t dstFrames = destinationFramesPossible(
2094 srcFrames, config.sample_rate, sampleRate);
2095 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
2096 }
2097 return bytes;
2098 }
2099 }
Andy Hung6770c6f2015-04-07 13:43:36 -07002100 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002101
2102 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
2103 "format %#x, channelMask %#x",sampleRate, format, channelMask);
2104 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105}
2106
Glenn Kasten5f972c02014-01-13 09:59:31 -08002107uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 Mutex::Autolock _l(mLock);
2110
2111 RecordThread *recordThread = checkRecordThread_l(ioHandle);
2112 if (recordThread != NULL) {
2113 return recordThread->getInputFramesLost();
2114 }
2115 return 0;
2116}
2117
2118status_t AudioFlinger::setVoiceVolume(float value)
2119{
Eric Laurenta1884f92011-08-23 08:25:03 -07002120 status_t ret = initCheck();
2121 if (ret != NO_ERROR) {
2122 return ret;
2123 }
2124
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125 // check calling permissions
2126 if (!settingsAllowed()) {
2127 return PERMISSION_DENIED;
2128 }
2129
2130 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002131 if (mPrimaryHardwareDev == nullptr) {
2132 return INVALID_OPERATION;
2133 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002134 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08002135 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002136 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 mHardwareStatus = AUDIO_HW_IDLE;
2138
Joey Poomarin52989982020-03-05 17:40:49 +08002139 mediametrics::LogItem(mMetricsId)
2140 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
2141 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
2142 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 return ret;
2144}
2145
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002146status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002147 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 Mutex::Autolock _l(mLock);
2150
2151 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
2152 if (playbackThread != NULL) {
2153 return playbackThread->getRenderPosition(halFrames, dspFrames);
2154 }
2155
2156 return BAD_VALUE;
2157}
2158
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002159void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07002162 if (client == 0) {
2163 return;
2164 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002165 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08002166 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07002167 {
2168 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07002169 if (mNotificationClients.indexOfKey(pid) < 0) {
2170 sp<NotificationClient> notificationClient = new NotificationClient(this,
2171 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08002172 pid,
2173 uid);
2174 ALOGV("registerClient() client %p, pid %d, uid %u",
2175 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176
Eric Laurent021cf962014-05-13 10:18:14 -07002177 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178
Marco Nelissen06b46062014-11-14 07:58:25 -08002179 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07002180 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07002181 }
2182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183
Eric Laurent021cf962014-05-13 10:18:14 -07002184 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002185 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002186 // the config change is always sent from playback or record threads to avoid deadlock
2187 // with AudioSystem::gLock
2188 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002189 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002192 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002193 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 }
2195}
2196
2197void AudioFlinger::removeNotificationClient(pid_t pid)
2198{
Eric Laurent6c796322019-04-09 14:13:17 -07002199 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07002200 {
Eric Laurent6c796322019-04-09 14:13:17 -07002201 Mutex::Autolock _l(mLock);
2202 {
2203 Mutex::Autolock _cl(mClientLock);
2204 mNotificationClients.removeItem(pid);
2205 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002206
Eric Laurent6c796322019-04-09 14:13:17 -07002207 ALOGV("%d died, releasing its sessions", pid);
2208 size_t num = mAudioSessionRefs.size();
2209 bool removed = false;
2210 for (size_t i = 0; i < num; ) {
2211 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2212 ALOGV(" pid %d @ %zu", ref->mPid, i);
2213 if (ref->mPid == pid) {
2214 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
2215 mAudioSessionRefs.removeAt(i);
2216 delete ref;
2217 removed = true;
2218 num--;
2219 } else {
2220 i++;
2221 }
2222 }
2223 if (removed) {
2224 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002225 }
2226 }
Eric Laurent6c796322019-04-09 14:13:17 -07002227 for (auto& effect : removedEffects) {
2228 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002229 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230}
2231
Mikhail Naganov88536df2021-07-26 17:30:29 -07002232void AudioFlinger::ioConfigChanged(audio_io_config_event_t event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002233 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002234 pid_t pid) {
Andy Hungb75b6242021-07-29 16:46:14 +00002235 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
2236 legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002237 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
2238 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002239
Eric Laurent021cf962014-05-13 10:18:14 -07002240 Mutex::Autolock _l(mClientLock);
2241 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002243 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002244 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(eventAidl,
2245 descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002246 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 }
2248}
2249
Eric Laurent076e7c72022-05-03 18:12:28 +02002250void AudioFlinger::onSupportedLatencyModesChanged(
2251 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) {
2252 int32_t outputAidl = VALUE_OR_FATAL(legacy2aidl_audio_io_handle_t_int32_t(output));
Mikhail Naganovf53e1822022-12-18 02:48:14 +00002253 std::vector<media::audio::common::AudioLatencyMode> modesAidl = VALUE_OR_FATAL(
2254 convertContainer<std::vector<media::audio::common::AudioLatencyMode>>(
2255 modes, legacy2aidl_audio_latency_mode_t_AudioLatencyMode));
Eric Laurent076e7c72022-05-03 18:12:28 +02002256
2257 Mutex::Autolock _l(mClientLock);
2258 size_t size = mNotificationClients.size();
2259 for (size_t i = 0; i < size; i++) {
2260 mNotificationClients.valueAt(i)->audioFlingerClient()
2261 ->onSupportedLatencyModesChanged(outputAidl, modesAidl);
2262 }
2263}
2264
Eric Laurent021cf962014-05-13 10:18:14 -07002265// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266void AudioFlinger::removeClient_l(pid_t pid)
2267{
Glenn Kasten827e5f12012-11-02 10:00:06 -07002268 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002269 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 mClients.removeItem(pid);
2271}
2272
Eric Laurent717e1282012-06-29 16:36:52 -07002273// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002274sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
2275 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07002276{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002277 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07002278
2279 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002280 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07002281 ALOG_ASSERT(thread == 0);
2282 thread = mPlaybackThreads.valueAt(i);
2283 }
2284 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002285 if (thread != nullptr) {
2286 return thread;
2287 }
2288 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2289 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
2290 ALOG_ASSERT(thread == 0);
2291 thread = mRecordThreads.valueAt(i);
2292 }
2293 }
2294 if (thread != nullptr) {
2295 return thread;
2296 }
2297 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2298 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
2299 ALOG_ASSERT(thread == 0);
2300 thread = mMmapThreads.valueAt(i);
2301 }
2302 }
Eric Laurent717e1282012-06-29 16:36:52 -07002303 return thread;
2304}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307
2308// ----------------------------------------------------------------------------
2309
2310AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2311 : RefBase(),
2312 mAudioFlinger(audioFlinger),
Atneya3c61d882021-09-20 14:52:15 -04002313 mPid(pid),
2314 mClientAllocator(AllocatorFactory::getClientAllocator()) {}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315
Eric Laurent021cf962014-05-13 10:18:14 -07002316// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317AudioFlinger::Client::~Client()
2318{
2319 mAudioFlinger->removeClient_l(mPid);
2320}
2321
Atneya3c61d882021-09-20 14:52:15 -04002322AllocatorFactory::ClientAllocator& AudioFlinger::Client::allocator()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323{
Atneya3c61d882021-09-20 14:52:15 -04002324 return mClientAllocator;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325}
2326
2327// ----------------------------------------------------------------------------
2328
2329AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002330 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08002331 pid_t pid,
2332 uid_t uid)
2333 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334{
2335}
2336
2337AudioFlinger::NotificationClient::~NotificationClient()
2338{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339}
2340
Glenn Kasten0f11b512014-01-31 16:18:54 -08002341void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342{
2343 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08002344 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345}
2346
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002347// ----------------------------------------------------------------------------
2348AudioFlinger::MediaLogNotifier::MediaLogNotifier()
2349 : mPendingRequests(false) {}
2350
2351
2352void AudioFlinger::MediaLogNotifier::requestMerge() {
2353 AutoMutex _l(mMutex);
2354 mPendingRequests = true;
2355 mCond.signal();
2356}
2357
2358bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002359 // Should already have been checked, but just in case
2360 if (sMediaLogService == 0) {
2361 return false;
2362 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002363 // Wait until there are pending requests
2364 {
2365 AutoMutex _l(mMutex);
2366 mPendingRequests = false; // to ignore past requests
2367 while (!mPendingRequests) {
2368 mCond.wait(mMutex);
2369 // TODO may also need an exitPending check
2370 }
2371 mPendingRequests = false;
2372 }
2373 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002374 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002375 usleep(kPostTriggerSleepPeriod);
2376 return true;
2377}
2378
2379void AudioFlinger::requestLogMerge() {
2380 mMediaLogNotifier->requestMerge();
2381}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382
2383// ----------------------------------------------------------------------------
2384
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002385status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2386 media::CreateRecordResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387{
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002388 CreateRecordInput input = VALUE_OR_RETURN_STATUS(CreateRecordInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002389 CreateRecordOutput output;
2390
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 sp<RecordThread::RecordTrack> recordTrack;
2392 sp<RecordHandle> recordHandle;
2393 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002395 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002396 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397
Eric Laurentf14db3c2017-12-08 14:20:36 -08002398 output.cblk.clear();
2399 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002400 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002401
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002402 // TODO b/182392553: refactor or clean up
Svet Ganov33761132021-05-13 22:51:08 +00002403 AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource;
2404 bool updatePid = (adjAttributionSource.pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002405 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Svet Ganov33761132021-05-13 22:51:08 +00002406 const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(
2407 adjAttributionSource.uid));
Eric Laurent9ff3e532022-11-10 16:04:44 +01002408 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002409 ALOGW_IF(currentUid != callingUid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002410 "%s uid %d tried to pass itself off as %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002411 __FUNCTION__, callingUid, currentUid);
Svet Ganov33761132021-05-13 22:51:08 +00002412 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002413 updatePid = true;
2414 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07002415 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Svet Ganov33761132021-05-13 22:51:08 +00002416 const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
2417 adjAttributionSource.pid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002418 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002419 ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002420 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002421 __func__, callingUid, callingPid, currentPid);
Svet Ganov33761132021-05-13 22:51:08 +00002422 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Marco Nelissendcb346b2015-09-09 10:47:29 -07002423 }
Eric Laurent9ff3e532022-11-10 16:04:44 +01002424 adjAttributionSource = AudioFlinger::checkAttributionSourcePackage(
2425 adjAttributionSource);
Andy Hung6770c6f2015-04-07 13:43:36 -07002426 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08002427 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2428 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002429 lStatus = BAD_VALUE;
2430 goto Exit;
2431 }
2432
Glenn Kasten53b5d092014-02-05 10:00:23 -08002433 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002434 if (!audio_is_input_channel(input.config.channel_mask)) {
2435 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002436 lStatus = BAD_VALUE;
2437 goto Exit;
2438 }
2439
Eric Laurentf14db3c2017-12-08 14:20:36 -08002440 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2441 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2442 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2443 lStatus = BAD_VALUE;
2444 goto Exit;
2445 }
2446
2447 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002448 output.selectedDeviceId = input.selectedDeviceId;
2449 output.flags = input.flags;
2450
Svet Ganov33761132021-05-13 22:51:08 +00002451 client = registerPid(VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid)));
Eric Laurentf14db3c2017-12-08 14:20:36 -08002452
2453 // Not a conventional loop, but a retry loop for at most two iterations total.
2454 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2455 // Exits loop via break on no error of got exit on error
2456 // The sp<> references will be dropped when re-entering scope.
2457 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2458 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002459 // release previously opened input if retrying.
2460 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2461 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002462 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002463 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002464 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002465 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002466 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002467 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002468 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002469 sessionId,
2470 // FIXME compare to AudioTrack
Svet Ganov33761132021-05-13 22:51:08 +00002471 adjAttributionSource,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002472 &input.config,
2473 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002474 if (lStatus != NO_ERROR) {
2475 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2476 goto Exit;
2477 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002478
Glenn Kasten05997e22014-03-13 15:08:33 -07002479 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002481 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002483 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2484 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 goto Exit;
2486 }
2487
Eric Laurentf14db3c2017-12-08 14:20:36 -08002488 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489
Eric Laurentf14db3c2017-12-08 14:20:36 -08002490 output.sampleRate = input.config.sample_rate;
2491 output.frameCount = input.frameCount;
2492 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002493
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002494 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002495 input.config.format, input.config.channel_mask,
2496 &output.frameCount, sessionId,
2497 &output.notificationFrameCount,
Svet Ganov33761132021-05-13 22:51:08 +00002498 callingPid, adjAttributionSource, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002499 input.clientInfo.clientTid,
Eric Laurentec376dc2021-04-08 20:41:22 +02002500 &lStatus, portId, input.maxSharedAudioHistoryMs);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002501 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002502
Eric Laurentf14db3c2017-12-08 14:20:36 -08002503 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2504 // audio policy manager without FAST constraint
2505 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002506 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002507 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002508
2509 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002510 goto Exit;
2511 }
2512
jiabinb00edc32021-08-16 16:27:54 +00002513 if (recordTrack->isFastTrack()) {
2514 output.serverConfig = {
2515 thread->sampleRate(),
2516 thread->channelMask(),
2517 thread->format()
2518 };
2519 } else {
2520 output.serverConfig = {
2521 recordTrack->sampleRate(),
2522 recordTrack->channelMask(),
2523 recordTrack->format()
2524 };
2525 }
2526
Robert Wu310037a2022-09-06 21:48:18 +00002527 output.halConfig = {
2528 thread->sampleRate(),
2529 thread->channelMask(),
2530 thread->format()
2531 };
2532
Eric Laurentf14db3c2017-12-08 14:20:36 -08002533 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2534 // session and move it to this thread.
2535 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2536 if (chain != 0) {
Andy Hung920f6572022-10-06 12:09:49 -07002537 Mutex::Autolock _l2(thread->mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002538 thread->addEffectChain_l(chain);
2539 }
2540 break;
2541 }
2542 // End of retry loop.
2543 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 }
Glenn Kastene198c362013-08-13 09:13:36 -07002545
Eric Laurentf14db3c2017-12-08 14:20:36 -08002546 output.cblk = recordTrack->getCblk();
2547 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002548 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002549
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002550 output.audioRecord = new RecordHandle(recordTrack);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002551 _output = VALUE_OR_FATAL(output.toAidl());
2552
Eric Laurentf14db3c2017-12-08 14:20:36 -08002553Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002554 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002555 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002556 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002557 // Don't hold mClientLock when releasing the reference on the track as the
2558 // destructor will acquire it.
2559 {
2560 Mutex::Autolock _cl(mClientLock);
2561 client.clear();
2562 }
Eric Laurent896c9672017-12-08 14:08:45 -08002563 recordTrack.clear();
2564 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002565 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567 }
2568
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002569 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570}
2571
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002572
2573
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574// ----------------------------------------------------------------------------
2575
Eric Laurenta4c5a552012-03-29 10:12:40 -07002576audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2577{
Eric Laurent44622db2014-08-01 19:00:33 -07002578 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002579 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002580 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002581 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002582 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002583 }
2584 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002585 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002586 return loadHwModule_l(name);
2587}
2588
Eric Laurent00abf0d2020-04-22 19:28:22 -07002589// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002590audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2591{
2592 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2593 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2594 ALOGW("loadHwModule() module %s already loaded", name);
2595 return mAudioHwDevs.keyAt(i);
2596 }
2597 }
2598
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002599 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002600
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002601 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002602 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002603 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002604 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002605 }
Vlad Popa03bd5bc2023-01-17 16:16:51 +01002606 if (!mMelReporter->activateHalSoundDoseComputation(name, dev)) {
Vlad Popa1d5f0d52022-12-18 12:21:26 +01002607 ALOGW("loadHwModule() sound dose reporting is not available");
2608 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002609
2610 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002611 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002612 mHardwareStatus = AUDIO_HW_IDLE;
2613 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002614 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002615 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002616 }
2617
John Grossmanee578c02012-07-23 17:05:46 -07002618 // Check and cache this HAL's level of support for master mute and master
2619 // volume. If this is the first HAL opened, and it supports the get
2620 // methods, use the initial values provided by the HAL as the current
2621 // master mute and volume settings.
2622
2623 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002624 if (0 == mAudioHwDevs.size()) {
2625 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2626 float mv;
2627 if (OK == dev->getMasterVolume(&mv)) {
2628 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002629 }
2630
Eric Laurent00abf0d2020-04-22 19:28:22 -07002631 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2632 bool mm;
2633 if (OK == dev->getMasterMute(&mm)) {
2634 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002635 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002636 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002637
2638 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2639 if (OK == dev->setMasterVolume(mMasterVolume)) {
2640 flags = static_cast<AudioHwDevice::Flags>(flags |
2641 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2642 }
2643
2644 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2645 if (OK == dev->setMasterMute(mMasterMute)) {
2646 flags = static_cast<AudioHwDevice::Flags>(flags |
2647 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2648 }
2649
2650 mHardwareStatus = AUDIO_HW_IDLE;
2651
Mikhail Naganov97373b02018-07-23 13:27:24 -07002652 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002653 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2654 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2655 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002656
Eric Laurent52057642022-12-16 11:45:07 +01002657
2658 if (bool supports = false;
Eric Laurent50d72582022-12-20 20:20:23 +01002659 dev->supportsBluetoothVariableLatency(&supports) == NO_ERROR && supports) {
Eric Laurent52057642022-12-16 11:45:07 +01002660 flags = static_cast<AudioHwDevice::Flags>(flags |
2661 AudioHwDevice::AHWD_SUPPORTS_BT_LATENCY_MODES);
2662 }
2663
Glenn Kastena13cde92016-03-28 15:26:02 -07002664 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002665 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2666 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2667 mPrimaryHardwareDev = audioDevice;
2668 mHardwareStatus = AUDIO_HW_SET_MODE;
2669 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2670 mHardwareStatus = AUDIO_HW_IDLE;
2671 }
2672
Shunkai Yao2b8fed42022-12-09 01:12:02 +00002673 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
jiabine504e7b2021-09-18 00:27:08 +00002674 if (int32_t mixerBursts = dev->getAAudioMixerBurstCount();
jiabina4ff38f2022-02-11 19:42:25 +00002675 mixerBursts > 0 && mixerBursts > mAAudioBurstsPerBuffer) {
jiabine504e7b2021-09-18 00:27:08 +00002676 mAAudioBurstsPerBuffer = mixerBursts;
2677 }
2678 if (int32_t hwBurstMinMicros = dev->getAAudioHardwareBurstMinUsec();
jiabina4ff38f2022-02-11 19:42:25 +00002679 hwBurstMinMicros > 0
2680 && (hwBurstMinMicros < mAAudioHwBurstMinMicros || mAAudioHwBurstMinMicros == 0)) {
jiabine504e7b2021-09-18 00:27:08 +00002681 mAAudioHwBurstMinMicros = hwBurstMinMicros;
2682 }
2683 }
2684
Eric Laurent00abf0d2020-04-22 19:28:22 -07002685 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002686
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002687 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002688
2689 return handle;
2690
2691}
2692
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002693// ----------------------------------------------------------------------------
2694
Glenn Kasten3b16c762012-11-14 08:44:39 -08002695uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002696{
2697 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002698 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002699 return thread != NULL ? thread->sampleRate() : 0;
2700}
2701
Glenn Kastene33054e2012-11-14 12:54:39 -08002702size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002703{
2704 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002705 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002706 return thread != NULL ? thread->frameCountHAL() : 0;
2707}
2708
2709// ----------------------------------------------------------------------------
2710
Andy Hung6f248bb2018-01-23 14:04:37 -08002711status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002712{
2713 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002714 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002715 return PERMISSION_DENIED;
2716 }
2717 Mutex::Autolock _l(mLock);
2718 if (mIsDeviceTypeKnown) {
2719 return INVALID_OPERATION;
2720 }
2721 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002722 mTotalMemory = totalMemory;
2723 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2724 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2725 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2726 // though actual setting is determined through device configuration.
2727 constexpr int64_t GB = 1024 * 1024 * 1024;
2728 mClientSharedHeapSize =
2729 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2730 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2731 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2732 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2733 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002734 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002735
2736 // TODO: Cache the client shared heap size in a persistent property.
2737 // It's possible that a native process or Java service or app accesses audioserver
2738 // after it is registered by system server, but before AudioService updates
2739 // the memory info. This would occur immediately after boot or an audioserver
2740 // crash and restore. Before update from AudioService, the client would get the
2741 // minimum heap size.
2742
2743 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2744 (isLowRamDevice ? "true" : "false"),
2745 (long long)mTotalMemory,
2746 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002747 return NO_ERROR;
2748}
2749
Andy Hung6f248bb2018-01-23 14:04:37 -08002750size_t AudioFlinger::getClientSharedHeapSize() const
2751{
2752 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2753 if (heapSizeInBytes != 0) { // read-only property overrides all.
2754 return heapSizeInBytes;
2755 }
2756 return mClientSharedHeapSize;
2757}
2758
Mikhail Naganovdea53042018-04-26 13:10:21 -07002759status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2760{
2761 ALOGV(__func__);
2762
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08002763 status_t status = AudioValidator::validateAudioPortConfig(*config);
2764 if (status != NO_ERROR) {
2765 return status;
2766 }
2767
Mikhail Naganovdea53042018-04-26 13:10:21 -07002768 audio_module_handle_t module;
2769 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2770 module = config->ext.device.hw_module;
2771 } else {
2772 module = config->ext.mix.hw_module;
2773 }
2774
2775 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002776 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002777 ssize_t index = mAudioHwDevs.indexOfKey(module);
2778 if (index < 0) {
2779 ALOGW("%s() bad hw module %d", __func__, module);
2780 return BAD_VALUE;
2781 }
2782
2783 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2784 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2785}
2786
Eric Laurent93c3d412014-08-01 14:48:35 -07002787audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2788{
2789 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002790
2791 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2792 if (index >= 0) {
2793 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2794 mHwAvSyncIds.valueAt(index), sessionId);
2795 return mHwAvSyncIds.valueAt(index);
2796 }
2797
Eric Laurent00abf0d2020-04-22 19:28:22 -07002798 sp<DeviceHalInterface> dev;
2799 {
2800 AutoMutex lock(mHardwareLock);
2801 if (mPrimaryHardwareDev == nullptr) {
2802 return AUDIO_HW_SYNC_INVALID;
2803 }
2804 dev = mPrimaryHardwareDev->hwDevice();
2805 }
2806 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002807 return AUDIO_HW_SYNC_INVALID;
2808 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002809
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002810 error::Result<audio_hw_sync_t> result = dev->getHwAvSync();
2811 if (!result.ok()) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002812 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2813 return AUDIO_HW_SYNC_INVALID;
2814 }
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002815 audio_hw_sync_t value = VALUE_OR_FATAL(result);
Eric Laurentfa90e842014-10-17 18:12:31 -07002816
2817 // allow only one session for a given HW A/V sync ID.
2818 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002819 if (mHwAvSyncIds.valueAt(i) == value) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002820 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2821 value, mHwAvSyncIds.keyAt(i));
2822 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002823 break;
2824 }
2825 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002826
2827 mHwAvSyncIds.add(sessionId, value);
2828
2829 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2830 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2831 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002832 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002833 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002834 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002835 String8 keyValuePairs = param.toString();
2836 thread->setParameters(keyValuePairs);
2837 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2838 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002839 break;
2840 }
2841 }
2842
2843 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2844 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002845}
2846
Eric Laurent72e3f392015-05-20 14:43:50 -07002847status_t AudioFlinger::systemReady()
2848{
2849 Mutex::Autolock _l(mLock);
2850 ALOGI("%s", __FUNCTION__);
2851 if (mSystemReady) {
2852 ALOGW("%s called twice", __FUNCTION__);
2853 return NO_ERROR;
2854 }
2855 mSystemReady = true;
2856 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2857 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2858 thread->systemReady();
2859 }
2860 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2861 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2862 thread->systemReady();
2863 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02002864 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2865 ThreadBase *thread = (ThreadBase *)mMmapThreads.valueAt(i).get();
2866 thread->systemReady();
2867 }
Vlad Popae8d99472022-06-30 16:02:48 +02002868
2869 // Java services are ready, so we can create a reference to AudioService
2870 getOrCreateAudioManager();
2871
Eric Laurent72e3f392015-05-20 14:43:50 -07002872 return NO_ERROR;
2873}
2874
Vlad Popae8d99472022-06-30 16:02:48 +02002875sp<IAudioManager> AudioFlinger::getOrCreateAudioManager()
2876{
2877 if (mAudioManager.load() == nullptr) {
2878 // use checkService() to avoid blocking
2879 sp<IBinder> binder =
2880 defaultServiceManager()->checkService(String16(kAudioServiceName));
2881 if (binder != nullptr) {
2882 mAudioManager = interface_cast<IAudioManager>(binder);
2883 } else {
2884 ALOGE("%s(): binding to audio service failed.", __func__);
2885 }
2886 }
2887 return mAudioManager.load();
2888}
2889
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08002890status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfoFw> *microphones)
jiabin46a76fa2018-01-05 10:18:21 -08002891{
jiabin9ff780e2018-03-19 18:19:52 -07002892 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002893 status_t status = INVALID_OPERATION;
2894
2895 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Shunkai Yaoed624a72022-12-12 06:11:46 +00002896 std::vector<audio_microphone_characteristic_t> mics;
Eric Laurent00abf0d2020-04-22 19:28:22 -07002897 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2898 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2899 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2900 mHardwareStatus = AUDIO_HW_IDLE;
2901 if (devStatus == NO_ERROR) {
Eric Laurent00abf0d2020-04-22 19:28:22 -07002902 // report success if at least one HW module supports the function.
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08002903 std::transform(mics.begin(), mics.end(), std::back_inserter(*microphones), [](auto& mic)
2904 {
2905 auto microphone =
2906 legacy2aidl_audio_microphone_characteristic_t_MicrophoneInfoFw(mic);
2907 return microphone.ok() ? microphone.value() : media::MicrophoneInfoFw{};
2908 });
Eric Laurent00abf0d2020-04-22 19:28:22 -07002909 status = NO_ERROR;
2910 }
2911 }
2912
jiabin9ff780e2018-03-19 18:19:52 -07002913 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002914}
2915
Eric Laurentfa90e842014-10-17 18:12:31 -07002916// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2917void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2918{
2919 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2920 if (index >= 0) {
2921 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2922 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2923 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002924 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002925 String8 keyValuePairs = param.toString();
2926 thread->setParameters(keyValuePairs);
2927 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2928 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002929 }
2930}
2931
2932
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002933// ----------------------------------------------------------------------------
2934
Eric Laurent83b88082014-06-20 18:31:16 -07002935
Eric Laurent6acd1d42017-01-04 14:23:29 -08002936sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002937 audio_io_handle_t *output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002938 audio_config_t *halConfig,
Andy Hung920f6572022-10-06 12:09:49 -07002939 audio_config_base_t *mixerConfig,
jiabin43810402019-10-24 14:58:31 -07002940 audio_devices_t deviceType,
2941 const String8& address,
2942 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002943{
jiabin43810402019-10-24 14:58:31 -07002944 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002945 if (outHwDev == NULL) {
Eric Laurente28c66d2022-01-21 13:40:41 +01002946 return nullptr;
Eric Laurent83b88082014-06-20 18:31:16 -07002947 }
2948
Eric Laurentcf2c0212014-07-25 16:20:43 -07002949 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002950 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2951 } else {
2952 // Audio Policy does not currently request a specific output handle.
2953 // If this is ever needed, see openInput_l() for example code.
2954 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
Eric Laurente28c66d2022-01-21 13:40:41 +01002955 return nullptr;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002956 }
Eric Laurent83b88082014-06-20 18:31:16 -07002957
Eric Laurente28c66d2022-01-21 13:40:41 +01002958#ifndef MULTICHANNEL_EFFECT_CHAIN
2959 if (flags & AUDIO_OUTPUT_FLAG_SPATIALIZER) {
2960 ALOGE("openOutput_l() cannot create spatializer thread "
2961 "without #define MULTICHANNEL_EFFECT_CHAIN");
2962 return nullptr;
2963 }
2964#endif
2965
Eric Laurent83b88082014-06-20 18:31:16 -07002966 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2967
Eric Laurent83b88082014-06-20 18:31:16 -07002968 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002969 // This if statement allows overriding the audio policy settings
2970 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2971 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2972 // Check only for Normal Mixing mode
2973 if (kEnableExtendedPrecision) {
2974 // Specify format (uncomment one below to choose)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002975 //halConfig->format = AUDIO_FORMAT_PCM_FLOAT;
2976 //halConfig->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2977 //halConfig->format = AUDIO_FORMAT_PCM_32_BIT;
2978 //halConfig->format = AUDIO_FORMAT_PCM_8_24_BIT;
2979 // ALOGV("openOutput_l() upgrading format to %#08x", halConfig->format);
Andy Hung9a592762014-07-21 21:56:01 -07002980 }
2981 if (kEnableExtendedChannels) {
2982 // Specify channel mask (uncomment one below to choose)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002983 //halConfig->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2984 //halConfig->channel_mask = audio_channel_mask_from_representation_and_bits(
Andy Hung9a592762014-07-21 21:56:01 -07002985 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2986 }
Eric Laurent83b88082014-06-20 18:31:16 -07002987 }
2988
Phil Burk062e67a2015-02-11 13:40:50 -08002989 AudioStreamOut *outputStream = NULL;
2990 status_t status = outHwDev->openOutputStream(
2991 &outputStream,
2992 *output,
jiabin43810402019-10-24 14:58:31 -07002993 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002994 flags,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002995 halConfig,
Phil Burk062e67a2015-02-11 13:40:50 -08002996 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002997
2998 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002999
Phil Burk062e67a2015-02-11 13:40:50 -08003000 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003001 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
3002 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07003003 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003004 mMmapThreads.add(*output, thread);
3005 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
3006 *output, thread.get());
3007 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07003008 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003009 sp<PlaybackThread> thread;
jiabinc658e452022-10-21 20:52:21 +00003010 if (flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
3011 thread = sp<BitPerfectThread>::make(this, outputStream, *output, mSystemReady);
3012 ALOGV("%s() created bit-perfect output: ID %d thread %p",
3013 __func__, *output, thread.get());
3014 } else if (flags & AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02003015 thread = new SpatializerThread(this, outputStream, *output,
Eric Laurentb3f315a2021-07-13 15:09:05 +02003016 mSystemReady, mixerConfig);
Eric Laurente28c66d2022-01-21 13:40:41 +01003017 ALOGV("openOutput_l() created spatializer output: ID %d thread %p",
Eric Laurentb3f315a2021-07-13 15:09:05 +02003018 *output, thread.get());
3019 } else if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Gareth Fennb18c1a32022-10-05 13:42:36 -07003020 thread = new OffloadThread(this, outputStream, *output,
3021 mSystemReady, halConfig->offload_info);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003022 ALOGV("openOutput_l() created offload output: ID %d thread %p",
3023 *output, thread.get());
3024 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
Eric Laurentf1f22e72021-07-13 14:04:14 +02003025 || !isValidPcmSinkFormat(halConfig->format)
3026 || !isValidPcmSinkChannelMask(halConfig->channel_mask)) {
Gareth Fennb18c1a32022-10-05 13:42:36 -07003027 thread = new DirectOutputThread(this, outputStream, *output,
3028 mSystemReady, halConfig->offload_info);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003029 ALOGV("openOutput_l() created direct output: ID %d thread %p",
3030 *output, thread.get());
3031 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07003032 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003033 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
3034 *output, thread.get());
3035 }
3036 mPlaybackThreads.add(*output, thread);
Eric Laurent74c38dc2020-12-23 18:19:44 +01003037 struct audio_patch patch;
3038 mPatchPanel.notifyStreamOpened(outHwDev, *output, &patch);
3039 if (thread->isMsdDevice()) {
3040 thread->setDownStreamPatch(&patch);
3041 }
Eric Laurent50d72582022-12-20 20:20:23 +01003042 thread->setBluetoothVariableLatencyEnabled(mBluetoothLatencyModesEnabled.load());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003043 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07003044 }
Eric Laurent83b88082014-06-20 18:31:16 -07003045 }
3046
Eric Laurente28c66d2022-01-21 13:40:41 +01003047 return nullptr;
Eric Laurent83b88082014-06-20 18:31:16 -07003048}
3049
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003050status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request,
3051 media::OpenOutputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052{
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003053 audio_module_handle_t module = VALUE_OR_RETURN_STATUS(
3054 aidl2legacy_int32_t_audio_module_handle_t(request.module));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003055 audio_config_t halConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003056 aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003057 audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003058 aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003059 sp<DeviceDescriptorBase> device = VALUE_OR_RETURN_STATUS(
3060 aidl2legacy_DeviceDescriptorBase(request.device));
3061 audio_output_flags_t flags = VALUE_OR_RETURN_STATUS(
Andy Hung973638a2020-12-08 20:47:45 -08003062 aidl2legacy_int32_t_audio_output_flags_t_mask(request.flags));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003063
3064 audio_io_handle_t output;
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003065
jiabin43810402019-10-24 14:58:31 -07003066 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003067 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08003068 this, module,
jiabin43810402019-10-24 14:58:31 -07003069 device->toString().c_str(),
Eric Laurentf1f22e72021-07-13 14:04:14 +02003070 halConfig.sample_rate,
3071 halConfig.format,
3072 halConfig.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07003073 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074
jiabin43810402019-10-24 14:58:31 -07003075 audio_devices_t deviceType = device->type();
3076 const String8 address = String8(device->address().c_str());
3077
3078 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003079 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080 }
Dima Zavin799a70e2011-04-18 16:57:27 -07003081
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 Mutex::Autolock _l(mLock);
3083
Eric Laurentf1f22e72021-07-13 14:04:14 +02003084 sp<ThreadBase> thread = openOutput_l(module, &output, &halConfig,
3085 &mixerConfig, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07003086 if (thread != 0) {
Andy Hung920f6572022-10-06 12:09:49 -07003087 uint32_t latencyMs = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003088 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
3089 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003090 latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091
Eric Laurent6acd1d42017-01-04 14:23:29 -08003092 // notify client processes of the new output creation
3093 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07003094
Eric Laurent00abf0d2020-04-22 19:28:22 -07003095 // the first primary output opened designates the primary hw device if no HW module
3096 // named "primary" was already loaded.
3097 AutoMutex lock(mHardwareLock);
3098 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08003099 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003100 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07003101
Eric Laurent6acd1d42017-01-04 14:23:29 -08003102 mHardwareStatus = AUDIO_HW_SET_MODE;
3103 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
3104 mHardwareStatus = AUDIO_HW_IDLE;
3105 }
3106 } else {
3107 MmapThread *mmapThread = (MmapThread *)thread.get();
3108 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07003109 }
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003110 response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003111 response->config = VALUE_OR_RETURN_STATUS(
3112 legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003113 response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(latencyMs));
Andy Hung973638a2020-12-08 20:47:45 -08003114 response->flags = VALUE_OR_RETURN_STATUS(
3115 legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
Eric Laurentcf2c0212014-07-25 16:20:43 -07003116 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 }
3118
Eric Laurentcf2c0212014-07-25 16:20:43 -07003119 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120}
3121
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003122audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
3123 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124{
3125 Mutex::Autolock _l(mLock);
3126 MixerThread *thread1 = checkMixerThread_l(output1);
3127 MixerThread *thread2 = checkMixerThread_l(output2);
3128
3129 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003130 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
3131 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07003132 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 }
3134
Glenn Kasteneeecb982016-02-26 10:44:04 -08003135 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07003136 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137 thread->addOutputTrack(thread2);
3138 mPlaybackThreads.add(id, thread);
3139 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07003140 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141 return id;
3142}
3143
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003144status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145{
Glenn Kastend96c5722012-04-25 13:44:49 -07003146 return closeOutput_nonvirtual(output);
3147}
3148
3149status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
3150{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 // keep strong reference on the playback thread so that
3152 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08003153 sp<PlaybackThread> playbackThread;
3154 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 {
3156 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003157 playbackThread = checkPlaybackThread_l(output);
3158 if (playbackThread != NULL) {
3159 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160
Andy Hungdc099c22018-09-18 13:46:39 -07003161 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07003162
Eric Laurent6acd1d42017-01-04 14:23:29 -08003163 if (playbackThread->type() == ThreadBase::MIXER) {
3164 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3165 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
3166 DuplicatingThread *dupThread =
3167 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
3168 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
3169 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170 }
3171 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003172
3173
Eric Laurent6acd1d42017-01-04 14:23:29 -08003174 mPlaybackThreads.removeItem(output);
3175 // save all effects to the default thread
3176 if (mPlaybackThreads.size()) {
3177 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
3178 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003179 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08003180 Mutex::Autolock _dl(dstThread->mLock);
3181 Mutex::Autolock _sl(playbackThread->mLock);
3182 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
3183 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003184 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07003185 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 }
3188 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003189 } else {
3190 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
3191 if (mmapThread == 0) {
3192 return BAD_VALUE;
3193 }
Andy Hungdc099c22018-09-18 13:46:39 -07003194 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003195 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08003196 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 }
Mikhail Naganov88536df2021-07-26 17:30:29 -07003198 ioConfigChanged(AUDIO_OUTPUT_CLOSED, sp<AudioIoDescriptor>::make(output));
Mikhail Naganovadca70f2018-07-09 12:49:25 -07003199 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08003201 // The thread entity (active unit of execution) is no longer running here,
3202 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203
Eric Laurent6acd1d42017-01-04 14:23:29 -08003204 if (playbackThread != 0) {
3205 playbackThread->exit();
3206 if (!playbackThread->isDuplicating()) {
3207 closeOutputFinish(playbackThread);
3208 }
3209 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08003210 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08003211 mmapThread->exit();
3212 AudioStreamOut *out = mmapThread->clearOutput();
3213 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3214 // from now on thread->mOutput is NULL
3215 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 }
3217 return NO_ERROR;
3218}
3219
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003220void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003221{
3222 AudioStreamOut *out = thread->clearOutput();
3223 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3224 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07003225 delete out;
3226}
3227
Mikhail Naganov444ecc32018-05-01 17:40:05 -07003228void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003229{
3230 mPlaybackThreads.removeItem(thread->mId);
3231 thread->exit();
3232 closeOutputFinish(thread);
3233}
3234
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003235status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236{
3237 Mutex::Autolock _l(mLock);
3238 PlaybackThread *thread = checkPlaybackThread_l(output);
3239
3240 if (thread == NULL) {
3241 return BAD_VALUE;
3242 }
3243
Steve Block3856b092011-10-20 11:56:00 +01003244 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 thread->suspend();
3246
3247 return NO_ERROR;
3248}
3249
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003250status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251{
3252 Mutex::Autolock _l(mLock);
3253 PlaybackThread *thread = checkPlaybackThread_l(output);
3254
3255 if (thread == NULL) {
3256 return BAD_VALUE;
3257 }
3258
Steve Block3856b092011-10-20 11:56:00 +01003259 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260
3261 thread->restore();
3262
3263 return NO_ERROR;
3264}
3265
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003266status_t AudioFlinger::openInput(const media::OpenInputRequest& request,
3267 media::OpenInputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268{
Eric Laurent83b88082014-06-20 18:31:16 -07003269 Mutex::Autolock _l(mLock);
3270
Mikhail Naganov21a32ec2021-07-08 14:40:12 -07003271 AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
3272 aidl2legacy_AudioDeviceTypeAddress(request.device));
3273 if (device.mType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003274 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07003275 }
3276
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003277 audio_io_handle_t input = VALUE_OR_RETURN_STATUS(
3278 aidl2legacy_int32_t_audio_io_handle_t(request.input));
3279 audio_config_t config = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003280 aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003281
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08003282 sp<ThreadBase> thread = openInput_l(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003283 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)),
3284 &input,
3285 &config,
3286 device.mType,
3287 device.address().c_str(),
Mikhail Naganovddceecc2021-09-03 13:58:56 -07003288 VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSource_audio_source_t(request.source)),
Andy Hung973638a2020-12-08 20:47:45 -08003289 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)),
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003290 AUDIO_DEVICE_NONE,
3291 String8{});
3292
3293 response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003294 response->config = VALUE_OR_RETURN_STATUS(
3295 legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003296 response->device = request.device;
Eric Laurent83b88082014-06-20 18:31:16 -07003297
3298 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07003299 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07003300 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003301 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003303 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07003304}
Dima Zavin799a70e2011-04-18 16:57:27 -07003305
Eric Laurent6acd1d42017-01-04 14:23:29 -08003306sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003307 audio_io_handle_t *input,
3308 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08003309 audio_devices_t devices,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003310 const char* address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003311 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08003312 audio_input_flags_t flags,
3313 audio_devices_t outputDevice,
3314 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07003315{
Glenn Kastene7d66712015-03-05 13:46:52 -08003316 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07003317 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003318 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07003319 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07003320 }
Dima Zavin799a70e2011-04-18 16:57:27 -07003321
Glenn Kasteneeecb982016-02-26 10:44:04 -08003322 // Audio Policy can request a specific handle for hardware hotword.
3323 // The goal here is not to re-open an already opened input.
3324 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07003325 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08003326 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
3327 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
3328 ALOGE("openInput_l() requested input handle %d is invalid", *input);
3329 return 0;
3330 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
3331 // This should not happen in a transient state with current design.
3332 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
3333 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003334 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07003335
Eric Laurentcf2c0212014-07-25 16:20:43 -07003336 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003337 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003338 sp<StreamInHalInterface> inStream;
3339 status_t status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003340 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08003341 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003342 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
3343 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003344 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08003345 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003346 halconfig.sample_rate,
3347 halconfig.format,
3348 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07003349 flags,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003350 status, address);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003352 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07003353 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07003354 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07003355 audio_is_linear_pcm(config->format) &&
3356 audio_is_linear_pcm(halconfig.format) &&
3357 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
Andy Hung936845a2021-06-08 00:09:06 -07003358 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_LIMIT) &&
3359 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_LIMIT)) {
Glenn Kasten85948432013-08-19 12:09:05 -07003360 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07003361 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003362 inStream.clear();
3363 status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003364 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08003365 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07003366 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 }
3368
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003369 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07003370 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003371 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
3372 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07003373 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003374 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08003375 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
3376 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003377 return thread;
3378 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003379 // Start record thread
3380 // RecordThread requires both input and output device indication to forward to audio
3381 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07003382 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003383 mRecordThreads.add(*input, thread);
3384 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
3385 return thread;
3386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 }
3388
Eric Laurentcf2c0212014-07-25 16:20:43 -07003389 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 return 0;
3391}
3392
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003393status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394{
Glenn Kastend96c5722012-04-25 13:44:49 -07003395 return closeInput_nonvirtual(input);
3396}
3397
3398status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
3399{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 // keep strong reference on the record thread so that
3401 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08003402 sp<RecordThread> recordThread;
3403 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 {
3405 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003406 recordThread = checkRecordThread_l(input);
3407 if (recordThread != 0) {
3408 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409
Andy Hungdc099c22018-09-18 13:46:39 -07003410 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07003411
Eric Laurent6acd1d42017-01-04 14:23:29 -08003412 // If we still have effect chains, it means that a client still holds a handle
3413 // on at least one effect. We must either move the chain to an existing thread with the
3414 // same session ID or put it aside in case a new record thread is opened for a
3415 // new capture on the same session
3416 sp<EffectChain> chain;
3417 {
3418 Mutex::Autolock _sl(recordThread->mLock);
3419 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
3420 // Note: maximum one chain per record thread
3421 if (effectChains.size() != 0) {
3422 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07003423 }
3424 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003425 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003426 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08003427 // This should only happen in case of overlap between one thread tear down and the
3428 // creation of its replacement
3429 size_t i;
3430 for (i = 0; i < mRecordThreads.size(); i++) {
3431 sp<RecordThread> t = mRecordThreads.valueAt(i);
3432 if (t == recordThread) {
3433 continue;
3434 }
3435 if (t->hasAudioSession(chain->sessionId()) != 0) {
Andy Hung920f6572022-10-06 12:09:49 -07003436 Mutex::Autolock _l2(t->mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003437 ALOGV("closeInput() found thread %d for effect session %d",
3438 t->id(), chain->sessionId());
3439 t->addEffectChain_l(chain);
3440 break;
3441 }
3442 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08003443 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08003444 if (i == mRecordThreads.size()) {
3445 putOrphanEffectChain_l(chain);
3446 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003447 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003448 mRecordThreads.removeItem(input);
3449 } else {
3450 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
3451 if (mmapThread == 0) {
3452 return BAD_VALUE;
3453 }
Andy Hungdc099c22018-09-18 13:46:39 -07003454 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003455 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07003456 }
Mikhail Naganov88536df2021-07-26 17:30:29 -07003457 ioConfigChanged(AUDIO_INPUT_CLOSED, sp<AudioIoDescriptor>::make(input));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458 }
Eric Laurent83b88082014-06-20 18:31:16 -07003459 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
3460 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08003461 if (recordThread != 0) {
3462 closeInputFinish(recordThread);
3463 } else if (mmapThread != 0) {
3464 mmapThread->exit();
3465 AudioStreamIn *in = mmapThread->clearInput();
3466 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3467 // from now on thread->mInput is NULL
3468 delete in;
3469 }
Eric Laurent83b88082014-06-20 18:31:16 -07003470 return NO_ERROR;
3471}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003473void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003474{
3475 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003476 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003477 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003478 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07003479 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07003480}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481
Mikhail Naganov444ecc32018-05-01 17:40:05 -07003482void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003483{
3484 mRecordThreads.removeItem(thread->mId);
3485 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486}
3487
jiabinc44b3462022-12-08 12:52:31 -08003488status_t AudioFlinger::invalidateTracks(const std::vector<audio_port_handle_t> &portIds) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003489 Mutex::Autolock _l(mLock);
jiabinc44b3462022-12-08 12:52:31 -08003490 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491
jiabinc44b3462022-12-08 12:52:31 -08003492 std::set<audio_port_handle_t> portIdSet(portIds.begin(), portIds.end());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3494 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
jiabinc44b3462022-12-08 12:52:31 -08003495 thread->invalidateTracks(portIdSet);
3496 if (portIdSet.empty()) {
3497 return NO_ERROR;
3498 }
Eric Laurentde070132010-07-13 04:45:46 -07003499 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003500 for (size_t i = 0; i < mMmapThreads.size(); i++) {
jiabinc44b3462022-12-08 12:52:31 -08003501 mMmapThreads[i]->invalidateTracks(portIdSet);
3502 if (portIdSet.empty()) {
3503 return NO_ERROR;
3504 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003505 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 return NO_ERROR;
3507}
3508
3509
Glenn Kasteneeecb982016-02-26 10:44:04 -08003510audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511{
Glenn Kasten9d003132016-04-06 14:38:09 -07003512 // This is a binder API, so a malicious client could pass in a bad parameter.
3513 // Check for that before calling the internal API nextUniqueId().
3514 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3515 ALOGE("newAudioUniqueId invalid use %d", use);
3516 return AUDIO_UNIQUE_ID_ALLOCATE;
3517 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003518 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519}
3520
Andy Hung8b0bfd92019-12-23 13:11:11 -08003521void AudioFlinger::acquireAudioSessionId(
3522 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003523{
3524 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08003525 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003526 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003527 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003528 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3529 caller = pid; // check must match releaseAudioSessionId()
3530 }
3531 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3532 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003533 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003534
Eric Laurent021cf962014-05-13 10:18:14 -07003535 {
3536 Mutex::Autolock _cl(mClientLock);
3537 // Ignore requests received from processes not known as notification client. The request
3538 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3539 // called from a different pid leaving a stale session reference. Also we don't know how
3540 // to clear this reference if the client process dies.
3541 if (mNotificationClients.indexOfKey(caller) < 0) {
3542 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3543 return;
3544 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003545 }
3546
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003547 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003548 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003549 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003550 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3551 ref->mCnt++;
3552 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003553 return;
3554 }
3555 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003556 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003557 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003558}
3559
Glenn Kastend848eb42016-03-08 13:42:11 -08003560void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003561{
Eric Laurent6c796322019-04-09 14:13:17 -07003562 std::vector< sp<EffectModule> > removedEffects;
3563 {
3564 Mutex::Autolock _l(mLock);
3565 pid_t caller = IPCThreadState::self()->getCallingPid();
3566 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3567 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003568 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3569 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003570 }
Eric Laurent6c796322019-04-09 14:13:17 -07003571 size_t num = mAudioSessionRefs.size();
3572 for (size_t i = 0; i < num; i++) {
3573 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3574 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3575 ref->mCnt--;
3576 ALOGV(" decremented refcount to %d", ref->mCnt);
3577 if (ref->mCnt == 0) {
3578 mAudioSessionRefs.removeAt(i);
3579 delete ref;
3580 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3581 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3582 }
3583 goto Exit;
3584 }
3585 }
3586 // If the caller is audioserver it is likely that the session being released was acquired
3587 // on behalf of a process not in notification clients and we ignore the warning.
3588 ALOGW_IF(!isAudioServerUid(callerUid),
3589 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003590 }
Eric Laurent6c796322019-04-09 14:13:17 -07003591
3592Exit:
3593 for (auto& effect : removedEffects) {
3594 effect->updatePolicyState();
3595 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003596}
3597
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003598bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3599{
3600 size_t num = mAudioSessionRefs.size();
3601 for (size_t i = 0; i < num; i++) {
3602 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3603 if (ref->mSessionid == audioSession) {
3604 return true;
3605 }
3606 }
3607 return false;
3608}
3609
Eric Laurent6c796322019-04-09 14:13:17 -07003610std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003611
Steve Block3856b092011-10-20 11:56:00 +01003612 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003613
3614 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003615 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003616
3617 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3618 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003619 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003620 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3621 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003622 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003623 chains.push(ec);
3624 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003625 }
3626 }
Eric Laurent6c796322019-04-09 14:13:17 -07003627
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003628 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3629 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003630 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003631 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3632 sp<EffectChain> ec = t->mEffectChains[j];
3633 chains.push(ec);
3634 }
3635 }
3636
Eric Laurent6c796322019-04-09 14:13:17 -07003637 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3638 sp<MmapThread> t = mMmapThreads.valueAt(i);
3639 Mutex::Autolock _l(t->mLock);
3640 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3641 sp<EffectChain> ec = t->mEffectChains[j];
3642 chains.push(ec);
3643 }
3644 }
3645
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003646 for (size_t i = 0; i < chains.size(); i++) {
Andy Hung920f6572022-10-06 12:09:49 -07003647 // clang-tidy suggests const ref
3648 sp<EffectChain> ec = chains[i]; // NOLINT(performance-unnecessary-copy-initialization)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003649 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003650 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003651 if (t == 0) {
3652 continue;
3653 }
3654 size_t numsessionrefs = mAudioSessionRefs.size();
3655 bool found = false;
3656 for (size_t k = 0; k < numsessionrefs; k++) {
3657 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003658 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003659 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003660 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003661 found = true;
3662 break;
3663 }
3664 }
3665 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003666 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003667 // remove all effects from the chain
3668 while (ec->mEffects.size()) {
3669 sp<EffectModule> effect = ec->mEffects[0];
3670 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003671 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003672 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003673 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003674 }
Eric Laurent6c796322019-04-09 14:13:17 -07003675 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003676 }
3677 }
3678 }
Eric Laurent6c796322019-04-09 14:13:17 -07003679 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003680}
3681
Andy Hungdc099c22018-09-18 13:46:39 -07003682// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3683void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3684{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303685 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
3686 audio_utils::FdToString fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
Andy Hungdc099c22018-09-18 13:46:39 -07003687 const int fd = fdToString.fd();
3688 if (fd >= 0) {
3689 thread->dump(fd, {} /* args */);
3690 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3691 }
3692}
3693
Glenn Kasteneeecb982016-02-26 10:44:04 -08003694// checkThread_l() must be called with AudioFlinger::mLock held
3695AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3696{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003697 ThreadBase *thread = checkMmapThread_l(ioHandle);
3698 if (thread == 0) {
3699 switch (audio_unique_id_get_use(ioHandle)) {
3700 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3701 thread = checkPlaybackThread_l(ioHandle);
3702 break;
3703 case AUDIO_UNIQUE_ID_USE_INPUT:
3704 thread = checkRecordThread_l(ioHandle);
3705 break;
3706 default:
3707 break;
3708 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003709 }
3710 return thread;
3711}
3712
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003713// checkOutputThread_l() must be called with AudioFlinger::mLock held
3714sp<AudioFlinger::ThreadBase> AudioFlinger::checkOutputThread_l(audio_io_handle_t ioHandle) const
3715{
3716 if (audio_unique_id_get_use(ioHandle) != AUDIO_UNIQUE_ID_USE_OUTPUT) {
3717 return nullptr;
3718 }
3719
3720 sp<AudioFlinger::ThreadBase> thread = mPlaybackThreads.valueFor(ioHandle);
3721 if (thread == nullptr) {
3722 thread = mMmapThreads.valueFor(ioHandle);
3723 }
3724 return thread;
3725}
3726
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003728AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729{
Glenn Kastena1117922012-01-26 10:53:32 -08003730 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003731}
3732
3733// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003734AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735{
3736 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003737 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738}
3739
3740// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003741AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742{
Glenn Kastena1117922012-01-26 10:53:32 -08003743 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744}
3745
Eric Laurent6acd1d42017-01-04 14:23:29 -08003746// checkMmapThread_l() must be called with AudioFlinger::mLock held
3747AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3748{
3749 return mMmapThreads.valueFor(io).get();
3750}
3751
3752
3753// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3754AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3755{
Eric Laurent7459b902017-04-19 18:10:41 -07003756 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003757 if (volumeInterface == nullptr) {
3758 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3759 if (mmapThread != nullptr) {
3760 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003761 MmapPlaybackThread *mmapPlaybackThread =
3762 static_cast<MmapPlaybackThread *>(mmapThread);
3763 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003764 }
3765 }
3766 }
3767 return volumeInterface;
3768}
3769
3770Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3771{
3772 Vector <VolumeInterface *> volumeInterfaces;
3773 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003774 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003775 }
3776 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3777 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003778 MmapPlaybackThread *mmapPlaybackThread =
3779 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3780 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003781 }
3782 }
3783 return volumeInterfaces;
3784}
3785
Glenn Kasteneeecb982016-02-26 10:44:04 -08003786audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003787{
Glenn Kasten9d003132016-04-06 14:38:09 -07003788 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003789 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003790 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3791 for (int retry = 0; retry < maxRetries; retry++) {
3792 // The cast allows wraparound from max positive to min negative instead of abort
3793 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3794 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3795 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3796 // allow wrap by skipping 0 and -1 for session ids
3797 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3798 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3799 return (audio_unique_id_t) (base | use);
3800 }
3801 }
3802 // We have no way of recovering from wraparound
3803 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3804 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805}
3806
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003807AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003808{
Eric Laurent00abf0d2020-04-22 19:28:22 -07003809 AutoMutex lock(mHardwareLock);
3810 if (mPrimaryHardwareDev == nullptr) {
3811 return nullptr;
3812 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003813 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3814 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003815 if(thread->isDuplicating()) {
3816 continue;
3817 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003818 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003819 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003820 return thread;
3821 }
3822 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07003823 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003824}
3825
jiabinc52b1ff2019-10-31 17:20:42 -07003826DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003827{
3828 PlaybackThread *thread = primaryPlaybackThread_l();
3829
3830 if (thread == NULL) {
Andy Hung920f6572022-10-06 12:09:49 -07003831 return {};
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003832 }
3833
jiabinc52b1ff2019-10-31 17:20:42 -07003834 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003835}
3836
Glenn Kastena7335632016-06-09 17:09:53 -07003837AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3838{
3839 size_t minFrameCount = 0;
3840 PlaybackThread *minThread = NULL;
3841 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3842 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3843 if (!thread->isDuplicating()) {
3844 size_t frameCount = thread->frameCountHAL();
3845 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3846 (frameCount == minFrameCount && thread->hasFastMixer() &&
3847 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3848 minFrameCount = frameCount;
3849 minThread = thread;
3850 }
3851 }
3852 }
3853 return minThread;
3854}
3855
jiabineb3bda02020-06-30 14:07:03 -07003856AudioFlinger::ThreadBase *AudioFlinger::hapticPlaybackThread_l() const {
3857 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
3858 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3859 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
3860 return thread;
3861 }
3862 }
3863 return nullptr;
3864}
3865
jiabinf042b9b2021-05-07 23:46:28 +00003866void AudioFlinger::updateSecondaryOutputsForTrack_l(
3867 PlaybackThread::Track* track,
3868 PlaybackThread* thread,
3869 const std::vector<audio_io_handle_t> &secondaryOutputs) const {
3870 TeePatches teePatches;
3871 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
3872 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
3873 if (secondaryThread == nullptr) {
3874 ALOGE("no playback thread found for secondary output %d", thread->id());
3875 continue;
3876 }
3877
3878 size_t sourceFrameCount = thread->frameCount() * track->sampleRate()
3879 / thread->sampleRate();
3880 size_t sinkFrameCount = secondaryThread->frameCount() * track->sampleRate()
3881 / secondaryThread->sampleRate();
3882 // If the secondary output has just been opened, the first secondaryThread write
3883 // will not block as it will fill the empty startup buffer of the HAL,
3884 // so a second sink buffer needs to be ready for the immediate next blocking write.
3885 // Additionally, have a margin of one main thread buffer as the scheduling jitter
3886 // can reorder the writes (eg if thread A&B have the same write intervale,
3887 // the scheduler could schedule AB...BA)
3888 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
3889 // Total secondary output buffer must be at least as the read frames plus
3890 // the margin of a few buffers on both sides in case the
3891 // threads scheduling has some jitter.
3892 // That value should not impact latency as the secondary track is started before
3893 // its buffer is full, see frameCountToBeReady.
3894 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
3895 // The frameCount should also not be smaller than the secondary thread min frame
3896 // count
3897 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
3898 [&] { Mutex::Autolock _l(secondaryThread->mLock);
3899 return secondaryThread->latency_l(); }(),
3900 secondaryThread->mNormalFrameCount,
3901 secondaryThread->mSampleRate,
3902 track->sampleRate(),
3903 track->getSpeed());
3904 frameCount = std::max(frameCount, minFrameCount);
3905
3906 using namespace std::chrono_literals;
3907 auto inChannelMask = audio_channel_mask_out_to_in(track->channelMask());
jiabin73e303c2022-09-15 17:49:50 +00003908 if (inChannelMask == AUDIO_CHANNEL_INVALID) {
3909 // The downstream PatchTrack has the proper output channel mask,
3910 // so if there is no input channel mask equivalent, we can just
3911 // use an index mask here to create the PatchRecord.
3912 inChannelMask = audio_channel_mask_out_to_in_index_mask(track->channelMask());
3913 }
jiabinf042b9b2021-05-07 23:46:28 +00003914 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
3915 track->sampleRate(),
3916 inChannelMask,
3917 track->format(),
3918 frameCount,
3919 nullptr /* buffer */,
3920 (size_t)0 /* bufferSize */,
3921 AUDIO_INPUT_FLAG_DIRECT,
3922 0ns /* timeout */);
3923 status_t status = patchRecord->initCheck();
3924 if (status != NO_ERROR) {
3925 ALOGE("Secondary output patchRecord init failed: %d", status);
3926 continue;
3927 }
3928
3929 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
3930 // for fast usage: thread has fast mixer, sample rate matches, etc.;
3931 // for now, we exclude fast tracks by removing the Fast flag.
3932 const audio_output_flags_t outputFlags =
3933 (audio_output_flags_t)(track->getOutputFlags() & ~AUDIO_OUTPUT_FLAG_FAST);
3934 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
3935 track->streamType(),
3936 track->sampleRate(),
3937 track->channelMask(),
3938 track->format(),
3939 frameCount,
3940 patchRecord->buffer(),
3941 patchRecord->bufferSize(),
3942 outputFlags,
3943 0ns /* timeout */,
3944 frameCountToBeReady);
3945 status = patchTrack->initCheck();
3946 if (status != NO_ERROR) {
3947 ALOGE("Secondary output patchTrack init failed: %d", status);
3948 continue;
3949 }
3950 teePatches.push_back({patchRecord, patchTrack});
3951 secondaryThread->addPatchTrack(patchTrack);
3952 // In case the downstream patchTrack on the secondaryThread temporarily outlives
3953 // our created track, ensure the corresponding patchRecord is still alive.
3954 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
3955 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
3956 }
Jiabin Huangfb476842022-12-06 03:18:10 +00003957 track->setTeePatchesToUpdate(std::move(teePatches));
jiabinf042b9b2021-05-07 23:46:28 +00003958}
3959
Eric Laurenta011e352012-03-29 15:51:43 -07003960sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003961 audio_session_t triggerSession,
3962 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003963 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003964 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003965{
3966 Mutex::Autolock _l(mLock);
3967
3968 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3969 status_t playStatus = NAME_NOT_FOUND;
3970 status_t recStatus = NAME_NOT_FOUND;
3971 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3972 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3973 if (playStatus == NO_ERROR) {
3974 return event;
3975 }
3976 }
3977 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3978 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3979 if (recStatus == NO_ERROR) {
3980 return event;
3981 }
3982 }
3983 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3984 mPendingSyncEvents.add(event);
3985 } else {
3986 ALOGV("createSyncEvent() invalid event %d", event->type());
3987 event.clear();
3988 }
3989 return event;
3990}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003991
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992// ----------------------------------------------------------------------------
3993// Effect management
3994// ----------------------------------------------------------------------------
3995
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003996sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3997 return mEffectsFactoryHal;
3998}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999
Glenn Kastenf587ba52012-01-26 16:25:10 -08004000status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001{
4002 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004003 if (mEffectsFactoryHal.get()) {
4004 return mEffectsFactoryHal->queryNumberEffects(numEffects);
4005 } else {
4006 return -ENODEV;
4007 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008}
4009
Glenn Kastenf587ba52012-01-26 16:25:10 -08004010status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011{
4012 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004013 if (mEffectsFactoryHal.get()) {
4014 return mEffectsFactoryHal->getDescriptor(index, descriptor);
4015 } else {
4016 return -ENODEV;
4017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018}
4019
Glenn Kasten5e92a782012-01-30 07:40:52 -08004020status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004021 const effect_uuid_t *pTypeUuid,
4022 uint32_t preferredTypeFlag,
4023 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004025 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
4026 return BAD_VALUE;
4027 }
4028
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004030
4031 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004032 return -ENODEV;
4033 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004035 status_t status = NO_ERROR;
4036 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
4037 // If uuid is specified, request effect descriptor from that.
4038 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
4039 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
4040 // If uuid is not specified, look for an available implementation
4041 // of the required type instead.
4042
4043 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
4044 effect_descriptor_t desc;
4045 desc.flags = 0; // prevent compiler warning
4046
4047 uint32_t numEffects = 0;
4048 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
4049 if (status < 0) {
4050 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
4051 return status;
4052 }
4053
4054 bool found = false;
4055 for (uint32_t i = 0; i < numEffects; i++) {
4056 status = mEffectsFactoryHal->getDescriptor(i, &desc);
4057 if (status < 0) {
4058 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
4059 continue;
4060 }
4061 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
4062 // If matching type found save effect descriptor.
4063 found = true;
4064 *descriptor = desc;
4065
4066 // If there's no preferred flag or this descriptor matches the preferred
4067 // flag, success! If this descriptor doesn't match the preferred
4068 // flag, continue enumeration in case a better matching version of this
4069 // effect type is available. Note that this means if no effect with a
4070 // correct flag is found, the descriptor returned will correspond to the
4071 // last effect that at least had a matching type uuid (if any).
4072 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
4073 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
4074 break;
4075 }
4076 }
4077 }
4078
4079 if (!found) {
4080 status = NAME_NOT_FOUND;
4081 ALOGW("getEffectDescriptor(): Effect not found by type.");
4082 }
4083 } else {
4084 status = BAD_VALUE;
4085 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
4086 }
4087 return status;
4088}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004090status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request,
4091 media::CreateEffectResponse* response) {
4092 const sp<IEffectClient>& effectClient = request.client;
4093 const int32_t priority = request.priority;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004094 const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004095 aidl2legacy_AudioDeviceTypeAddress(request.device));
Svet Ganov33761132021-05-13 22:51:08 +00004096 AttributionSourceState adjAttributionSource = request.attributionSource;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004097 const audio_session_t sessionId = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004098 aidl2legacy_int32_t_audio_session_t(request.sessionId));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004099 audio_io_handle_t io = VALUE_OR_RETURN_STATUS(
4100 aidl2legacy_int32_t_audio_io_handle_t(request.output));
4101 const effect_descriptor_t descIn = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004102 aidl2legacy_EffectDescriptor_effect_descriptor_t(request.desc));
4103 const bool probe = request.probe;
4104
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105 sp<EffectHandle> handle;
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004106 effect_descriptor_t descOut;
4107 int enabledOut = 0;
4108 int idOut = -1;
4109
4110 status_t lStatus = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004112 // TODO b/182392553: refactor or make clearer
Eric Laurentb6436272016-12-07 19:24:50 -08004113 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Svet Ganov33761132021-05-13 22:51:08 +00004114 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
4115 pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid));
Eric Laurent9ff3e532022-11-10 16:04:44 +01004116 if (currentPid == -1 || !isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08004117 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004118 ALOGW_IF(currentPid != -1 && currentPid != callingPid,
Eric Laurentb6436272016-12-07 19:24:50 -08004119 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004120 __func__, callingUid, callingPid, currentPid);
Svet Ganov33761132021-05-13 22:51:08 +00004121 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004122 currentPid = callingPid;
Eric Laurentb6436272016-12-07 19:24:50 -08004123 }
Eric Laurent9ff3e532022-11-10 16:04:44 +01004124 adjAttributionSource = AudioFlinger::checkAttributionSourcePackage(adjAttributionSource);
Eric Laurentb6436272016-12-07 19:24:50 -08004125
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004126 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
Svet Ganov33761132021-05-13 22:51:08 +00004127 adjAttributionSource.pid, effectClient.get(), priority, sessionId, io,
4128 mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004130 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07004131 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004132 lStatus = NO_INIT;
4133 goto Exit;
4134 }
4135
Andy Hung6096dcd2019-03-13 13:20:30 -07004136 // check audio settings permission for global effects
4137 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4138 if (!settingsAllowed()) {
4139 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
4140 lStatus = PERMISSION_DENIED;
4141 goto Exit;
4142 }
4143 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung6096dcd2019-03-13 13:20:30 -07004144 if (io == AUDIO_IO_HANDLE_NONE) {
4145 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
4146 lStatus = BAD_VALUE;
4147 goto Exit;
4148 }
Eric Laurenta74058e2022-05-26 15:08:00 +00004149 PlaybackThread *thread = checkPlaybackThread_l(io);
4150 if (thread == nullptr) {
4151 ALOGE("%s: invalid output %d specified for AUDIO_SESSION_OUTPUT_STAGE", __func__, io);
4152 lStatus = BAD_VALUE;
4153 goto Exit;
4154 }
4155 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)
4156 && !isAudioServerUid(callingUid)) {
4157 ALOGE("%s: effect on AUDIO_SESSION_OUTPUT_STAGE not granted for uid %d",
4158 __func__, callingUid);
4159 lStatus = PERMISSION_DENIED;
4160 goto Exit;
4161 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004162 } else if (sessionId == AUDIO_SESSION_DEVICE) {
Svet Ganov33761132021-05-13 22:51:08 +00004163 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)) {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004164 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
4165 lStatus = PERMISSION_DENIED;
4166 goto Exit;
4167 }
Eric Laurent94876032019-11-13 12:45:28 -08004168 if (io != AUDIO_IO_HANDLE_NONE) {
4169 ALOGE("%s: io handle should not be specified for device effect", __func__);
4170 lStatus = BAD_VALUE;
4171 goto Exit;
4172 }
Andy Hung6096dcd2019-03-13 13:20:30 -07004173 } else {
4174 // general sessionId.
4175
4176 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
4177 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
4178 lStatus = BAD_VALUE;
4179 goto Exit;
4180 }
4181
4182 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
4183 // to prevent creating an effect when one doesn't actually have track with that session?
4184 }
4185
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004187 // Get the full effect descriptor from the uuid/type.
4188 // If the session is the output mix, prefer an auxiliary effect,
4189 // otherwise no preference.
4190 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
4191 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004192 lStatus = getEffectDescriptor(&descIn.uuid, &descIn.type, preferredType, &descOut);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004193 if (lStatus < 0) {
4194 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
4195 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 }
4197
4198 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004199 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004200 (descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201 lStatus = INVALID_OPERATION;
4202 goto Exit;
4203 }
4204
Eric Laurent59255e42011-07-27 19:49:51 -07004205 // check recording permission for visualizer
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004206 if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08004207 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Svet Ganov33761132021-05-13 22:51:08 +00004208 !recordingAllowed(adjAttributionSource)) {
Eric Laurent59255e42011-07-27 19:49:51 -07004209 lStatus = PERMISSION_DENIED;
4210 goto Exit;
4211 }
4212
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004213 const bool hapticPlaybackRequired = EffectModule::isHapticGenerator(&descOut.type);
jiabineb3bda02020-06-30 14:07:03 -07004214 if (hapticPlaybackRequired
4215 && (sessionId == AUDIO_SESSION_DEVICE
4216 || sessionId == AUDIO_SESSION_OUTPUT_MIX
4217 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
4218 // haptic-generating effect is only valid when the session id is a general session id
4219 lStatus = INVALID_OPERATION;
4220 goto Exit;
4221 }
4222
Eric Laurentf690c462021-09-17 14:47:03 +02004223 // Only audio policy service can create a spatializer effect
4224 if ((memcmp(&descOut.type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0) &&
4225 (callingUid != AID_AUDIOSERVER || currentPid != getpid())) {
4226 ALOGW("%s: attempt to create a spatializer effect from uid/pid %d/%d",
4227 __func__, callingUid, currentPid);
4228 lStatus = PERMISSION_DENIED;
4229 goto Exit;
4230 }
4231
Glenn Kasten142f5192014-03-25 17:44:59 -07004232 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07004233 // if the output returned by getOutputForEffect() is removed before we lock the
4234 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
4235 // and we will exit safely
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004236 io = AudioSystem::getOutputForEffect(&descOut);
Eric Laurenteb3c3372013-09-25 12:25:29 -07004237 ALOGV("createEffect got output %d", io);
4238 }
4239
4240 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
Eric Laurentb82e6b72019-11-22 17:25:04 -08004242 if (sessionId == AUDIO_SESSION_DEVICE) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004243 sp<Client> client = registerPid(currentPid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07004244 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Vlad Popa5161f8a2022-10-10 16:17:20 +02004245 handle = mDeviceEffectManager->createEffect_l(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004246 &descOut, device, client, effectClient, mPatchPanel.patches_l(),
Eric Laurentde8caf42021-08-11 17:19:25 +02004247 &enabledOut, &lStatus, probe, request.notifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08004248 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4249 // remove local strong reference to Client with mClientLock held
4250 Mutex::Autolock _cl(mClientLock);
4251 client.clear();
4252 } else {
4253 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004254 if (handle.get() != nullptr) idOut = handle->id();
Eric Laurentb82e6b72019-11-22 17:25:04 -08004255 }
4256 goto Register;
4257 }
4258
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 // If output is not specified try to find a matching audio session ID in one of the
4260 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004261 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4262 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07004263 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
4264 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07004265 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07004266 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07004267 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
4268 if (io == AUDIO_IO_HANDLE_NONE) {
4269 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08004271 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07004272 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08004273 }
Andy Hung444bb552019-03-14 17:06:39 -07004274
4275 // If you wish to create a Record preprocessing AudioEffect in Java,
4276 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
4277 // Otherwise it will fail when created on a Playback thread by legacy
4278 // handling below. Ditto with Mmap, the associated Mmap track must be created
4279 // before creating the AudioEffect or the io handle must be specified.
4280 //
4281 // Detect if the effect is created after an AudioRecord is destroyed.
4282 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
4283 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004284 " for session %d no longer exists",
4285 __func__, descOut.name, sessionId);
Andy Hung444bb552019-03-14 17:06:39 -07004286 lStatus = PERMISSION_DENIED;
4287 goto Exit;
4288 }
4289
4290 // Legacy handling of creating an effect on an expired or made-up
4291 // session id. We think that it is a Playback effect.
4292 //
Eric Laurent84e9a102010-09-23 16:10:16 -07004293 // If no output thread contains the requested session ID, default to
4294 // first output. The effect chain will be moved to the correct output
4295 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07004296 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004297 io = mPlaybackThreads.keyAt(0);
4298 }
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004299 ALOGV("createEffect() got io %d for effect %s", io, descOut.name);
Eric Laurentb3f315a2021-07-13 15:09:05 +02004300 } else if (checkPlaybackThread_l(io) != nullptr
4301 && sessionId != AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung1631f062019-03-12 19:39:03 -07004302 // allow only one effect chain per sessionId on mPlaybackThreads.
4303 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4304 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07004305 if (io == checkIo) {
4306 if (hapticPlaybackRequired
4307 && mPlaybackThreads.valueAt(i)
4308 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
4309 ALOGE("%s: haptic playback thread is required while the required playback "
4310 "thread(io=%d) doesn't support", __func__, (int)io);
4311 lStatus = BAD_VALUE;
4312 goto Exit;
4313 }
4314 continue;
4315 }
Andy Hung1631f062019-03-12 19:39:03 -07004316 const uint32_t sessionType =
4317 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
4318 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
4319 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004320 __func__, descOut.name, (int) io, (int) sessionId, (int) checkIo);
Andy Hung1631f062019-03-12 19:39:03 -07004321 android_errorWriteLog(0x534e4554, "123237974");
4322 lStatus = BAD_VALUE;
4323 goto Exit;
4324 }
4325 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004326 }
4327 ThreadBase *thread = checkRecordThread_l(io);
4328 if (thread == NULL) {
4329 thread = checkPlaybackThread_l(io);
4330 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08004331 thread = checkMmapThread_l(io);
4332 if (thread == NULL) {
4333 ALOGE("createEffect() unknown output thread");
4334 lStatus = BAD_VALUE;
4335 goto Exit;
4336 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004337 }
Eric Laurentaaa44472014-09-12 17:41:50 -07004338 } else {
4339 // Check if one effect chain was awaiting for an effect to be created on this
4340 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08004341 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07004342 if (chain != 0) {
Andy Hung920f6572022-10-06 12:09:49 -07004343 Mutex::Autolock _l2(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07004344 thread->addEffectChain_l(chain);
4345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004347
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004348 sp<Client> client = registerPid(currentPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004350 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004351 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
jiabineb3bda02020-06-30 14:07:03 -07004352 ThreadBase *oriThread = nullptr;
4353 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
4354 ThreadBase *hapticThread = hapticPlaybackThread_l();
4355 if (hapticThread == nullptr) {
4356 ALOGE("%s haptic thread not found while it is required", __func__);
4357 lStatus = INVALID_OPERATION;
4358 goto Exit;
4359 }
4360 if (hapticThread != thread) {
4361 // Force to use haptic thread for haptic-generating effect.
4362 oriThread = thread;
4363 thread = hapticThread;
4364 }
4365 }
Eric Laurentde070132010-07-13 04:45:46 -07004366 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurentde8caf42021-08-11 17:19:25 +02004367 &descOut, &enabledOut, &lStatus, pinned, probe,
4368 request.notifyFramesProcessed);
haobo101735295ff7b0d2017-03-17 17:44:03 +08004369 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07004370 // remove local strong reference to Client with mClientLock held
4371 Mutex::Autolock _cl(mClientLock);
4372 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08004373 } else {
4374 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004375 if (handle.get() != nullptr) idOut = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07004376 // Invalidate audio session when haptic playback is created.
4377 if (hapticPlaybackRequired && oriThread != nullptr) {
4378 // invalidateTracksForAudioSession will trigger locking the thread.
4379 oriThread->invalidateTracksForAudioSession(sessionId);
4380 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07004381 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 }
4383
Eric Laurentb82e6b72019-11-22 17:25:04 -08004384Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07004385 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent4f1d4e92022-02-01 14:37:16 +01004386 if (lStatus == ALREADY_EXISTS) {
4387 response->alreadyExists = true;
4388 lStatus = NO_ERROR;
4389 } else {
4390 response->alreadyExists = false;
4391 }
Eric Laurent6c796322019-04-09 14:13:17 -07004392 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08004393 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004394 if (effect != nullptr) {
4395 status_t rStatus = effect->updatePolicyState();
4396 if (rStatus != NO_ERROR) {
4397 lStatus = rStatus;
4398 }
4399 }
4400 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08004401 handle.clear();
4402 }
4403
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004404 response->id = idOut;
4405 response->enabled = enabledOut != 0;
4406 response->effect = handle;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004407 response->desc = VALUE_OR_RETURN_STATUS(
4408 legacy2aidl_effect_descriptor_t_EffectDescriptor(descOut));
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004409
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410Exit:
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004411 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412}
4413
Glenn Kastend848eb42016-03-08 13:42:11 -08004414status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004415 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07004416{
Steve Block3856b092011-10-20 11:56:00 +01004417 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07004418 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004419 Mutex::Autolock _l(mLock);
4420 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004421 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004422 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
Eric Laurentde070132010-07-13 04:45:46 -07004424 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4425 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004426 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004427 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 }
Eric Laurentde070132010-07-13 04:45:46 -07004429 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4430 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004431 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07004432 return BAD_VALUE;
4433 }
4434
4435 Mutex::Autolock _dl(dstThread->mLock);
4436 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07004437 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438}
4439
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004440
4441void AudioFlinger::setEffectSuspended(int effectId,
4442 audio_session_t sessionId,
4443 bool suspended)
4444{
4445 Mutex::Autolock _l(mLock);
4446
4447 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
4448 if (thread == nullptr) {
4449 return;
4450 }
4451 Mutex::Autolock _sl(thread->mLock);
4452 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
4453 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
4454}
4455
4456
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004457// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08004458status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07004459 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07004460 AudioFlinger::PlaybackThread *dstThread)
Andy Hung920f6572022-10-06 12:09:49 -07004461NO_THREAD_SAFETY_ANALYSIS // requires srcThread and dstThread locks
Eric Laurentde070132010-07-13 04:45:46 -07004462{
Steve Block3856b092011-10-20 11:56:00 +01004463 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07004464 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07004465
Eric Laurent59255e42011-07-27 19:49:51 -07004466 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07004467 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004468 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07004469 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07004470 return INVALID_OPERATION;
4471 }
4472
Eric Laurent4c415062016-06-17 16:14:16 -07004473 // Check whether the destination thread and all effects in the chain are compatible
4474 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07004475 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07004476 " destination thread %p is not compatible with effects in the chain",
4477 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07004478 return INVALID_OPERATION;
4479 }
4480
Eric Laurent39e94f82010-07-28 01:32:47 -07004481 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004482 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07004483 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07004484 // removed.
Andy Hung180f49a2022-01-27 10:25:02 -08004485 // TODO(b/216875016): consider holding the effect chain locks for the duration of the move.
Eric Laurentde070132010-07-13 04:45:46 -07004486 srcThread->removeEffectChain_l(chain);
4487
4488 // transfer all effects one by one so that new effect chain is created on new thread with
4489 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07004490 sp<EffectChain> dstChain;
Eric Laurent5baf2af2013-09-12 17:37:00 -07004491 Vector< sp<EffectModule> > removed;
4492 status_t status = NO_ERROR;
Andy Hung03410c02022-01-27 08:24:31 -08004493 std::string errorString;
Andy Hung920f6572022-10-06 12:09:49 -07004494 // process effects one by one.
4495 for (sp<EffectModule> effect = chain->getEffectFromId_l(0); effect != nullptr;
4496 effect = chain->getEffectFromId_l(0)) {
Eric Laurentde070132010-07-13 04:45:46 -07004497 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004498 removed.add(effect);
4499 status = dstThread->addEffect_l(effect);
4500 if (status != NO_ERROR) {
Andy Hung03410c02022-01-27 08:24:31 -08004501 errorString = StringPrintf(
4502 "cannot add effect %p to destination thread", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004503 break;
4504 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004505 // if the move request is not received from audio policy manager, the effect must be
Andy Hung180f49a2022-01-27 10:25:02 -08004506 // re-registered with the new strategy and output.
4507
4508 // We obtain the dstChain once the effect is on the new thread.
4509 if (dstChain == nullptr) {
Andy Hungfda44002021-06-03 17:23:16 -07004510 dstChain = effect->getCallback()->chain().promote();
Andy Hung180f49a2022-01-27 10:25:02 -08004511 if (dstChain == nullptr) {
Andy Hung03410c02022-01-27 08:24:31 -08004512 errorString = StringPrintf("cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004513 status = NO_INIT;
4514 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004515 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004516 }
Eric Laurentde070132010-07-13 04:45:46 -07004517 }
4518
Andy Hung03410c02022-01-27 08:24:31 -08004519 size_t restored = 0;
Eric Laurent5baf2af2013-09-12 17:37:00 -07004520 if (status != NO_ERROR) {
Andy Hung180f49a2022-01-27 10:25:02 -08004521 dstChain.clear(); // dstChain is now from the srcThread (could be recreated).
Andy Hung03410c02022-01-27 08:24:31 -08004522 for (const auto& effect : removed) {
Andy Hung5c4dd0d2022-01-27 10:21:59 -08004523 dstThread->removeEffect_l(effect); // Note: Depending on error location, the last
4524 // effect may not have been placed on dstThread.
Andy Hung03410c02022-01-27 08:24:31 -08004525 if (srcThread->addEffect_l(effect) == NO_ERROR) {
4526 ++restored;
Andy Hung180f49a2022-01-27 10:25:02 -08004527 if (dstChain == nullptr) {
4528 dstChain = effect->getCallback()->chain().promote();
4529 }
Andy Hung03410c02022-01-27 08:24:31 -08004530 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004531 }
4532 }
4533
Andy Hung180f49a2022-01-27 10:25:02 -08004534 // After all the effects have been moved to new thread (or put back) we restart the effects
4535 // because removeEffect_l() has stopped the effect if it is currently active.
4536 size_t started = 0;
4537 if (dstChain != nullptr && !removed.empty()) {
4538 // If we do not take the dstChain lock, it is possible that processing is ongoing
4539 // while we are starting the effect. This can cause glitches with volume,
4540 // see b/202360137.
4541 dstChain->lock();
4542 for (const auto& effect : removed) {
4543 if (effect->state() == EffectModule::ACTIVE ||
4544 effect->state() == EffectModule::STOPPING) {
4545 ++started;
4546 effect->start();
4547 }
4548 }
4549 dstChain->unlock();
4550 }
4551
Andy Hung03410c02022-01-27 08:24:31 -08004552 if (status != NO_ERROR) {
4553 if (errorString.empty()) {
4554 errorString = StringPrintf("%s: failed status %d", __func__, status);
4555 }
4556 ALOGW("%s: %s unsuccessful move of session %d from srcThread %p to dstThread %p "
Andy Hung180f49a2022-01-27 10:25:02 -08004557 "(%zu effects removed from srcThread, %zu effects restored to srcThread, "
4558 "%zu effects started)",
Andy Hung03410c02022-01-27 08:24:31 -08004559 __func__, errorString.c_str(), sessionId, srcThread, dstThread,
Andy Hung180f49a2022-01-27 10:25:02 -08004560 removed.size(), restored, started);
Andy Hung03410c02022-01-27 08:24:31 -08004561 } else {
4562 ALOGD("%s: successful move of session %d from srcThread %p to dstThread %p "
Andy Hung180f49a2022-01-27 10:25:02 -08004563 "(%zu effects moved, %zu effects started)",
4564 __func__, sessionId, srcThread, dstThread, removed.size(), started);
Andy Hung03410c02022-01-27 08:24:31 -08004565 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004566 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567}
4568
Eric Laurent6c796322019-04-09 14:13:17 -07004569status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
4570 const sp<PlaybackThread>& dstThread,
4571 sp<PlaybackThread> *srcThread)
4572{
4573 status_t status = NO_ERROR;
4574 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004575 sp<PlaybackThread> thread =
4576 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07004577
4578 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
4579 Mutex::Autolock _dl(dstThread->mLock);
4580 Mutex::Autolock _sl(thread->mLock);
4581 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4582 sp<EffectChain> dstChain;
4583 if (srcChain == 0) {
4584 return INVALID_OPERATION;
4585 }
4586
4587 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
4588 if (effect == 0) {
4589 return INVALID_OPERATION;
4590 }
4591 thread->removeEffect_l(effect);
4592 status = dstThread->addEffect_l(effect);
4593 if (status != NO_ERROR) {
4594 thread->addEffect_l(effect);
4595 status = INVALID_OPERATION;
4596 goto Exit;
4597 }
4598
Andy Hungfda44002021-06-03 17:23:16 -07004599 dstChain = effect->getCallback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004600 if (dstChain == 0) {
4601 thread->addEffect_l(effect);
4602 status = INVALID_OPERATION;
4603 }
4604
4605Exit:
4606 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4607 if (effect->state() == EffectModule::ACTIVE ||
4608 effect->state() == EffectModule::STOPPING) {
4609 effect->start();
4610 }
4611 }
4612
4613 if (status == NO_ERROR && srcThread != nullptr) {
4614 *srcThread = thread;
4615 }
4616 return status;
4617}
4618
Eric Laurent5baf2af2013-09-12 17:37:00 -07004619bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Andy Hung920f6572022-10-06 12:09:49 -07004620NO_THREAD_SAFETY_ANALYSIS // thread lock for getEffectChain_l.
Eric Laurent813e2a72013-08-31 12:59:48 -07004621{
4622 if (mGlobalEffectEnableTime != 0 &&
4623 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
4624 return true;
4625 }
4626
4627 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4628 sp<EffectChain> ec =
4629 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004630 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07004631 return true;
4632 }
4633 }
4634 return false;
4635}
4636
Eric Laurent5baf2af2013-09-12 17:37:00 -07004637void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07004638{
4639 Mutex::Autolock _l(mLock);
4640
4641 mGlobalEffectEnableTime = systemTime();
4642
4643 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4644 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
4645 if (t->mType == ThreadBase::OFFLOAD) {
4646 t->invalidateTracks(AUDIO_STREAM_MUSIC);
4647 }
4648 }
4649
4650}
4651
Eric Laurentaaa44472014-09-12 17:41:50 -07004652status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
4653{
Eric Laurentd8365c52017-07-16 15:27:05 -07004654 // clear possible suspended state before parking the chain so that it starts in default state
4655 // when attached to a new record thread
4656 chain->setEffectSuspended_l(FX_IID_AEC, false);
4657 chain->setEffectSuspended_l(FX_IID_NS, false);
4658
Glenn Kastend848eb42016-03-08 13:42:11 -08004659 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004660 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004661 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004662 if (index >= 0) {
4663 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
4664 return ALREADY_EXISTS;
4665 }
4666 mOrphanEffectChains.add(session, chain);
4667 return NO_ERROR;
4668}
4669
4670sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
4671{
4672 sp<EffectChain> chain;
4673 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004674 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004675 if (index >= 0) {
4676 chain = mOrphanEffectChains.valueAt(index);
4677 mOrphanEffectChains.removeItemsAt(index);
4678 }
4679 return chain;
4680}
4681
4682bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
4683{
4684 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08004685 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004686 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004687 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004688 if (index >= 0) {
4689 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08004690 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004691 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004692 mOrphanEffectChains.removeItemsAt(index);
4693 }
4694 return true;
4695 }
4696 return false;
4697}
4698
4699
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700// ----------------------------------------------------------------------------
4701
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004702status_t AudioFlinger::onTransactWrapper(TransactionCode code,
Jing Mike537412f2023-03-12 11:01:47 +08004703 [[maybe_unused]] const Parcel& data,
4704 [[maybe_unused]] uint32_t flags,
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004705 const std::function<status_t()>& delegate) {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004706 // make sure transactions reserved to AudioPolicyManager do not come from other processes
4707 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004708 case TransactionCode::SET_STREAM_VOLUME:
4709 case TransactionCode::SET_STREAM_MUTE:
4710 case TransactionCode::OPEN_OUTPUT:
4711 case TransactionCode::OPEN_DUPLICATE_OUTPUT:
4712 case TransactionCode::CLOSE_OUTPUT:
4713 case TransactionCode::SUSPEND_OUTPUT:
4714 case TransactionCode::RESTORE_OUTPUT:
4715 case TransactionCode::OPEN_INPUT:
4716 case TransactionCode::CLOSE_INPUT:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004717 case TransactionCode::SET_VOICE_VOLUME:
4718 case TransactionCode::MOVE_EFFECTS:
4719 case TransactionCode::SET_EFFECT_SUSPENDED:
4720 case TransactionCode::LOAD_HW_MODULE:
4721 case TransactionCode::GET_AUDIO_PORT:
4722 case TransactionCode::CREATE_AUDIO_PATCH:
4723 case TransactionCode::RELEASE_AUDIO_PATCH:
4724 case TransactionCode::LIST_AUDIO_PATCHES:
4725 case TransactionCode::SET_AUDIO_PORT_CONFIG:
4726 case TransactionCode::SET_RECORD_SILENCED:
Eric Laurentd66d7a12021-07-13 13:35:32 +02004727 case TransactionCode::AUDIO_POLICY_READY:
Mikhail Naganov516d3982022-02-01 23:53:59 +00004728 case TransactionCode::SET_DEVICE_CONNECTED_STATE:
Eric Laurent076e7c72022-05-03 18:12:28 +02004729 case TransactionCode::SET_REQUESTED_LATENCY_MODE:
4730 case TransactionCode::GET_SUPPORTED_LATENCY_MODES:
jiabinc44b3462022-12-08 12:52:31 -08004731 case TransactionCode::INVALIDATE_TRACKS:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004732 ALOGW("%s: transaction %d received from PID %d",
4733 __func__, code, IPCThreadState::self()->getCallingPid());
4734 // return status only for non void methods
4735 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004736 case TransactionCode::SET_RECORD_SILENCED:
4737 case TransactionCode::SET_EFFECT_SUSPENDED:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004738 break;
4739 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004740 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004741 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004742 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004743 return OK;
4744 default:
4745 break;
4746 }
4747
4748 // make sure the following transactions come from system components
4749 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004750 case TransactionCode::SET_MASTER_VOLUME:
4751 case TransactionCode::SET_MASTER_MUTE:
Jean-Michel Trivie4f113b2020-11-16 11:50:33 -08004752 case TransactionCode::MASTER_MUTE:
Vlad Popae3fd1c22022-11-07 21:03:18 +01004753 case TransactionCode::GET_SOUND_DOSE_INTERFACE:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004754 case TransactionCode::SET_MODE:
4755 case TransactionCode::SET_MIC_MUTE:
4756 case TransactionCode::SET_LOW_RAM_DEVICE:
4757 case TransactionCode::SYSTEM_READY:
jiabin1319f5a2021-03-30 22:21:24 +00004758 case TransactionCode::SET_AUDIO_HAL_PIDS:
jiabinf042b9b2021-05-07 23:46:28 +00004759 case TransactionCode::SET_VIBRATOR_INFOS:
Eric Laurent52057642022-12-16 11:45:07 +01004760 case TransactionCode::UPDATE_SECONDARY_OUTPUTS:
Eric Laurent50d72582022-12-20 20:20:23 +01004761 case TransactionCode::SET_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
4762 case TransactionCode::IS_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
4763 case TransactionCode::SUPPORTS_BLUETOOTH_VARIABLE_LATENCY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004764 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
4765 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
4766 __func__, code, IPCThreadState::self()->getCallingPid(),
4767 IPCThreadState::self()->getCallingUid());
Vlad Popa63f047e2022-11-05 14:09:19 +01004768 // return status only for non-void methods
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004769 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004770 case TransactionCode::SYSTEM_READY:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004771 break;
4772 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004773 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004774 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004775 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004776 return OK;
4777 }
4778 } break;
4779 default:
4780 break;
4781 }
4782
4783 // List of relevant events that trigger log merging.
4784 // Log merging should activate during audio activity of any kind. This are considered the
4785 // most relevant events.
4786 // TODO should select more wisely the items from the list
4787 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004788 case TransactionCode::CREATE_TRACK:
4789 case TransactionCode::CREATE_RECORD:
4790 case TransactionCode::SET_MASTER_VOLUME:
4791 case TransactionCode::SET_MASTER_MUTE:
4792 case TransactionCode::SET_MIC_MUTE:
4793 case TransactionCode::SET_PARAMETERS:
4794 case TransactionCode::CREATE_EFFECT:
4795 case TransactionCode::SYSTEM_READY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004796 requestLogMerge();
4797 break;
4798 }
4799 default:
4800 break;
4801 }
4802
Andy Hungc747c532022-03-07 21:41:14 -08004803 const std::string methodName = getIAudioFlingerStatistics().getMethodForCode(code);
4804 mediautils::TimeCheck check(
4805 std::string("IAudioFlinger::").append(methodName),
4806 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
4807 if (timeout) {
4808 mediametrics::LogItem(mMetricsId)
4809 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
4810 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
4811 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
4812 .record();
4813 } else {
4814 getIAudioFlingerStatistics().event(code, elapsedMs);
4815 }
Andy Hungf8ab0932022-06-13 19:49:43 -07004816 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
4817 mediautils::TimeCheck::kDefaultSecondChanceDuration,
4818 true /* crashOnTimeout */);
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004819
4820 // Make sure we connect to Audio Policy Service before calling into AudioFlinger:
4821 // - AudioFlinger can call into Audio Policy Service with its global mutex held
4822 // - If this is the first time Audio Policy Service is queried from inside audioserver process
4823 // this will trigger Audio Policy Manager initialization.
4824 // - Audio Policy Manager initialization calls into AudioFlinger which will try to lock
4825 // its global mutex and a deadlock will occur.
4826 if (IPCThreadState::self()->getCallingPid() != getpid()) {
4827 AudioSystem::get_audio_policy_service();
4828 }
4829
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004830 return delegate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831}
4832
Glenn Kasten63238ef2015-03-02 15:50:29 -08004833} // namespace android