blob: 40332479ec1e8ddb6d8aa0a1ad963638f9044489 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/time.h>
28#include <sys/resource.h>
29
jiabin57303cc2018-12-18 15:45:57 -080030#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070036#include <media/audiohal/DeviceHalInterface.h>
37#include <media/audiohal/DevicesFactoryHalInterface.h>
38#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070039#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070041#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <utils/String16.h>
43#include <utils/threads.h>
44
Steven Morelandf0c02ce2018-02-23 14:53:55 -080045#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/properties.h>
47
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070051#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Andy Hung6770c6f2015-04-07 13:43:36 -070053#include <media/AudioResamplerPublic.h>
54
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_visualizer.h>
56#include <system/audio_effects/effect_ns.h>
57#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070068#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080074#include "TypedLogger.h"
75
Mathias Agopian65ab4712010-07-14 17:59:35 -070076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
John Grossman1c345192012-03-27 14:00:17 -070078// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
Eric Laurentde070132010-07-13 04:45:46 -070090
Mathias Agopian65ab4712010-07-14 17:59:35 -070091namespace android {
92
Glenn Kastenec1d6b52011-12-12 09:04:45 -080093static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
94static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070095static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070096static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten58912562012-04-03 10:45:00 -070098
John Grossman4ff14ba2012-02-08 16:37:41 -080099nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700102
Eric Laurent813e2a72013-08-31 12:59:48 -0700103// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
104// we define a minimum time during which a global effect is considered enabled.
105static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
106
Eric Laurentfc235202016-12-20 18:48:17 -0800107Mutex gLock;
108wp<AudioFlinger> gAudioFlinger;
109
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700110// Keep a strong reference to media.log service around forever.
111// The service is within our parent process so it can never die in a way that we could observe.
112// These two variables are const after initialization.
113static sp<IBinder> sMediaLogServiceAsBinder;
114static sp<IMediaLogService> sMediaLogService;
115
116static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
117
118static void sMediaLogInit()
119{
120 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
121 if (sMediaLogServiceAsBinder != 0) {
122 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
123 }
124}
125
jiabin57303cc2018-12-18 15:45:57 -0800126// Keep a strong reference to external vibrator service
127static sp<os::IExternalVibratorService> sExternalVibratorService;
128
129static sp<os::IExternalVibratorService> getExternalVibratorService() {
130 if (sExternalVibratorService == 0) {
131 sp <IBinder> binder = defaultServiceManager()->getService(
132 String16("external_vibrator_service"));
133 if (binder != 0) {
134 sExternalVibratorService =
135 interface_cast<os::IExternalVibratorService>(binder);
136 }
137 }
138 return sExternalVibratorService;
139}
140
Mathias Agopian65ab4712010-07-14 17:59:35 -0700141// ----------------------------------------------------------------------------
142
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700143std::string formatToString(audio_format_t format) {
144 std::string result;
145 FormatConverter::toString(format, result);
146 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800147}
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800153 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800155 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700156 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700159 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800160 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700161 mBtNrecIsOff(false),
162 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700163 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800164 mTotalMemory(0),
165 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700166 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700167 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700168 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700170 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
171 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
172 // zero ID has a special meaning, so unavailable
173 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
174 }
175
Glenn Kastenae0cff12016-02-24 13:57:49 -0800176 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800177 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800178 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
179 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700180 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800181 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700182
Wei Jia3f273d12015-11-24 09:06:49 -0800183 // reset battery stats.
184 // if the audio service has crashed, battery stats could be left
185 // in bad state, reset the state upon service start.
186 BatteryNotifier::getInstance().noteResetAudio();
187
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700188 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700189 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
190
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800191 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192}
193
194void AudioFlinger::onFirstRef()
195{
Eric Laurent93575202011-01-18 18:39:02 -0800196 Mutex::Autolock _l(mLock);
197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800199 char val_str[PROPERTY_VALUE_MAX] = { 0 };
200 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
201 uint32_t int_val;
202 if (1 == sscanf(val_str, "%u", &int_val)) {
203 mStandbyTimeInNsecs = milliseconds(int_val);
204 ALOGI("Using %u mSec as standby time.", int_val);
205 } else {
206 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
207 ALOGI("Using default %u mSec as standby time.",
208 (uint32_t)(mStandbyTimeInNsecs / 1000000));
209 }
210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211
Eric Laurenta4c5a552012-03-29 10:12:40 -0700212 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800213
214 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215}
216
217AudioFlinger::~AudioFlinger()
218{
219 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700220 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700221 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700222 }
223 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700224 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700225 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700227
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800228 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
229 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700230 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700232
233 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700234 if (sMediaLogService != 0) {
235 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
236 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
237 mUnregisteredWriters.pop();
238 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700239 }
240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241}
242
Eric Laurentfc235202016-12-20 18:48:17 -0800243//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800244__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800245status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
246 const audio_attributes_t *attr,
247 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700248 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800249 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800250 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800251 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700252 sp<MmapStreamInterface>& interface,
253 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800254{
255 sp<AudioFlinger> af;
256 {
257 Mutex::Autolock _l(gLock);
258 af = gAudioFlinger.promote();
259 }
260 status_t ret = NO_INIT;
261 if (af != 0) {
262 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800263 direction, attr, config, client, deviceId,
264 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800265 }
266 return ret;
267}
268
Eric Laurent6acd1d42017-01-04 14:23:29 -0800269status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
270 const audio_attributes_t *attr,
271 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700272 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800273 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800274 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800275 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700276 sp<MmapStreamInterface>& interface,
277 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800278{
279 status_t ret = initCheck();
280 if (ret != NO_ERROR) {
281 return ret;
282 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800283 audio_session_t actualSessionId = *sessionId;
284 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
285 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
286 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800287 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700288 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800289 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
290 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
291 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
292 fullConfig.sample_rate = config->sample_rate;
293 fullConfig.channel_mask = config->channel_mask;
294 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800295 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800296 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800297 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200298 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800299 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800300 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
301 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800302 deviceId, &portId, &secondaryOutputs);
303 ALOGW_IF(!secondaryOutputs.empty(),
304 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800305 } else {
306 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800307 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800308 client.clientPid,
309 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800310 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800311 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700312 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800313 }
314 if (ret != NO_ERROR) {
315 return ret;
316 }
317
318 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
319 // audio policy manager and we can retrieve it
320 sp<MmapThread> thread = mMmapThreads.valueFor(io);
321 if (thread != 0) {
322 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800323 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700324 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800325 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800326 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700327 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700328 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700329 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800330 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700331 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800332 ret = NO_INIT;
333 }
334
335 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
336
Eric Laurentfc235202016-12-20 18:48:17 -0800337 return ret;
338}
339
jiabin57303cc2018-12-18 15:45:57 -0800340/* static */
341int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
342 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
343 if (evs != 0) {
344 int32_t ret;
345 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
346 if (status.isOk()) {
347 return ret;
348 }
349 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800350 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800351}
352
353/* static */
354void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
355 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
356 if (evs != 0) {
357 evs->onExternalVibrationStop(*externalVibration);
358 }
359}
360
Eric Laurenta4c5a552012-03-29 10:12:40 -0700361static const char * const audio_interfaces[] = {
362 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
363 AUDIO_HARDWARE_MODULE_ID_A2DP,
364 AUDIO_HARDWARE_MODULE_ID_USB,
365};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700366
Phil Burk062e67a2015-02-11 13:40:50 -0800367AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700368 audio_module_handle_t module,
369 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700370{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700371 // if module is 0, the request comes from an old policy manager and we should load
372 // well known modules
373 if (module == 0) {
374 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700375 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700376 loadHwModule_l(audio_interfaces[i]);
377 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700378 // then try to find a module supporting the requested device.
379 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
380 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700381 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
382 uint32_t supportedDevices;
383 if (dev->getSupportedDevices(&supportedDevices) == OK &&
384 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700385 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700386 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700387 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700388 } else {
389 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700390 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
391 if (audioHwDevice != NULL) {
392 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700393 }
394 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700395
Dima Zavin799a70e2011-04-18 16:57:27 -0700396 return NULL;
397}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700398
Glenn Kasten0f11b512014-01-31 16:18:54 -0800399void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400{
401 const size_t SIZE = 256;
402 char buffer[SIZE];
403 String8 result;
404
405 result.append("Clients:\n");
406 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800407 sp<Client> client = mClients.valueAt(i).promote();
408 if (client != 0) {
409 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
410 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 }
412 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700413
Eric Laurentd1b28d42013-09-18 18:47:13 -0700414 result.append("Notification Clients:\n");
415 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
416 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
417 result.append(buffer);
418 }
419
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700420 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800421 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700422 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
423 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800424 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700425 result.append(buffer);
426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428}
429
430
Glenn Kasten0f11b512014-01-31 16:18:54 -0800431void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432{
433 const size_t SIZE = 256;
434 char buffer[SIZE];
435 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800436 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437
John Grossman4ff14ba2012-02-08 16:37:41 -0800438 snprintf(buffer, SIZE, "Hardware status: %d\n"
439 "Standby Time mSec: %u\n",
440 hardwareStatus,
441 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 result.append(buffer);
443 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444}
445
Glenn Kasten0f11b512014-01-31 16:18:54 -0800446void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447{
448 const size_t SIZE = 256;
449 char buffer[SIZE];
450 String8 result;
451 snprintf(buffer, SIZE, "Permission Denial: "
452 "can't dump AudioFlinger from pid=%d, uid=%d\n",
453 IPCThreadState::self()->getCallingPid(),
454 IPCThreadState::self()->getCallingUid());
455 result.append(buffer);
456 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457}
458
Eric Laurent81784c32012-11-19 14:55:58 -0800459bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460{
461 bool locked = false;
462 for (int i = 0; i < kDumpLockRetries; ++i) {
463 if (mutex.tryLock() == NO_ERROR) {
464 locked = true;
465 break;
466 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800467 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468 }
469 return locked;
470}
471
472status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
473{
Glenn Kasten44deb052012-02-05 18:09:08 -0800474 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475 dumpPermissionDenial(fd, args);
476 } else {
477 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800478 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479 if (!hardwareLocked) {
480 String8 result(kHardwareLockedString);
481 write(fd, result.string(), result.size());
482 } else {
483 mHardwareLock.unlock();
484 }
485
Eric Tan7b651152018-07-13 10:17:19 -0700486 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487
488 // failed to lock - AudioFlinger is probably deadlocked
489 if (!locked) {
490 String8 result(kDeadlockedString);
491 write(fd, result.string(), result.size());
492 }
493
Eric Laurent021cf962014-05-13 10:18:14 -0700494 bool clientLocked = dumpTryLock(mClientLock);
495 if (!clientLocked) {
496 String8 result(kClientLockedString);
497 write(fd, result.string(), result.size());
498 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700499
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700500 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700501 mEffectsFactoryHal->dumpEffects(fd);
502 } else {
503 String8 result(kNoEffectsFactory);
504 write(fd, result.string(), result.size());
505 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700506
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700508 if (clientLocked) {
509 mClientLock.unlock();
510 }
511
Mathias Agopian65ab4712010-07-14 17:59:35 -0700512 dumpInternals(fd, args);
513
514 // dump playback threads
515 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
516 mPlaybackThreads.valueAt(i)->dump(fd, args);
517 }
518
519 // dump record threads
520 for (size_t i = 0; i < mRecordThreads.size(); i++) {
521 mRecordThreads.valueAt(i)->dump(fd, args);
522 }
523
Eric Laurent6acd1d42017-01-04 14:23:29 -0800524 // dump mmap threads
525 for (size_t i = 0; i < mMmapThreads.size(); i++) {
526 mMmapThreads.valueAt(i)->dump(fd, args);
527 }
528
Eric Laurentaaa44472014-09-12 17:41:50 -0700529 // dump orphan effect chains
530 if (mOrphanEffectChains.size() != 0) {
531 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
532 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
533 mOrphanEffectChains.valueAt(i)->dump(fd, args);
534 }
535 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700536 // dump all hardware devs
537 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700538 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
539 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700541
Mikhail Naganov201369b2018-05-16 16:52:32 -0700542 mPatchPanel.dump(fd);
543
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700544 // dump external setParameters
545 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
546 dprintf(fd, "\n%s setParameters:\n", name);
547 logger.dump(fd, " " /* prefix */);
548 };
549 dumpLogger(mRejectedSetParameterLog, "Rejected");
550 dumpLogger(mAppSetParameterLog, "App");
551 dumpLogger(mSystemSetParameterLog, "System");
552
Andy Hunga8115dc2018-08-24 15:51:59 -0700553 // dump historical threads in the last 10 seconds
554 const std::string threadLog = mThreadLog.dumpToString(
555 "Historical Thread Log ", 0 /* lines */,
556 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
557 write(fd, threadLog.c_str(), threadLog.size());
558
rago3bd1c872016-09-26 12:58:14 -0700559 BUFLOG_RESET;
560
Glenn Kastend65d73c2012-06-22 17:21:07 -0700561 if (locked) {
562 mLock.unlock();
563 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800564
Andy Hung8946a282018-04-19 20:04:56 -0700565#ifdef TEE_SINK
566 // NBAIO_Tee dump is safe to call outside of AF lock.
567 NBAIO_Tee::dumpAll(fd, "_DUMP");
568#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800569 // append a copy of media.log here by forwarding fd to it, but don't attempt
570 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700571 if (sMediaLogServiceAsBinder != 0) {
572 dprintf(fd, "\nmedia.log:\n");
573 Vector<String16> args;
574 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800575 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700576
577 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700578 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700579 bool unreachableMemory = false;
580 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700581 if (arg == String16("-m")) {
582 dumpMem = true;
583 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700584 unreachableMemory = true;
585 }
586 }
587
Andy Hung07b745e2016-05-23 16:21:07 -0700588 if (dumpMem) {
589 dprintf(fd, "\nDumping memory:\n");
590 std::string s = dumpMemoryAddresses(100 /* limit */);
591 write(fd, s.c_str(), s.size());
592 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700593 if (unreachableMemory) {
594 dprintf(fd, "\nDumping unreachable memory:\n");
595 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700596 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700597 write(fd, s.c_str(), s.size());
598 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 }
600 return NO_ERROR;
601}
602
Eric Laurent021cf962014-05-13 10:18:14 -0700603sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800604{
Eric Laurent021cf962014-05-13 10:18:14 -0700605 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800606 // If pid is already in the mClients wp<> map, then use that entry
607 // (for which promote() is always != 0), otherwise create a new entry and Client.
608 sp<Client> client = mClients.valueFor(pid).promote();
609 if (client == 0) {
610 client = new Client(this, pid);
611 mClients.add(pid, client);
612 }
613
614 return client;
615}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616
Glenn Kasten9e58b552013-01-18 15:09:48 -0800617sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
618{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700619 // If there is no memory allocated for logs, return a dummy writer that does nothing.
620 // Similarly if we can't contact the media.log service, also return a dummy writer.
621 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800622 return new NBLog::Writer();
623 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700624 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
625 // If allocation fails, consult the vector of previously unregistered writers
626 // and garbage-collect one or more them until an allocation succeeds
627 if (shared == 0) {
628 Mutex::Autolock _l(mUnregisteredWritersLock);
629 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
630 {
631 // Pick the oldest stale writer to garbage-collect
632 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
633 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700634 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700635 // Now the media.log remote reference to IMemory is gone. When our last local
636 // reference to IMemory also drops to zero at end of this block,
637 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
638 }
639 // Re-attempt the allocation
640 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
641 if (shared != 0) {
642 goto success;
643 }
644 }
645 // Even after garbage-collecting all old writers, there is still not enough memory,
646 // so return a dummy writer
647 return new NBLog::Writer();
648 }
649success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800650 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
651 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
652 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700653 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800654 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800655}
656
657void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
658{
Glenn Kasten685ef092013-02-04 08:15:34 -0800659 if (writer == 0) {
660 return;
661 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800662 sp<IMemory> iMemory(writer->getIMemory());
663 if (iMemory == 0) {
664 return;
665 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700666 // Rather than removing the writer immediately, append it to a queue of old writers to
667 // be garbage-collected later. This allows us to continue to view old logs for a while.
668 Mutex::Autolock _l(mUnregisteredWritersLock);
669 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800670}
671
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672// IAudioFlinger interface
673
Eric Laurent21da6472017-11-09 16:29:26 -0800674sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
675 CreateTrackOutput& output,
676 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677{
678 sp<PlaybackThread::Track> track;
679 sp<TrackHandle> trackHandle;
680 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800682 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800683 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800684 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685
Eric Laurent21da6472017-11-09 16:29:26 -0800686 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700687 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800688 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700689 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800690 ALOGW_IF(clientUid != callingUid,
691 "%s uid %d tried to pass itself off as %d",
692 __FUNCTION__, callingUid, clientUid);
693 clientUid = callingUid;
694 updatePid = true;
695 }
696 pid_t clientPid = input.clientInfo.clientPid;
697 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700698 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800699 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700700 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800701 __func__, callingUid, callingPid, clientPid);
702 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700703 }
704
Eric Laurent21da6472017-11-09 16:29:26 -0800705 audio_session_t sessionId = input.sessionId;
706 if (sessionId == AUDIO_SESSION_ALLOCATE) {
707 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800708 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
709 lStatus = BAD_VALUE;
710 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800711 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800712
Eric Laurent21da6472017-11-09 16:29:26 -0800713 output.sessionId = sessionId;
714 output.outputId = AUDIO_IO_HANDLE_NONE;
715 output.selectedDeviceId = input.selectedDeviceId;
716
717 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200718 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800719 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800720
721 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
722 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
723 goto Exit;
724 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800725 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
726 // but if someone uses binder directly they could bypass that and cause us to crash
727 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000728 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 lStatus = BAD_VALUE;
730 goto Exit;
731 }
732
Glenn Kasten53b5d092014-02-05 10:00:23 -0800733 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800734 if (!audio_is_output_channel(input.config.channel_mask)) {
735 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800736 lStatus = BAD_VALUE;
737 goto Exit;
738 }
739
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700740 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800741 if (!audio_is_valid_format(input.config.format)) {
742 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700743 lStatus = BAD_VALUE;
744 goto Exit;
745 }
746
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 {
748 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800749 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800751 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 lStatus = BAD_VALUE;
753 goto Exit;
754 }
755
Eric Laurent21da6472017-11-09 16:29:26 -0800756 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757
Glenn Kastene848bd92014-03-13 15:00:32 -0700758 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800759 // check if an effect chain with the same session ID is present on another
760 // output thread and move it here.
761 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
762 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
763 if (mPlaybackThreads.keyAt(i) != output.outputId) {
764 uint32_t sessions = t->hasAudioSession(sessionId);
765 if (sessions & ThreadBase::EFFECT_SESSION) {
766 effectThread = t.get();
767 break;
Eric Laurentde070132010-07-13 04:45:46 -0700768 }
769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 }
Eric Laurent21da6472017-11-09 16:29:26 -0800771 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772
Eric Laurent21da6472017-11-09 16:29:26 -0800773 output.sampleRate = input.config.sample_rate;
774 output.frameCount = input.frameCount;
775 output.notificationFrameCount = input.notificationFrameCount;
776 output.flags = input.flags;
777
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700778 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
779 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800780 &output.frameCount, &output.notificationFrameCount,
781 input.notificationsPerBuffer, input.speed,
782 input.sharedBuffer, sessionId, &output.flags,
783 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800784 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700785 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700786
Eric Laurent21da6472017-11-09 16:29:26 -0800787 output.afFrameCount = thread->frameCount();
788 output.afSampleRate = thread->sampleRate();
789 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800790 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800791
Kevin Rocard153f92d2018-12-18 18:33:28 -0800792 if (lStatus == NO_ERROR) {
793 // Connect secondary outputs. Failure on a secondary output must not imped the primary
794 // Any secondary output setup failure will lead to a desync between the AP and AF until
795 // the track is destroyed.
796 TeePatches teePatches;
797 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
798 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
799 if (secondaryThread == NULL) {
800 ALOGE("no playback thread found for secondary output %d", output.outputId);
801 continue;
802 }
803
804 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
805
806 using namespace std::chrono_literals;
807 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
808 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
809 output.sampleRate,
810 inChannelMask,
811 input.config.format,
812 frameCount,
813 NULL /* buffer */,
814 (size_t)0 /* bufferSize */,
815 AUDIO_INPUT_FLAG_DIRECT,
816 0ns /* timeout */);
817 status_t status = patchRecord->initCheck();
818 if (status != NO_ERROR) {
819 ALOGE("Secondary output patchRecord init failed: %d", status);
820 continue;
821 }
822 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
823 streamType,
824 output.sampleRate,
825 input.config.channel_mask,
826 input.config.format,
827 frameCount,
828 patchRecord->buffer(),
829 patchRecord->bufferSize(),
830 output.flags,
831 0ns /* timeout */);
832 status = patchTrack->initCheck();
833 if (status != NO_ERROR) {
834 ALOGE("Secondary output patchTrack init failed: %d", status);
835 continue;
836 }
837 teePatches.push_back({patchRecord, patchTrack});
838 secondaryThread->addPatchTrack(patchTrack);
839 patchTrack->setPeerProxy(patchRecord.get());
840 patchRecord->setPeerProxy(patchTrack.get());
Kevin Rocard153f92d2018-12-18 18:33:28 -0800841 }
842 track->setTeePatches(std::move(teePatches));
843 }
844
Eric Laurent39e94f82010-07-28 01:32:47 -0700845 // move effect chain to this output thread if an effect on same session was waiting
846 // for a track to be created
847 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700848 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700849 Mutex::Autolock _dl(thread->mLock);
850 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800851 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700852 }
Eric Laurenta011e352012-03-29 15:51:43 -0700853
854 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700855 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800856 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700857 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700858 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700859 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700860 } else {
861 mPendingSyncEvents[i]->cancel();
862 }
Eric Laurenta011e352012-03-29 15:51:43 -0700863 mPendingSyncEvents.removeAt(i);
864 i--;
865 }
866 }
867 }
Glenn Kastene198c362013-08-13 09:13:36 -0700868
Eric Laurent21da6472017-11-09 16:29:26 -0800869 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 }
Glenn Kastene198c362013-08-13 09:13:36 -0700871
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700872 if (lStatus != NO_ERROR) {
873 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700874 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700875 // Don't hold mClientLock when releasing the reference on the track as the
876 // destructor will acquire it.
877 {
878 Mutex::Autolock _cl(mClientLock);
879 client.clear();
880 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700882 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 }
884
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700885 // return handle to client
886 trackHandle = new TrackHandle(track);
887
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800889 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700890 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800891 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700892 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 return trackHandle;
894}
895
Glenn Kasten2c073da2016-02-26 09:14:08 -0800896uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897{
898 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800899 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800901 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902 return 0;
903 }
904 return thread->sampleRate();
905}
906
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800907audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908{
909 Mutex::Autolock _l(mLock);
910 PlaybackThread *thread = checkPlaybackThread_l(output);
911 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000912 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800913 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914 }
915 return thread->format();
916}
917
Glenn Kasten2c073da2016-02-26 09:14:08 -0800918size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919{
920 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800921 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800923 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924 return 0;
925 }
Glenn Kasten58912562012-04-03 10:45:00 -0700926 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
927 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 return thread->frameCount();
929}
930
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700931size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
932{
933 Mutex::Autolock _l(mLock);
934 ThreadBase *thread = checkThread_l(ioHandle);
935 if (thread == NULL) {
936 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
937 return 0;
938 }
939 return thread->frameCountHAL();
940}
941
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800942uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943{
944 Mutex::Autolock _l(mLock);
945 PlaybackThread *thread = checkPlaybackThread_l(output);
946 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800947 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 return 0;
949 }
950 return thread->latency();
951}
952
953status_t AudioFlinger::setMasterVolume(float value)
954{
Eric Laurenta1884f92011-08-23 08:25:03 -0700955 status_t ret = initCheck();
956 if (ret != NO_ERROR) {
957 return ret;
958 }
959
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960 // check calling permissions
961 if (!settingsAllowed()) {
962 return PERMISSION_DENIED;
963 }
964
Eric Laurenta4c5a552012-03-29 10:12:40 -0700965 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700966 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700967
John Grossmanee578c02012-07-23 17:05:46 -0700968 // Set master volume in the HALs which support it.
969 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
970 AutoMutex lock(mHardwareLock);
971 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800972
John Grossmanee578c02012-07-23 17:05:46 -0700973 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
974 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700975 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800976 }
John Grossmanee578c02012-07-23 17:05:46 -0700977 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979
John Grossmanee578c02012-07-23 17:05:46 -0700980 // Now set the master volume in each playback thread. Playback threads
981 // assigned to HALs which do not have master volume support will apply
982 // master volume during the mix operation. Threads with HALs which do
983 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700984 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
985 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
986 continue;
987 }
John Grossmanee578c02012-07-23 17:05:46 -0700988 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990
991 return NO_ERROR;
992}
993
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100994status_t AudioFlinger::setMasterBalance(float balance)
995{
996 status_t ret = initCheck();
997 if (ret != NO_ERROR) {
998 return ret;
999 }
1000
1001 // check calling permissions
1002 if (!settingsAllowed()) {
1003 return PERMISSION_DENIED;
1004 }
1005
1006 // check range
1007 if (isnan(balance) || fabs(balance) > 1.f) {
1008 return BAD_VALUE;
1009 }
1010
1011 Mutex::Autolock _l(mLock);
1012
1013 // short cut.
1014 if (mMasterBalance == balance) return NO_ERROR;
1015
1016 mMasterBalance = balance;
1017
1018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1019 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1020 continue;
1021 }
1022 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1023 }
1024
1025 return NO_ERROR;
1026}
1027
Glenn Kastenf78aee72012-01-04 11:00:47 -08001028status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029{
Eric Laurenta1884f92011-08-23 08:25:03 -07001030 status_t ret = initCheck();
1031 if (ret != NO_ERROR) {
1032 return ret;
1033 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034
1035 // check calling permissions
1036 if (!settingsAllowed()) {
1037 return PERMISSION_DENIED;
1038 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001039 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001040 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041 return BAD_VALUE;
1042 }
1043
1044 { // scope for the lock
1045 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001046 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001048 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 mHardwareStatus = AUDIO_HW_IDLE;
1050 }
1051
1052 if (NO_ERROR == ret) {
1053 Mutex::Autolock _l(mLock);
1054 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001055 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001056 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 }
1058
1059 return ret;
1060}
1061
1062status_t AudioFlinger::setMicMute(bool state)
1063{
Eric Laurenta1884f92011-08-23 08:25:03 -07001064 status_t ret = initCheck();
1065 if (ret != NO_ERROR) {
1066 return ret;
1067 }
1068
Mathias Agopian65ab4712010-07-14 17:59:35 -07001069 // check calling permissions
1070 if (!settingsAllowed()) {
1071 return PERMISSION_DENIED;
1072 }
1073
1074 AutoMutex lock(mHardwareLock);
1075 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001076 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001077 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1078 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001079 if (result != NO_ERROR) {
1080 ret = result;
1081 }
1082 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 mHardwareStatus = AUDIO_HW_IDLE;
1084 return ret;
1085}
1086
1087bool AudioFlinger::getMicMute() const
1088{
Eric Laurenta1884f92011-08-23 08:25:03 -07001089 status_t ret = initCheck();
1090 if (ret != NO_ERROR) {
1091 return false;
1092 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001093 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001094 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001095 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001097 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001098 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1099 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001100 if (result == NO_ERROR) {
1101 mute = mute && state;
1102 }
1103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001105
1106 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107}
1108
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001109void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1110{
1111 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1112
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001113 AutoMutex lock(mLock);
1114 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001115 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1116 }
1117 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1118 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001119 }
1120}
1121
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122status_t AudioFlinger::setMasterMute(bool muted)
1123{
John Grossmand8f178d2012-07-20 14:51:35 -07001124 status_t ret = initCheck();
1125 if (ret != NO_ERROR) {
1126 return ret;
1127 }
1128
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 // check calling permissions
1130 if (!settingsAllowed()) {
1131 return PERMISSION_DENIED;
1132 }
1133
John Grossmanee578c02012-07-23 17:05:46 -07001134 Mutex::Autolock _l(mLock);
1135 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001136
John Grossmanee578c02012-07-23 17:05:46 -07001137 // Set master mute in the HALs which support it.
1138 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1139 AutoMutex lock(mHardwareLock);
1140 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001141
John Grossmanee578c02012-07-23 17:05:46 -07001142 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1143 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001144 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001145 }
John Grossmanee578c02012-07-23 17:05:46 -07001146 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001147 }
1148
John Grossmanee578c02012-07-23 17:05:46 -07001149 // Now set the master mute in each playback thread. Playback threads
1150 // assigned to HALs which do not have master mute support will apply master
1151 // mute during the mix operation. Threads with HALs which do support master
1152 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001153 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1154 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1155 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157
1158 return NO_ERROR;
1159}
1160
1161float AudioFlinger::masterVolume() const
1162{
Glenn Kasten98067102011-12-13 11:47:54 -08001163 Mutex::Autolock _l(mLock);
1164 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165}
1166
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001167status_t AudioFlinger::getMasterBalance(float *balance) const
1168{
1169 Mutex::Autolock _l(mLock);
1170 *balance = getMasterBalance_l();
1171 return NO_ERROR; // if called through binder, may return a transactional error
1172}
1173
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174bool AudioFlinger::masterMute() const
1175{
Glenn Kasten98067102011-12-13 11:47:54 -08001176 Mutex::Autolock _l(mLock);
1177 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178}
1179
John Grossman4ff14ba2012-02-08 16:37:41 -08001180float AudioFlinger::masterVolume_l() const
1181{
John Grossman4ff14ba2012-02-08 16:37:41 -08001182 return mMasterVolume;
1183}
1184
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001185float AudioFlinger::getMasterBalance_l() const
1186{
1187 return mMasterBalance;
1188}
1189
John Grossmand8f178d2012-07-20 14:51:35 -07001190bool AudioFlinger::masterMute_l() const
1191{
John Grossmanee578c02012-07-23 17:05:46 -07001192 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001193}
1194
Eric Laurent223fd5c2014-11-11 13:43:36 -08001195status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1196{
1197 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001198 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001199 return BAD_VALUE;
1200 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001201 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1202 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1203 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001204 return PERMISSION_DENIED;
1205 }
1206
1207 return NO_ERROR;
1208}
1209
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001210status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1211 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001212{
1213 // check calling permissions
1214 if (!settingsAllowed()) {
1215 return PERMISSION_DENIED;
1216 }
1217
Eric Laurent223fd5c2014-11-11 13:43:36 -08001218 status_t status = checkStreamType(stream);
1219 if (status != NO_ERROR) {
1220 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 }
Eric Laurent98e38192018-02-15 18:31:53 -08001222 if (output == AUDIO_IO_HANDLE_NONE) {
1223 return BAD_VALUE;
1224 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001225 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226
1227 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001228 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1229 if (volumeInterface == NULL) {
1230 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 }
Eric Laurent98e38192018-02-15 18:31:53 -08001232 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001233
1234 return NO_ERROR;
1235}
1236
Glenn Kastenfff6d712012-01-12 16:38:12 -08001237status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238{
1239 // check calling permissions
1240 if (!settingsAllowed()) {
1241 return PERMISSION_DENIED;
1242 }
1243
Eric Laurent223fd5c2014-11-11 13:43:36 -08001244 status_t status = checkStreamType(stream);
1245 if (status != NO_ERROR) {
1246 return status;
1247 }
1248 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1249
1250 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001251 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 return BAD_VALUE;
1253 }
1254
Eric Laurent93575202011-01-18 18:39:02 -08001255 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001257 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1258 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1259 volumeInterfaces[i]->setStreamMute(stream, muted);
1260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001261
1262 return NO_ERROR;
1263}
1264
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001265float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001267 status_t status = checkStreamType(stream);
1268 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 return 0.0f;
1270 }
Eric Laurent98e38192018-02-15 18:31:53 -08001271 if (output == AUDIO_IO_HANDLE_NONE) {
1272 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273 }
1274
Eric Laurent98e38192018-02-15 18:31:53 -08001275 AutoMutex lock(mLock);
1276 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1277 if (volumeInterface == NULL) {
1278 return 0.0f;
1279 }
1280
1281 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282}
1283
Glenn Kastenfff6d712012-01-12 16:38:12 -08001284bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001286 status_t status = checkStreamType(stream);
1287 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288 return true;
1289 }
1290
Glenn Kasten6637baa2012-01-09 09:40:36 -08001291 AutoMutex lock(mLock);
1292 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293}
1294
Eric Laurent054d9d32015-04-24 08:48:48 -07001295
1296void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1297{
1298 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1299 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1300 }
1301}
1302
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001303// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1304void AudioFlinger::forwardParametersToDownstreamPatches_l(
1305 audio_io_handle_t upStream, const String8& keyValuePairs,
1306 std::function<bool(const sp<PlaybackThread>&)> useThread)
1307{
1308 std::vector<PatchPanel::SoftwarePatch> swPatches;
1309 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1310 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1311 __func__, swPatches.size(), upStream);
1312 for (const auto& swPatch : swPatches) {
1313 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1314 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1315 downStream->setParameters(keyValuePairs);
1316 }
1317 }
1318}
1319
Eric Laurentf1047e82018-04-16 19:18:20 -07001320// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1321// Some keys are used for audio routing and audio path configuration and should be reserved for use
1322// by audio policy and audio flinger for functional, privacy and security reasons.
1323void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1324{
1325 static const String8 kReservedParameters[] = {
1326 String8(AudioParameter::keyRouting),
1327 String8(AudioParameter::keySamplingRate),
1328 String8(AudioParameter::keyFormat),
1329 String8(AudioParameter::keyChannels),
1330 String8(AudioParameter::keyFrameCount),
1331 String8(AudioParameter::keyInputSource),
1332 String8(AudioParameter::keyMonoOutput),
1333 String8(AudioParameter::keyStreamConnect),
1334 String8(AudioParameter::keyStreamDisconnect),
1335 String8(AudioParameter::keyStreamSupportedFormats),
1336 String8(AudioParameter::keyStreamSupportedChannels),
1337 String8(AudioParameter::keyStreamSupportedSamplingRates),
1338 };
1339
Andy Hung4ef19fa2018-05-15 19:35:29 -07001340 if (isAudioServerUid(callingUid)) {
1341 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001342 }
1343
1344 AudioParameter param = AudioParameter(keyValuePairs);
1345 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001346 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001347 for (auto& key : kReservedParameters) {
1348 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001349 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001350 param.remove(key);
1351 }
1352 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001353 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1354 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001355 keyValuePairs = param.toString();
1356}
1357
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001358void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1359 size_t rejectedKVPSize, const String8& rejectedKVPs,
1360 uid_t callingUid) {
1361 auto prefix = String8::format("UID %5d", callingUid);
1362 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1363 if (rejectedKVPSize != 0) {
1364 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1365 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1366 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1367 } else {
1368 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1369 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1370 }
1371}
1372
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001373status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374{
Eric Laurentf1047e82018-04-16 19:18:20 -07001375 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1376 ioHandle, keyValuePairs.string(),
1377 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001378
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379 // check calling permissions
1380 if (!settingsAllowed()) {
1381 return PERMISSION_DENIED;
1382 }
1383
Eric Laurentf1047e82018-04-16 19:18:20 -07001384 String8 filteredKeyValuePairs = keyValuePairs;
1385 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1386
1387 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1388
Glenn Kasten142f5192014-03-25 17:44:59 -07001389 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1390 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001391 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001392 // result will remain NO_INIT if no audio device is present
1393 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001394 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001395 AutoMutex lock(mHardwareLock);
1396 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1397 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001398 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001399 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001400 // return success if at least one audio device accepts the parameters as not all
1401 // HALs are requested to support all parameters. If no audio device supports the
1402 // requested parameters, the last error is reported.
1403 if (final_result != NO_ERROR) {
1404 final_result = result;
1405 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001406 }
1407 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001408 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001409 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001410 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001411 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001412 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1413 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001414 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001415 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001416 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001417 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001418 }
1419 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001420 String8 screenState;
1421 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001422 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001423 if (isOff != (AudioFlinger::mScreenState & 1)) {
1424 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001425 }
1426 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001427 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428 }
1429
1430 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1431 // and the thread is exited once the lock is released
1432 sp<ThreadBase> thread;
1433 {
1434 Mutex::Autolock _l(mLock);
1435 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001436 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001438 if (thread == 0) {
1439 thread = checkMmapThread_l(ioHandle);
1440 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001441 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001442 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001443 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001444 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001445 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1446 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001447 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001448 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449 }
1450 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001451 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001452 status_t result = thread->setParameters(filteredKeyValuePairs);
1453 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1454 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 }
1456 return BAD_VALUE;
1457}
1458
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001459String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001461 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1462 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463
Eric Laurenta4c5a552012-03-29 10:12:40 -07001464 Mutex::Autolock _l(mLock);
1465
Glenn Kasten142f5192014-03-25 17:44:59 -07001466 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001467 String8 out_s8;
1468
Dima Zavin799a70e2011-04-18 16:57:27 -07001469 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001470 String8 s;
1471 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001472 {
1473 AutoMutex lock(mHardwareLock);
1474 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001475 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1476 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001477 mHardwareStatus = AUDIO_HW_IDLE;
1478 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001479 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001480 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001481 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 }
1483
Eric Laurent6acd1d42017-01-04 14:23:29 -08001484 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1485 if (thread == NULL) {
1486 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1487 if (thread == NULL) {
1488 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1489 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001490 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001491 }
1492 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001494 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495}
1496
Glenn Kastendd8104c2012-07-02 12:42:44 -07001497size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1498 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499{
Eric Laurenta1884f92011-08-23 08:25:03 -07001500 status_t ret = initCheck();
1501 if (ret != NO_ERROR) {
1502 return 0;
1503 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001504 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001505 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001506 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001507 return 0;
1508 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001509
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001510 AutoMutex lock(mHardwareLock);
1511 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001512 audio_config_t config, proposed;
1513 memset(&proposed, 0, sizeof(proposed));
1514 proposed.sample_rate = sampleRate;
1515 proposed.channel_mask = channelMask;
1516 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001517
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001518 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001519 size_t frames;
1520 for (;;) {
1521 // Note: config is currently a const parameter for get_input_buffer_size()
1522 // but we use a copy from proposed in case config changes from the call.
1523 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001524 status_t result = dev->getInputBufferSize(&config, &frames);
1525 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001526 break; // hal success, config is the result
1527 }
1528 // change one parameter of the configuration each iteration to a more "common" value
1529 // to see if the device will support it.
1530 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1531 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1532 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1533 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1534 } else {
1535 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1536 "format %#x, channelMask 0x%X",
1537 sampleRate, format, channelMask);
1538 break; // retries failed, break out of loop with frames == 0.
1539 }
1540 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001541 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001542 if (frames > 0 && config.sample_rate != sampleRate) {
1543 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1544 }
1545 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546}
1547
Glenn Kasten5f972c02014-01-13 09:59:31 -08001548uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 Mutex::Autolock _l(mLock);
1551
1552 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1553 if (recordThread != NULL) {
1554 return recordThread->getInputFramesLost();
1555 }
1556 return 0;
1557}
1558
1559status_t AudioFlinger::setVoiceVolume(float value)
1560{
Eric Laurenta1884f92011-08-23 08:25:03 -07001561 status_t ret = initCheck();
1562 if (ret != NO_ERROR) {
1563 return ret;
1564 }
1565
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 // check calling permissions
1567 if (!settingsAllowed()) {
1568 return PERMISSION_DENIED;
1569 }
1570
1571 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001572 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001573 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001574 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575 mHardwareStatus = AUDIO_HW_IDLE;
1576
1577 return ret;
1578}
1579
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001580status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001581 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 Mutex::Autolock _l(mLock);
1584
1585 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1586 if (playbackThread != NULL) {
1587 return playbackThread->getRenderPosition(halFrames, dspFrames);
1588 }
1589
1590 return BAD_VALUE;
1591}
1592
1593void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1594{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001596 if (client == 0) {
1597 return;
1598 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001599 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001600 {
1601 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001602 if (mNotificationClients.indexOfKey(pid) < 0) {
1603 sp<NotificationClient> notificationClient = new NotificationClient(this,
1604 client,
1605 pid);
1606 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607
Eric Laurent021cf962014-05-13 10:18:14 -07001608 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609
Marco Nelissen06b46062014-11-14 07:58:25 -08001610 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001611 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001612 }
1613 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614
Eric Laurent021cf962014-05-13 10:18:14 -07001615 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001616 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001617 // the config change is always sent from playback or record threads to avoid deadlock
1618 // with AudioSystem::gLock
1619 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001620 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001621 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001623 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001624 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 }
1626}
1627
1628void AudioFlinger::removeNotificationClient(pid_t pid)
1629{
1630 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001631 {
1632 Mutex::Autolock _cl(mClientLock);
1633 mNotificationClients.removeItem(pid);
1634 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001635
Steve Block3856b092011-10-20 11:56:00 +01001636 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001637 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001638 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001639 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001640 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001641 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001642 if (ref->mPid == pid) {
1643 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001644 mAudioSessionRefs.removeAt(i);
1645 delete ref;
1646 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001647 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001648 } else {
1649 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001650 }
1651 }
1652 if (removed) {
1653 purgeStaleEffects_l();
1654 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655}
1656
Eric Laurent73e26b62015-04-27 16:55:58 -07001657void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001658 const sp<AudioIoDescriptor>& ioDesc,
1659 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660{
Eric Laurent021cf962014-05-13 10:18:14 -07001661 Mutex::Autolock _l(mClientLock);
1662 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001664 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1665 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667 }
1668}
1669
Eric Laurent021cf962014-05-13 10:18:14 -07001670// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671void AudioFlinger::removeClient_l(pid_t pid)
1672{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001673 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001674 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 mClients.removeItem(pid);
1676}
1677
Eric Laurent717e1282012-06-29 16:36:52 -07001678// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001679sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1680 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001681{
1682 sp<PlaybackThread> thread;
1683
1684 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1685 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1686 ALOG_ASSERT(thread == 0);
1687 thread = mPlaybackThreads.valueAt(i);
1688 }
1689 }
1690
1691 return thread;
1692}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695
1696// ----------------------------------------------------------------------------
1697
1698AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1699 : RefBase(),
1700 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001701 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702{
Andy Hung6f248bb2018-01-23 14:04:37 -08001703 mMemoryDealer = new MemoryDealer(
1704 audioFlinger->getClientSharedHeapSize(),
1705 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706}
1707
Eric Laurent021cf962014-05-13 10:18:14 -07001708// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709AudioFlinger::Client::~Client()
1710{
1711 mAudioFlinger->removeClient_l(mPid);
1712}
1713
Glenn Kasten435dbe62012-01-30 10:15:48 -08001714sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715{
1716 return mMemoryDealer;
1717}
1718
1719// ----------------------------------------------------------------------------
1720
1721AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1722 const sp<IAudioFlingerClient>& client,
1723 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001724 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725{
1726}
1727
1728AudioFlinger::NotificationClient::~NotificationClient()
1729{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730}
1731
Glenn Kasten0f11b512014-01-31 16:18:54 -08001732void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733{
1734 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001735 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736}
1737
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001738// ----------------------------------------------------------------------------
1739AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1740 : mPendingRequests(false) {}
1741
1742
1743void AudioFlinger::MediaLogNotifier::requestMerge() {
1744 AutoMutex _l(mMutex);
1745 mPendingRequests = true;
1746 mCond.signal();
1747}
1748
1749bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001750 // Should already have been checked, but just in case
1751 if (sMediaLogService == 0) {
1752 return false;
1753 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001754 // Wait until there are pending requests
1755 {
1756 AutoMutex _l(mMutex);
1757 mPendingRequests = false; // to ignore past requests
1758 while (!mPendingRequests) {
1759 mCond.wait(mMutex);
1760 // TODO may also need an exitPending check
1761 }
1762 mPendingRequests = false;
1763 }
1764 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001765 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001766 usleep(kPostTriggerSleepPeriod);
1767 return true;
1768}
1769
1770void AudioFlinger::requestLogMerge() {
1771 mMediaLogNotifier->requestMerge();
1772}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773
1774// ----------------------------------------------------------------------------
1775
Eric Laurentf14db3c2017-12-08 14:20:36 -08001776sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1777 CreateRecordOutput& output,
1778 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779{
1780 sp<RecordThread::RecordTrack> recordTrack;
1781 sp<RecordHandle> recordHandle;
1782 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001784 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001785 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786
Eric Laurentf14db3c2017-12-08 14:20:36 -08001787 output.cblk.clear();
1788 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001789 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001790
Eric Laurentf14db3c2017-12-08 14:20:36 -08001791 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001792 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001793 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001794 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001795 ALOGW_IF(clientUid != callingUid,
1796 "%s uid %d tried to pass itself off as %d",
1797 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001798 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001799 updatePid = true;
1800 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001801 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001802 if (updatePid) {
1803 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001804 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001805 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001806 __func__, callingUid, callingPid, clientPid);
1807 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001808 }
1809
Andy Hung6770c6f2015-04-07 13:43:36 -07001810 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001811 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1812 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001813 lStatus = BAD_VALUE;
1814 goto Exit;
1815 }
1816
Glenn Kasten53b5d092014-02-05 10:00:23 -08001817 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001818 if (!audio_is_input_channel(input.config.channel_mask)) {
1819 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001820 lStatus = BAD_VALUE;
1821 goto Exit;
1822 }
1823
Eric Laurentf14db3c2017-12-08 14:20:36 -08001824 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1825 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1826 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1827 lStatus = BAD_VALUE;
1828 goto Exit;
1829 }
1830
1831 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001832 output.selectedDeviceId = input.selectedDeviceId;
1833 output.flags = input.flags;
1834
1835 client = registerPid(clientPid);
1836
1837 // Not a conventional loop, but a retry loop for at most two iterations total.
1838 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1839 // Exits loop via break on no error of got exit on error
1840 // The sp<> references will be dropped when re-entering scope.
1841 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1842 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001843 // release previously opened input if retrying.
1844 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1845 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001846 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001847 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001848 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001849 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001850 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001851 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1852 sessionId,
1853 // FIXME compare to AudioTrack
1854 clientPid,
1855 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001856 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001857 &input.config,
1858 output.flags, &output.selectedDeviceId, &portId);
1859
Glenn Kasten05997e22014-03-13 15:08:33 -07001860 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001862 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001864 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 lStatus = BAD_VALUE;
1866 goto Exit;
1867 }
1868
Eric Laurentf14db3c2017-12-08 14:20:36 -08001869 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870
Eric Laurentf14db3c2017-12-08 14:20:36 -08001871 output.sampleRate = input.config.sample_rate;
1872 output.frameCount = input.frameCount;
1873 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001874
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001875 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001876 input.config.format, input.config.channel_mask,
1877 &output.frameCount, sessionId,
1878 &output.notificationFrameCount,
1879 clientUid, &output.flags,
1880 input.clientInfo.clientTid,
1881 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001882 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001883
Eric Laurentf14db3c2017-12-08 14:20:36 -08001884 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1885 // audio policy manager without FAST constraint
1886 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001887 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001888 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001889
1890 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001891 goto Exit;
1892 }
1893
1894 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1895 // session and move it to this thread.
1896 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1897 if (chain != 0) {
1898 Mutex::Autolock _l(thread->mLock);
1899 thread->addEffectChain_l(chain);
1900 }
1901 break;
1902 }
1903 // End of retry loop.
1904 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 }
Glenn Kastene198c362013-08-13 09:13:36 -07001906
Eric Laurentf14db3c2017-12-08 14:20:36 -08001907 output.cblk = recordTrack->getCblk();
1908 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001909 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001910
1911 // return handle to client
1912 recordHandle = new RecordHandle(recordTrack);
1913
1914Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001915 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001916 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001917 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001918 // Don't hold mClientLock when releasing the reference on the track as the
1919 // destructor will acquire it.
1920 {
1921 Mutex::Autolock _cl(mClientLock);
1922 client.clear();
1923 }
Eric Laurent896c9672017-12-08 14:08:45 -08001924 recordTrack.clear();
1925 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001926 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001927 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 }
1929
Glenn Kasten9156ef32013-08-06 15:39:08 -07001930 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 return recordHandle;
1932}
1933
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001934
1935
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936// ----------------------------------------------------------------------------
1937
Eric Laurenta4c5a552012-03-29 10:12:40 -07001938audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1939{
Eric Laurent44622db2014-08-01 19:00:33 -07001940 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001941 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001942 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001943 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001944 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001945 }
1946 Mutex::Autolock _l(mLock);
1947 return loadHwModule_l(name);
1948}
1949
1950// loadHwModule_l() must be called with AudioFlinger::mLock held
1951audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1952{
1953 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1954 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1955 ALOGW("loadHwModule() module %s already loaded", name);
1956 return mAudioHwDevs.keyAt(i);
1957 }
1958 }
1959
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001960 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001961
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001962 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001963 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001964 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001965 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001966 }
1967
1968 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001969 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001970 mHardwareStatus = AUDIO_HW_IDLE;
1971 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001972 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001973 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001974 }
1975
John Grossmanee578c02012-07-23 17:05:46 -07001976 // Check and cache this HAL's level of support for master mute and master
1977 // volume. If this is the first HAL opened, and it supports the get
1978 // methods, use the initial values provided by the HAL as the current
1979 // master mute and volume settings.
1980
1981 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1982 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001983 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001984
1985 if (0 == mAudioHwDevs.size()) {
1986 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001987 float mv;
1988 if (OK == dev->getMasterVolume(&mv)) {
1989 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001990 }
1991
1992 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001993 bool mm;
1994 if (OK == dev->getMasterMute(&mm)) {
1995 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001996 }
1997 }
1998
Eric Laurenta4c5a552012-03-29 10:12:40 -07001999 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002000 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002001 flags = static_cast<AudioHwDevice::Flags>(flags |
2002 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2003 }
2004
2005 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002006 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002007 flags = static_cast<AudioHwDevice::Flags>(flags |
2008 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2009 }
2010
Eric Laurenta4c5a552012-03-29 10:12:40 -07002011 mHardwareStatus = AUDIO_HW_IDLE;
2012 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002013 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002014 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2015 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2016 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002017
Glenn Kastena13cde92016-03-28 15:26:02 -07002018 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002019 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002020
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002021 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002022
2023 return handle;
2024
2025}
2026
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002027// ----------------------------------------------------------------------------
2028
Glenn Kasten3b16c762012-11-14 08:44:39 -08002029uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002030{
2031 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002032 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002033 return thread != NULL ? thread->sampleRate() : 0;
2034}
2035
Glenn Kastene33054e2012-11-14 12:54:39 -08002036size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002037{
2038 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002039 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002040 return thread != NULL ? thread->frameCountHAL() : 0;
2041}
2042
2043// ----------------------------------------------------------------------------
2044
Andy Hung6f248bb2018-01-23 14:04:37 -08002045status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002046{
2047 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002048 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002049 return PERMISSION_DENIED;
2050 }
2051 Mutex::Autolock _l(mLock);
2052 if (mIsDeviceTypeKnown) {
2053 return INVALID_OPERATION;
2054 }
2055 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002056 mTotalMemory = totalMemory;
2057 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2058 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2059 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2060 // though actual setting is determined through device configuration.
2061 constexpr int64_t GB = 1024 * 1024 * 1024;
2062 mClientSharedHeapSize =
2063 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2064 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2065 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2066 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2067 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002068 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002069
2070 // TODO: Cache the client shared heap size in a persistent property.
2071 // It's possible that a native process or Java service or app accesses audioserver
2072 // after it is registered by system server, but before AudioService updates
2073 // the memory info. This would occur immediately after boot or an audioserver
2074 // crash and restore. Before update from AudioService, the client would get the
2075 // minimum heap size.
2076
2077 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2078 (isLowRamDevice ? "true" : "false"),
2079 (long long)mTotalMemory,
2080 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002081 return NO_ERROR;
2082}
2083
Andy Hung6f248bb2018-01-23 14:04:37 -08002084size_t AudioFlinger::getClientSharedHeapSize() const
2085{
2086 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2087 if (heapSizeInBytes != 0) { // read-only property overrides all.
2088 return heapSizeInBytes;
2089 }
2090 return mClientSharedHeapSize;
2091}
2092
Mikhail Naganovdea53042018-04-26 13:10:21 -07002093status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2094{
2095 ALOGV(__func__);
2096
2097 audio_module_handle_t module;
2098 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2099 module = config->ext.device.hw_module;
2100 } else {
2101 module = config->ext.mix.hw_module;
2102 }
2103
2104 Mutex::Autolock _l(mLock);
2105 ssize_t index = mAudioHwDevs.indexOfKey(module);
2106 if (index < 0) {
2107 ALOGW("%s() bad hw module %d", __func__, module);
2108 return BAD_VALUE;
2109 }
2110
2111 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2112 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2113}
2114
Eric Laurent93c3d412014-08-01 14:48:35 -07002115audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2116{
2117 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002118
2119 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2120 if (index >= 0) {
2121 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2122 mHwAvSyncIds.valueAt(index), sessionId);
2123 return mHwAvSyncIds.valueAt(index);
2124 }
2125
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002126 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002127 if (dev == NULL) {
2128 return AUDIO_HW_SYNC_INVALID;
2129 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002130 String8 reply;
2131 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002132 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002133 param = AudioParameter(reply);
2134 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002135
2136 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002137 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002138 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2139 return AUDIO_HW_SYNC_INVALID;
2140 }
2141
2142 // allow only one session for a given HW A/V sync ID.
2143 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2144 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2145 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2146 value, mHwAvSyncIds.keyAt(i));
2147 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002148 break;
2149 }
2150 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002151
2152 mHwAvSyncIds.add(sessionId, value);
2153
2154 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2155 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2156 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002157 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002158 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002159 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002160 String8 keyValuePairs = param.toString();
2161 thread->setParameters(keyValuePairs);
2162 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2163 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002164 break;
2165 }
2166 }
2167
2168 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2169 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002170}
2171
Eric Laurent72e3f392015-05-20 14:43:50 -07002172status_t AudioFlinger::systemReady()
2173{
2174 Mutex::Autolock _l(mLock);
2175 ALOGI("%s", __FUNCTION__);
2176 if (mSystemReady) {
2177 ALOGW("%s called twice", __FUNCTION__);
2178 return NO_ERROR;
2179 }
2180 mSystemReady = true;
2181 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2182 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2183 thread->systemReady();
2184 }
2185 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2186 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2187 thread->systemReady();
2188 }
2189 return NO_ERROR;
2190}
2191
jiabin46a76fa2018-01-05 10:18:21 -08002192status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2193{
jiabin9ff780e2018-03-19 18:19:52 -07002194 AutoMutex lock(mHardwareLock);
2195 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2196 status_t status = dev->getMicrophones(microphones);
2197 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002198}
2199
Eric Laurentfa90e842014-10-17 18:12:31 -07002200// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2201void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2202{
2203 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2204 if (index >= 0) {
2205 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2206 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2207 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002208 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002209 String8 keyValuePairs = param.toString();
2210 thread->setParameters(keyValuePairs);
2211 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2212 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002213 }
2214}
2215
2216
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002217// ----------------------------------------------------------------------------
2218
Eric Laurent83b88082014-06-20 18:31:16 -07002219
Eric Laurent6acd1d42017-01-04 14:23:29 -08002220sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002221 audio_io_handle_t *output,
2222 audio_config_t *config,
2223 audio_devices_t devices,
2224 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002225 audio_output_flags_t flags)
2226{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002227 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002228 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002229 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002230 }
2231
Eric Laurentcf2c0212014-07-25 16:20:43 -07002232 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002233 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2234 } else {
2235 // Audio Policy does not currently request a specific output handle.
2236 // If this is ever needed, see openInput_l() for example code.
2237 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2238 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002239 }
Eric Laurent83b88082014-06-20 18:31:16 -07002240
2241 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2242
Eric Laurent83b88082014-06-20 18:31:16 -07002243 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002244 // This if statement allows overriding the audio policy settings
2245 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2246 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2247 // Check only for Normal Mixing mode
2248 if (kEnableExtendedPrecision) {
2249 // Specify format (uncomment one below to choose)
2250 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2251 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2252 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2253 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002254 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002255 }
2256 if (kEnableExtendedChannels) {
2257 // Specify channel mask (uncomment one below to choose)
2258 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2259 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2260 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2261 }
Eric Laurent83b88082014-06-20 18:31:16 -07002262 }
2263
Phil Burk062e67a2015-02-11 13:40:50 -08002264 AudioStreamOut *outputStream = NULL;
2265 status_t status = outHwDev->openOutputStream(
2266 &outputStream,
2267 *output,
2268 devices,
2269 flags,
2270 config,
2271 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002272
2273 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002274
Phil Burk062e67a2015-02-11 13:40:50 -08002275 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002276 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2277 sp<MmapPlaybackThread> thread =
2278 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2279 devices, AUDIO_DEVICE_NONE, mSystemReady);
2280 mMmapThreads.add(*output, thread);
2281 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2282 *output, thread.get());
2283 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002284 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002285 sp<PlaybackThread> thread;
2286 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2287 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2288 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2289 *output, thread.get());
2290 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2291 || !isValidPcmSinkFormat(config->format)
2292 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2293 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2294 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2295 *output, thread.get());
2296 } else {
2297 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2298 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2299 *output, thread.get());
2300 }
2301 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002302 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002303 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002304 }
Eric Laurent83b88082014-06-20 18:31:16 -07002305 }
2306
2307 return 0;
2308}
2309
Eric Laurentcf2c0212014-07-25 16:20:43 -07002310status_t AudioFlinger::openOutput(audio_module_handle_t module,
2311 audio_io_handle_t *output,
2312 audio_config_t *config,
2313 audio_devices_t *devices,
2314 const String8& address,
2315 uint32_t *latencyMs,
2316 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002318 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2319 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002320 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002321 (devices != NULL) ? *devices : 0,
2322 config->sample_rate,
2323 config->format,
2324 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002325 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002327 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002328 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002330
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 Mutex::Autolock _l(mLock);
2332
Eric Laurent6acd1d42017-01-04 14:23:29 -08002333 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002334 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002335 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2336 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2337 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338
Eric Laurent6acd1d42017-01-04 14:23:29 -08002339 // notify client processes of the new output creation
2340 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002341
Eric Laurent6acd1d42017-01-04 14:23:29 -08002342 // the first primary output opened designates the primary hw device
2343 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002344 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002345 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002346
Eric Laurent6acd1d42017-01-04 14:23:29 -08002347 AutoMutex lock(mHardwareLock);
2348 mHardwareStatus = AUDIO_HW_SET_MODE;
2349 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2350 mHardwareStatus = AUDIO_HW_IDLE;
2351 }
2352 } else {
2353 MmapThread *mmapThread = (MmapThread *)thread.get();
2354 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002355 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002356 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 }
2358
Eric Laurentcf2c0212014-07-25 16:20:43 -07002359 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360}
2361
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002362audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2363 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364{
2365 Mutex::Autolock _l(mLock);
2366 MixerThread *thread1 = checkMixerThread_l(output1);
2367 MixerThread *thread2 = checkMixerThread_l(output2);
2368
2369 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002370 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2371 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002372 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373 }
2374
Glenn Kasteneeecb982016-02-26 10:44:04 -08002375 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002376 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377 thread->addOutputTrack(thread2);
2378 mPlaybackThreads.add(id, thread);
2379 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002380 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381 return id;
2382}
2383
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002384status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385{
Glenn Kastend96c5722012-04-25 13:44:49 -07002386 return closeOutput_nonvirtual(output);
2387}
2388
2389status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2390{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 // keep strong reference on the playback thread so that
2392 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002393 sp<PlaybackThread> playbackThread;
2394 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 {
2396 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002397 playbackThread = checkPlaybackThread_l(output);
2398 if (playbackThread != NULL) {
2399 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400
Andy Hungdc099c22018-09-18 13:46:39 -07002401 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002402
Eric Laurent6acd1d42017-01-04 14:23:29 -08002403 if (playbackThread->type() == ThreadBase::MIXER) {
2404 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2405 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2406 DuplicatingThread *dupThread =
2407 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2408 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2409 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002410 }
2411 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412
2413
Eric Laurent6acd1d42017-01-04 14:23:29 -08002414 mPlaybackThreads.removeItem(output);
2415 // save all effects to the default thread
2416 if (mPlaybackThreads.size()) {
2417 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2418 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002419 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002420 Mutex::Autolock _dl(dstThread->mLock);
2421 Mutex::Autolock _sl(playbackThread->mLock);
2422 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2423 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002424 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2425 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 }
2428 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002429 } else {
2430 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2431 if (mmapThread == 0) {
2432 return BAD_VALUE;
2433 }
Andy Hungdc099c22018-09-18 13:46:39 -07002434 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002435 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002436 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002438 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2439 ioDesc->mIoHandle = output;
2440 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002441 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002443 // The thread entity (active unit of execution) is no longer running here,
2444 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445
Eric Laurent6acd1d42017-01-04 14:23:29 -08002446 if (playbackThread != 0) {
2447 playbackThread->exit();
2448 if (!playbackThread->isDuplicating()) {
2449 closeOutputFinish(playbackThread);
2450 }
2451 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002452 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002453 mmapThread->exit();
2454 AudioStreamOut *out = mmapThread->clearOutput();
2455 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2456 // from now on thread->mOutput is NULL
2457 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 }
2459 return NO_ERROR;
2460}
2461
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002462void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002463{
2464 AudioStreamOut *out = thread->clearOutput();
2465 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2466 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002467 delete out;
2468}
2469
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002470void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002471{
2472 mPlaybackThreads.removeItem(thread->mId);
2473 thread->exit();
2474 closeOutputFinish(thread);
2475}
2476
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002477status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478{
2479 Mutex::Autolock _l(mLock);
2480 PlaybackThread *thread = checkPlaybackThread_l(output);
2481
2482 if (thread == NULL) {
2483 return BAD_VALUE;
2484 }
2485
Steve Block3856b092011-10-20 11:56:00 +01002486 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 thread->suspend();
2488
2489 return NO_ERROR;
2490}
2491
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002492status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493{
2494 Mutex::Autolock _l(mLock);
2495 PlaybackThread *thread = checkPlaybackThread_l(output);
2496
2497 if (thread == NULL) {
2498 return BAD_VALUE;
2499 }
2500
Steve Block3856b092011-10-20 11:56:00 +01002501 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502
2503 thread->restore();
2504
2505 return NO_ERROR;
2506}
2507
Eric Laurentcf2c0212014-07-25 16:20:43 -07002508status_t AudioFlinger::openInput(audio_module_handle_t module,
2509 audio_io_handle_t *input,
2510 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002511 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002512 const String8& address,
2513 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002514 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515{
Eric Laurent83b88082014-06-20 18:31:16 -07002516 Mutex::Autolock _l(mLock);
2517
Glenn Kastene7d66712015-03-05 13:46:52 -08002518 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002519 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002520 }
2521
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002522 sp<ThreadBase> thread = openInput_l(
2523 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002524
2525 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002526 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002527 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002528 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002530 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002531}
Dima Zavin799a70e2011-04-18 16:57:27 -07002532
Eric Laurent6acd1d42017-01-04 14:23:29 -08002533sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002534 audio_io_handle_t *input,
2535 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002536 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002537 const String8& address,
2538 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002539 audio_input_flags_t flags,
2540 audio_devices_t outputDevice,
2541 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002542{
Glenn Kastene7d66712015-03-05 13:46:52 -08002543 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002544 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002545 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002546 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002547 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002548
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002549 // Some flags are specific to framework and must not leak to the HAL.
2550 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2551
Glenn Kasteneeecb982016-02-26 10:44:04 -08002552 // Audio Policy can request a specific handle for hardware hotword.
2553 // The goal here is not to re-open an already opened input.
2554 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002555 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002556 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2557 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2558 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2559 return 0;
2560 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2561 // This should not happen in a transient state with current design.
2562 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2563 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002564 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002565
Eric Laurentcf2c0212014-07-25 16:20:43 -07002566 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002567 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002568 sp<StreamInHalInterface> inStream;
2569 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002570 *input, devices, &halconfig, flags, address.string(), source,
2571 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002572 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2573 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002574 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002575 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002576 halconfig.sample_rate,
2577 halconfig.format,
2578 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002579 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002580 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002582 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002583 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002584 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002585 audio_is_linear_pcm(config->format) &&
2586 audio_is_linear_pcm(halconfig.format) &&
2587 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002588 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2589 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002590 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002591 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002592 inStream.clear();
2593 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002594 *input, devices, &halconfig, flags, address.string(), source,
2595 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002596 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597 }
2598
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002599 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002600 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002601 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2602 sp<MmapCaptureThread> thread =
2603 new MmapCaptureThread(this, *input,
2604 inHwDev, inputStream,
2605 primaryOutputDevice_l(), devices, mSystemReady);
2606 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002607 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2608 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002609 return thread;
2610 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002611 // Start record thread
2612 // RecordThread requires both input and output device indication to forward to audio
2613 // pre processing modules
2614 sp<RecordThread> thread = new RecordThread(this,
2615 inputStream,
2616 *input,
2617 primaryOutputDevice_l(),
2618 devices,
2619 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002620 );
2621 mRecordThreads.add(*input, thread);
2622 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2623 return thread;
2624 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 }
2626
Eric Laurentcf2c0212014-07-25 16:20:43 -07002627 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 return 0;
2629}
2630
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002631status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632{
Glenn Kastend96c5722012-04-25 13:44:49 -07002633 return closeInput_nonvirtual(input);
2634}
2635
2636status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2637{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 // keep strong reference on the record thread so that
2639 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002640 sp<RecordThread> recordThread;
2641 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 {
2643 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002644 recordThread = checkRecordThread_l(input);
2645 if (recordThread != 0) {
2646 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647
Andy Hungdc099c22018-09-18 13:46:39 -07002648 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002649
Eric Laurent6acd1d42017-01-04 14:23:29 -08002650 // If we still have effect chains, it means that a client still holds a handle
2651 // on at least one effect. We must either move the chain to an existing thread with the
2652 // same session ID or put it aside in case a new record thread is opened for a
2653 // new capture on the same session
2654 sp<EffectChain> chain;
2655 {
2656 Mutex::Autolock _sl(recordThread->mLock);
2657 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2658 // Note: maximum one chain per record thread
2659 if (effectChains.size() != 0) {
2660 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002661 }
2662 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002663 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002664 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002665 // This should only happen in case of overlap between one thread tear down and the
2666 // creation of its replacement
2667 size_t i;
2668 for (i = 0; i < mRecordThreads.size(); i++) {
2669 sp<RecordThread> t = mRecordThreads.valueAt(i);
2670 if (t == recordThread) {
2671 continue;
2672 }
2673 if (t->hasAudioSession(chain->sessionId()) != 0) {
2674 Mutex::Autolock _l(t->mLock);
2675 ALOGV("closeInput() found thread %d for effect session %d",
2676 t->id(), chain->sessionId());
2677 t->addEffectChain_l(chain);
2678 break;
2679 }
2680 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002681 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002682 if (i == mRecordThreads.size()) {
2683 putOrphanEffectChain_l(chain);
2684 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002685 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002686 mRecordThreads.removeItem(input);
2687 } else {
2688 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2689 if (mmapThread == 0) {
2690 return BAD_VALUE;
2691 }
Andy Hungdc099c22018-09-18 13:46:39 -07002692 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002693 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002694 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002695 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2696 ioDesc->mIoHandle = input;
2697 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 }
Eric Laurent83b88082014-06-20 18:31:16 -07002699 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2700 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002701 if (recordThread != 0) {
2702 closeInputFinish(recordThread);
2703 } else if (mmapThread != 0) {
2704 mmapThread->exit();
2705 AudioStreamIn *in = mmapThread->clearInput();
2706 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2707 // from now on thread->mInput is NULL
2708 delete in;
2709 }
Eric Laurent83b88082014-06-20 18:31:16 -07002710 return NO_ERROR;
2711}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002713void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002714{
2715 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002716 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002717 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002718 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002719 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002720}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002722void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002723{
2724 mRecordThreads.removeItem(thread->mId);
2725 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726}
2727
Glenn Kastend2304db2014-02-03 07:40:31 -08002728status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729{
2730 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002731 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732
2733 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2734 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002735 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002736 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002737 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2738 mMmapThreads[i]->invalidateTracks(stream);
2739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740 return NO_ERROR;
2741}
2742
2743
Glenn Kasteneeecb982016-02-26 10:44:04 -08002744audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745{
Glenn Kasten9d003132016-04-06 14:38:09 -07002746 // This is a binder API, so a malicious client could pass in a bad parameter.
2747 // Check for that before calling the internal API nextUniqueId().
2748 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2749 ALOGE("newAudioUniqueId invalid use %d", use);
2750 return AUDIO_UNIQUE_ID_ALLOCATE;
2751 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002752 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753}
2754
Glenn Kastend848eb42016-03-08 13:42:11 -08002755void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002756{
2757 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002758 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002759 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002760 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2761 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002762 caller = pid;
2763 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002764
Eric Laurent021cf962014-05-13 10:18:14 -07002765 {
2766 Mutex::Autolock _cl(mClientLock);
2767 // Ignore requests received from processes not known as notification client. The request
2768 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2769 // called from a different pid leaving a stale session reference. Also we don't know how
2770 // to clear this reference if the client process dies.
2771 if (mNotificationClients.indexOfKey(caller) < 0) {
2772 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2773 return;
2774 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002775 }
2776
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002777 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002778 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002779 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002780 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2781 ref->mCnt++;
2782 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002783 return;
2784 }
2785 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002786 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2787 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002788}
2789
Glenn Kastend848eb42016-03-08 13:42:11 -08002790void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002791{
2792 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002793 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002794 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002795 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2796 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002797 caller = pid;
2798 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002799 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002800 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002801 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002802 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2803 ref->mCnt--;
2804 ALOGV(" decremented refcount to %d", ref->mCnt);
2805 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002806 mAudioSessionRefs.removeAt(i);
2807 delete ref;
2808 purgeStaleEffects_l();
2809 }
2810 return;
2811 }
2812 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002813 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002814 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002815 ALOGW_IF(!isAudioServerUid(callerUid),
2816 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002817}
2818
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002819bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2820{
2821 size_t num = mAudioSessionRefs.size();
2822 for (size_t i = 0; i < num; i++) {
2823 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2824 if (ref->mSessionid == audioSession) {
2825 return true;
2826 }
2827 }
2828 return false;
2829}
2830
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002831void AudioFlinger::purgeStaleEffects_l() {
2832
Steve Block3856b092011-10-20 11:56:00 +01002833 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002834
2835 Vector< sp<EffectChain> > chains;
2836
2837 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2838 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002839 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002840 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2841 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002842 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2843 chains.push(ec);
2844 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002845 }
2846 }
2847 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2848 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002849 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002850 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2851 sp<EffectChain> ec = t->mEffectChains[j];
2852 chains.push(ec);
2853 }
2854 }
2855
2856 for (size_t i = 0; i < chains.size(); i++) {
2857 sp<EffectChain> ec = chains[i];
2858 int sessionid = ec->sessionId();
2859 sp<ThreadBase> t = ec->mThread.promote();
2860 if (t == 0) {
2861 continue;
2862 }
2863 size_t numsessionrefs = mAudioSessionRefs.size();
2864 bool found = false;
2865 for (size_t k = 0; k < numsessionrefs; k++) {
2866 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002867 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002868 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002869 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002870 found = true;
2871 break;
2872 }
2873 }
2874 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002875 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002876 // remove all effects from the chain
2877 while (ec->mEffects.size()) {
2878 sp<EffectModule> effect = ec->mEffects[0];
2879 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002880 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002881 if (effect->purgeHandles()) {
2882 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002883 }
2884 AudioSystem::unregisterEffect(effect->id());
2885 }
2886 }
2887 }
2888 return;
2889}
2890
Andy Hungdc099c22018-09-18 13:46:39 -07002891// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2892void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2893{
2894 audio_utils::FdToString fdToString;
2895 const int fd = fdToString.fd();
2896 if (fd >= 0) {
2897 thread->dump(fd, {} /* args */);
2898 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2899 }
2900}
2901
Glenn Kasteneeecb982016-02-26 10:44:04 -08002902// checkThread_l() must be called with AudioFlinger::mLock held
2903AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2904{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002905 ThreadBase *thread = checkMmapThread_l(ioHandle);
2906 if (thread == 0) {
2907 switch (audio_unique_id_get_use(ioHandle)) {
2908 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2909 thread = checkPlaybackThread_l(ioHandle);
2910 break;
2911 case AUDIO_UNIQUE_ID_USE_INPUT:
2912 thread = checkRecordThread_l(ioHandle);
2913 break;
2914 default:
2915 break;
2916 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002917 }
2918 return thread;
2919}
2920
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002922AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923{
Glenn Kastena1117922012-01-26 10:53:32 -08002924 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925}
2926
2927// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002928AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929{
2930 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002931 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932}
2933
2934// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002935AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936{
Glenn Kastena1117922012-01-26 10:53:32 -08002937 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938}
2939
Eric Laurent6acd1d42017-01-04 14:23:29 -08002940// checkMmapThread_l() must be called with AudioFlinger::mLock held
2941AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2942{
2943 return mMmapThreads.valueFor(io).get();
2944}
2945
2946
2947// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2948AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2949{
Eric Laurent7459b902017-04-19 18:10:41 -07002950 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002951 if (volumeInterface == nullptr) {
2952 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2953 if (mmapThread != nullptr) {
2954 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002955 MmapPlaybackThread *mmapPlaybackThread =
2956 static_cast<MmapPlaybackThread *>(mmapThread);
2957 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002958 }
2959 }
2960 }
2961 return volumeInterface;
2962}
2963
2964Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2965{
2966 Vector <VolumeInterface *> volumeInterfaces;
2967 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002968 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002969 }
2970 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2971 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002972 MmapPlaybackThread *mmapPlaybackThread =
2973 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2974 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002975 }
2976 }
2977 return volumeInterfaces;
2978}
2979
Glenn Kasteneeecb982016-02-26 10:44:04 -08002980audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981{
Glenn Kasten9d003132016-04-06 14:38:09 -07002982 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002983 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002984 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2985 for (int retry = 0; retry < maxRetries; retry++) {
2986 // The cast allows wraparound from max positive to min negative instead of abort
2987 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2988 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2989 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2990 // allow wrap by skipping 0 and -1 for session ids
2991 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2992 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2993 return (audio_unique_id_t) (base | use);
2994 }
2995 }
2996 // We have no way of recovering from wraparound
2997 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2998 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999}
3000
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003001AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003002{
3003 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3004 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003005 if(thread->isDuplicating()) {
3006 continue;
3007 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003008 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003009 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003010 return thread;
3011 }
3012 }
3013 return NULL;
3014}
3015
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003016audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003017{
3018 PlaybackThread *thread = primaryPlaybackThread_l();
3019
3020 if (thread == NULL) {
3021 return 0;
3022 }
3023
Eric Laurentf1c04f92012-08-28 14:26:53 -07003024 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003025}
3026
Glenn Kastena7335632016-06-09 17:09:53 -07003027AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3028{
3029 size_t minFrameCount = 0;
3030 PlaybackThread *minThread = NULL;
3031 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3032 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3033 if (!thread->isDuplicating()) {
3034 size_t frameCount = thread->frameCountHAL();
3035 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3036 (frameCount == minFrameCount && thread->hasFastMixer() &&
3037 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3038 minFrameCount = frameCount;
3039 minThread = thread;
3040 }
3041 }
3042 }
3043 return minThread;
3044}
3045
Eric Laurenta011e352012-03-29 15:51:43 -07003046sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003047 audio_session_t triggerSession,
3048 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003049 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003050 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003051{
3052 Mutex::Autolock _l(mLock);
3053
3054 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3055 status_t playStatus = NAME_NOT_FOUND;
3056 status_t recStatus = NAME_NOT_FOUND;
3057 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3058 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3059 if (playStatus == NO_ERROR) {
3060 return event;
3061 }
3062 }
3063 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3064 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3065 if (recStatus == NO_ERROR) {
3066 return event;
3067 }
3068 }
3069 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3070 mPendingSyncEvents.add(event);
3071 } else {
3072 ALOGV("createSyncEvent() invalid event %d", event->type());
3073 event.clear();
3074 }
3075 return event;
3076}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003077
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078// ----------------------------------------------------------------------------
3079// Effect management
3080// ----------------------------------------------------------------------------
3081
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003082sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3083 return mEffectsFactoryHal;
3084}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085
Glenn Kastenf587ba52012-01-26 16:25:10 -08003086status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087{
3088 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003089 if (mEffectsFactoryHal.get()) {
3090 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3091 } else {
3092 return -ENODEV;
3093 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094}
3095
Glenn Kastenf587ba52012-01-26 16:25:10 -08003096status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097{
3098 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003099 if (mEffectsFactoryHal.get()) {
3100 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3101 } else {
3102 return -ENODEV;
3103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104}
3105
Glenn Kasten5e92a782012-01-30 07:40:52 -08003106status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003107 const effect_uuid_t *pTypeUuid,
3108 uint32_t preferredTypeFlag,
3109 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003110{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003111 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3112 return BAD_VALUE;
3113 }
3114
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003116
3117 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003118 return -ENODEV;
3119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003121 status_t status = NO_ERROR;
3122 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3123 // If uuid is specified, request effect descriptor from that.
3124 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3125 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3126 // If uuid is not specified, look for an available implementation
3127 // of the required type instead.
3128
3129 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3130 effect_descriptor_t desc;
3131 desc.flags = 0; // prevent compiler warning
3132
3133 uint32_t numEffects = 0;
3134 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3135 if (status < 0) {
3136 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3137 return status;
3138 }
3139
3140 bool found = false;
3141 for (uint32_t i = 0; i < numEffects; i++) {
3142 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3143 if (status < 0) {
3144 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3145 continue;
3146 }
3147 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3148 // If matching type found save effect descriptor.
3149 found = true;
3150 *descriptor = desc;
3151
3152 // If there's no preferred flag or this descriptor matches the preferred
3153 // flag, success! If this descriptor doesn't match the preferred
3154 // flag, continue enumeration in case a better matching version of this
3155 // effect type is available. Note that this means if no effect with a
3156 // correct flag is found, the descriptor returned will correspond to the
3157 // last effect that at least had a matching type uuid (if any).
3158 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3159 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3160 break;
3161 }
3162 }
3163 }
3164
3165 if (!found) {
3166 status = NAME_NOT_FOUND;
3167 ALOGW("getEffectDescriptor(): Effect not found by type.");
3168 }
3169 } else {
3170 status = BAD_VALUE;
3171 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3172 }
3173 return status;
3174}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003176sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 effect_descriptor_t *pDesc,
3178 const sp<IEffectClient>& effectClient,
3179 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003180 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003181 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003182 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003183 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 status_t *status,
3185 int *id,
3186 int *enabled)
3187{
3188 status_t lStatus = NO_ERROR;
3189 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191
Eric Laurentb6436272016-12-07 19:24:50 -08003192 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003193 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003194 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3195 ALOGW_IF(pid != -1 && pid != callingPid,
3196 "%s uid %d pid %d tried to pass itself off as pid %d",
3197 __func__, callingUid, callingPid, pid);
3198 pid = callingPid;
3199 }
3200
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003201 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3202 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203
3204 if (pDesc == NULL) {
3205 lStatus = BAD_VALUE;
3206 goto Exit;
3207 }
3208
Eric Laurent84e9a102010-09-23 16:10:16 -07003209 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003210 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003211 lStatus = PERMISSION_DENIED;
3212 goto Exit;
3213 }
3214
Dima Zavinfce7a472011-04-19 22:30:36 -07003215 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003216 // that can only be created by audio policy manager
3217 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003218 lStatus = PERMISSION_DENIED;
3219 goto Exit;
3220 }
3221
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003222 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003223 lStatus = NO_INIT;
3224 goto Exit;
3225 }
3226
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003228 // Get the full effect descriptor from the uuid/type.
3229 // If the session is the output mix, prefer an auxiliary effect,
3230 // otherwise no preference.
3231 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3232 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3233 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3234 if (lStatus < 0) {
3235 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3236 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 }
3238
3239 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003240 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3242 lStatus = INVALID_OPERATION;
3243 goto Exit;
3244 }
3245
Eric Laurent59255e42011-07-27 19:49:51 -07003246 // check recording permission for visualizer
3247 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003248 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003249 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003250 lStatus = PERMISSION_DENIED;
3251 goto Exit;
3252 }
3253
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003255 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003256 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003257 // if the output returned by getOutputForEffect() is removed before we lock the
3258 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3259 // and we will exit safely
3260 io = AudioSystem::getOutputForEffect(&desc);
3261 ALOGV("createEffect got output %d", io);
3262 }
3263
3264 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265
3266 // If output is not specified try to find a matching audio session ID in one of the
3267 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003268 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3269 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003270 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003271 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003272 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3273 // output must be specified by AudioPolicyManager when using session
3274 // AUDIO_SESSION_OUTPUT_STAGE
3275 lStatus = BAD_VALUE;
3276 goto Exit;
3277 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003278 // look for the thread where the specified audio session is present
3279 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Weiyin Jiang9aeb1772018-04-27 00:39:29 +08003280 uint32_t sessionType = mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3281 if (sessionType != 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003282 io = mPlaybackThreads.keyAt(i);
Weiyin Jiang9aeb1772018-04-27 00:39:29 +08003283 // thread with same effect session is preferable
3284 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3285 break;
3286 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003289 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003290 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3291 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3292 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003293 break;
3294 }
3295 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003296 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003297 if (io == AUDIO_IO_HANDLE_NONE) {
3298 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3299 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3300 io = mMmapThreads.keyAt(i);
3301 break;
3302 }
3303 }
3304 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003305 // If no output thread contains the requested session ID, default to
3306 // first output. The effect chain will be moved to the correct output
3307 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003308 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003309 io = mPlaybackThreads.keyAt(0);
3310 }
Steve Block3856b092011-10-20 11:56:00 +01003311 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003312 }
3313 ThreadBase *thread = checkRecordThread_l(io);
3314 if (thread == NULL) {
3315 thread = checkPlaybackThread_l(io);
3316 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003317 thread = checkMmapThread_l(io);
3318 if (thread == NULL) {
3319 ALOGE("createEffect() unknown output thread");
3320 lStatus = BAD_VALUE;
3321 goto Exit;
3322 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003323 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003324 } else {
3325 // Check if one effect chain was awaiting for an effect to be created on this
3326 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003327 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003328 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003329 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003330 thread->addEffectChain_l(chain);
3331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003333
Eric Laurent021cf962014-05-13 10:18:14 -07003334 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003336 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003337 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003338 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003339 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003340 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003341 // remove local strong reference to Client with mClientLock held
3342 Mutex::Autolock _cl(mClientLock);
3343 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003344 } else {
3345 // handle must be valid here, but check again to be safe.
3346 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003347 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 }
3349
haobo101735295ff7b0d2017-03-17 17:44:03 +08003350 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3351 // handle must be cleared outside lock.
3352 handle.clear();
3353 }
3354
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003356 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 return handle;
3358}
3359
Glenn Kastend848eb42016-03-08 13:42:11 -08003360status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003361 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003362{
Steve Block3856b092011-10-20 11:56:00 +01003363 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003364 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003365 Mutex::Autolock _l(mLock);
3366 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003367 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003368 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 }
Eric Laurentde070132010-07-13 04:45:46 -07003370 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3371 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003372 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003373 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 }
Eric Laurentde070132010-07-13 04:45:46 -07003375 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3376 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003377 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003378 return BAD_VALUE;
3379 }
3380
3381 Mutex::Autolock _dl(dstThread->mLock);
3382 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003383 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384}
3385
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003386// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003387status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003388 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003389 AudioFlinger::PlaybackThread *dstThread,
3390 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003391{
Steve Block3856b092011-10-20 11:56:00 +01003392 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003393 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003394
Eric Laurent59255e42011-07-27 19:49:51 -07003395 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003396 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003397 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003398 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003399 return INVALID_OPERATION;
3400 }
3401
Eric Laurent4c415062016-06-17 16:14:16 -07003402 // Check whether the destination thread and all effects in the chain are compatible
3403 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003404 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003405 " destination thread %p is not compatible with effects in the chain",
3406 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003407 return INVALID_OPERATION;
3408 }
3409
Eric Laurent39e94f82010-07-28 01:32:47 -07003410 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003411 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003412 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003413 // removed.
3414 srcThread->removeEffectChain_l(chain);
3415
3416 // transfer all effects one by one so that new effect chain is created on new thread with
3417 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003418 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003419 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003420 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003421 Vector< sp<EffectModule> > removed;
3422 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003423 while (effect != 0) {
3424 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003425 removed.add(effect);
3426 status = dstThread->addEffect_l(effect);
3427 if (status != NO_ERROR) {
3428 break;
3429 }
Eric Laurentec35a142011-10-05 17:42:25 -07003430 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3431 if (effect->state() == EffectModule::ACTIVE ||
3432 effect->state() == EffectModule::STOPPING) {
3433 effect->start();
3434 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003435 // if the move request is not received from audio policy manager, the effect must be
3436 // re-registered with the new strategy and output
3437 if (dstChain == 0) {
3438 dstChain = effect->chain().promote();
3439 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003440 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003441 status = NO_INIT;
3442 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003443 }
3444 strategy = dstChain->strategy();
3445 }
3446 if (reRegister) {
3447 AudioSystem::unregisterEffect(effect->id());
3448 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003449 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003450 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003451 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003452 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003453 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003454 }
Eric Laurentde070132010-07-13 04:45:46 -07003455 effect = chain->getEffectFromId_l(0);
3456 }
3457
Eric Laurent5baf2af2013-09-12 17:37:00 -07003458 if (status != NO_ERROR) {
3459 for (size_t i = 0; i < removed.size(); i++) {
3460 srcThread->addEffect_l(removed[i]);
3461 if (dstChain != 0 && reRegister) {
3462 AudioSystem::unregisterEffect(removed[i]->id());
3463 AudioSystem::registerEffect(&removed[i]->desc(),
3464 srcThread->id(),
3465 strategy,
3466 sessionId,
3467 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003468 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003469 }
3470 }
3471 }
3472
3473 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474}
3475
Eric Laurent5baf2af2013-09-12 17:37:00 -07003476bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003477{
3478 if (mGlobalEffectEnableTime != 0 &&
3479 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3480 return true;
3481 }
3482
3483 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3484 sp<EffectChain> ec =
3485 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003486 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003487 return true;
3488 }
3489 }
3490 return false;
3491}
3492
Eric Laurent5baf2af2013-09-12 17:37:00 -07003493void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003494{
3495 Mutex::Autolock _l(mLock);
3496
3497 mGlobalEffectEnableTime = systemTime();
3498
3499 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3500 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3501 if (t->mType == ThreadBase::OFFLOAD) {
3502 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3503 }
3504 }
3505
3506}
3507
Eric Laurentaaa44472014-09-12 17:41:50 -07003508status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3509{
Eric Laurentd8365c52017-07-16 15:27:05 -07003510 // clear possible suspended state before parking the chain so that it starts in default state
3511 // when attached to a new record thread
3512 chain->setEffectSuspended_l(FX_IID_AEC, false);
3513 chain->setEffectSuspended_l(FX_IID_NS, false);
3514
Glenn Kastend848eb42016-03-08 13:42:11 -08003515 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003516 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003517 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003518 if (index >= 0) {
3519 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3520 return ALREADY_EXISTS;
3521 }
3522 mOrphanEffectChains.add(session, chain);
3523 return NO_ERROR;
3524}
3525
3526sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3527{
3528 sp<EffectChain> chain;
3529 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003530 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003531 if (index >= 0) {
3532 chain = mOrphanEffectChains.valueAt(index);
3533 mOrphanEffectChains.removeItemsAt(index);
3534 }
3535 return chain;
3536}
3537
3538bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3539{
3540 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003541 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003542 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003543 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003544 if (index >= 0) {
3545 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003546 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003547 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003548 mOrphanEffectChains.removeItemsAt(index);
3549 }
3550 return true;
3551 }
3552 return false;
3553}
3554
3555
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556// ----------------------------------------------------------------------------
3557
3558status_t AudioFlinger::onTransact(
3559 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3560{
3561 return BnAudioFlinger::onTransact(code, data, reply, flags);
3562}
3563
Glenn Kasten63238ef2015-03-02 15:50:29 -08003564} // namespace android