blob: 298d455f7dd52c7ec28761ef983823f4b5037a2a [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>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070042#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
Dima Zavinfce7a472011-04-19 22:30:36 -070044#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.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>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070067#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.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
Mathias Agopian65ab4712010-07-14 17:59:35 -070074// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070075
John Grossman1c345192012-03-27 14:00:17 -070076// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
Eric Laurentde070132010-07-13 04:45:46 -070088
Mathias Agopian65ab4712010-07-14 17:59:35 -070089namespace android {
90
Glenn Kastenec1d6b52011-12-12 09:04:45 -080091static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
92static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070093static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070094static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten58912562012-04-03 10:45:00 -070096
John Grossman4ff14ba2012-02-08 16:37:41 -080097nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080098
Eric Laurent81784c32012-11-19 14:55:58 -080099uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700100
Eric Laurentfc235202016-12-20 18:48:17 -0800101
Glenn Kasten46909e72013-02-26 09:20:22 -0800102#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800103bool AudioFlinger::mTeeSinkInputEnabled = false;
104bool AudioFlinger::mTeeSinkOutputEnabled = false;
105bool AudioFlinger::mTeeSinkTrackEnabled = false;
106
107size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
108size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
109size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800110#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800111
Eric Laurent813e2a72013-08-31 12:59:48 -0700112// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
113// we define a minimum time during which a global effect is considered enabled.
114static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
115
Eric Laurentfc235202016-12-20 18:48:17 -0800116Mutex gLock;
117wp<AudioFlinger> gAudioFlinger;
118
Mathias Agopian65ab4712010-07-14 17:59:35 -0700119// ----------------------------------------------------------------------------
120
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700121std::string formatToString(audio_format_t format) {
122 std::string result;
123 FormatConverter::toString(format, result);
124 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800125}
126
Mathias Agopian65ab4712010-07-14 17:59:35 -0700127// ----------------------------------------------------------------------------
128
129AudioFlinger::AudioFlinger()
130 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800131 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800132 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700133 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800134 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800135 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700136 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800137 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700138 mBtNrecIsOff(false),
139 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700140 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700141 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700142 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700143{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700144 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
145 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
146 // zero ID has a special meaning, so unavailable
147 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
148 }
149
Glenn Kasten949a9262013-04-16 12:35:20 -0700150 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800151 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800152 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800153 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
154 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800155 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700156
Wei Jia3f273d12015-11-24 09:06:49 -0800157 // reset battery stats.
158 // if the audio service has crashed, battery stats could be left
159 // in bad state, reset the state upon service start.
160 BatteryNotifier::getInstance().noteResetAudio();
161
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700162 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700163 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
164
Glenn Kasten46909e72013-02-26 09:20:22 -0800165#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800166 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800167 (void) property_get("ro.debuggable", value, "0");
168 int debuggable = atoi(value);
169 int teeEnabled = 0;
170 if (debuggable) {
171 (void) property_get("af.tee", value, "0");
172 teeEnabled = atoi(value);
173 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800174 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700175 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800176 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700177 }
178 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800179 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700180 }
181 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700183 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800184#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700185}
186
187void AudioFlinger::onFirstRef()
188{
Eric Laurent93575202011-01-18 18:39:02 -0800189 Mutex::Autolock _l(mLock);
190
Dima Zavin799a70e2011-04-18 16:57:27 -0700191 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800192 char val_str[PROPERTY_VALUE_MAX] = { 0 };
193 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
194 uint32_t int_val;
195 if (1 == sscanf(val_str, "%u", &int_val)) {
196 mStandbyTimeInNsecs = milliseconds(int_val);
197 ALOGI("Using %u mSec as standby time.", int_val);
198 } else {
199 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
200 ALOGI("Using default %u mSec as standby time.",
201 (uint32_t)(mStandbyTimeInNsecs / 1000000));
202 }
203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700204
Eric Laurent1c333e22014-05-20 10:48:17 -0700205 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700206
Eric Laurenta4c5a552012-03-29 10:12:40 -0700207 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800208
209 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210}
211
212AudioFlinger::~AudioFlinger()
213{
214 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700215 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700216 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217 }
218 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700219 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700220 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700222
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800223 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
224 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700225 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700227
228 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800229 if (mLogMemoryDealer != 0) {
230 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
231 if (binder != 0) {
232 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
233 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
234 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
235 mUnregisteredWriters.pop();
236 mediaLogService->unregisterWriter(iMemory);
237 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700238 }
239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240}
241
Eric Laurentfc235202016-12-20 18:48:17 -0800242//static
243status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
244 const audio_attributes_t *attr,
245 audio_config_base_t *config,
246 const MmapStreamInterface::Client& client,
247 audio_port_handle_t *deviceId,
248 const sp<MmapStreamCallback>& callback,
249 sp<MmapStreamInterface>& interface)
250{
251 sp<AudioFlinger> af;
252 {
253 Mutex::Autolock _l(gLock);
254 af = gAudioFlinger.promote();
255 }
256 status_t ret = NO_INIT;
257 if (af != 0) {
258 ret = af->openMmapStream(
259 direction, attr, config, client, deviceId, callback, interface);
260 }
261 return ret;
262}
263
264status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction __unused,
265 const audio_attributes_t *attr __unused,
266 audio_config_base_t *config __unused,
267 const MmapStreamInterface::Client& client __unused,
268 audio_port_handle_t *deviceId __unused,
269 const sp<MmapStreamCallback>& callback __unused,
270 sp<MmapStreamInterface>& interface __unused)
271{
272 status_t ret = initCheck();
273 if (ret != NO_ERROR) {
274 return ret;
275 }
276
277 return ret;
278}
279
Eric Laurenta4c5a552012-03-29 10:12:40 -0700280static const char * const audio_interfaces[] = {
281 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
282 AUDIO_HARDWARE_MODULE_ID_A2DP,
283 AUDIO_HARDWARE_MODULE_ID_USB,
284};
285#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
286
Phil Burk062e67a2015-02-11 13:40:50 -0800287AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700288 audio_module_handle_t module,
289 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700290{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700291 // if module is 0, the request comes from an old policy manager and we should load
292 // well known modules
293 if (module == 0) {
294 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
295 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
296 loadHwModule_l(audio_interfaces[i]);
297 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700298 // then try to find a module supporting the requested device.
299 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
300 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700301 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
302 uint32_t supportedDevices;
303 if (dev->getSupportedDevices(&supportedDevices) == OK &&
304 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700305 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700306 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700307 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700308 } else {
309 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700310 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
311 if (audioHwDevice != NULL) {
312 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700313 }
314 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700315
Dima Zavin799a70e2011-04-18 16:57:27 -0700316 return NULL;
317}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700318
Glenn Kasten0f11b512014-01-31 16:18:54 -0800319void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700320{
321 const size_t SIZE = 256;
322 char buffer[SIZE];
323 String8 result;
324
325 result.append("Clients:\n");
326 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800327 sp<Client> client = mClients.valueAt(i).promote();
328 if (client != 0) {
329 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
330 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331 }
332 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700333
Eric Laurentd1b28d42013-09-18 18:47:13 -0700334 result.append("Notification Clients:\n");
335 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
336 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
337 result.append(buffer);
338 }
339
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700340 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800341 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700342 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
343 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800344 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700345 result.append(buffer);
346 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348}
349
350
Glenn Kasten0f11b512014-01-31 16:18:54 -0800351void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352{
353 const size_t SIZE = 256;
354 char buffer[SIZE];
355 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800356 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700357
John Grossman4ff14ba2012-02-08 16:37:41 -0800358 snprintf(buffer, SIZE, "Hardware status: %d\n"
359 "Standby Time mSec: %u\n",
360 hardwareStatus,
361 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362 result.append(buffer);
363 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364}
365
Glenn Kasten0f11b512014-01-31 16:18:54 -0800366void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367{
368 const size_t SIZE = 256;
369 char buffer[SIZE];
370 String8 result;
371 snprintf(buffer, SIZE, "Permission Denial: "
372 "can't dump AudioFlinger from pid=%d, uid=%d\n",
373 IPCThreadState::self()->getCallingPid(),
374 IPCThreadState::self()->getCallingUid());
375 result.append(buffer);
376 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377}
378
Eric Laurent81784c32012-11-19 14:55:58 -0800379bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380{
381 bool locked = false;
382 for (int i = 0; i < kDumpLockRetries; ++i) {
383 if (mutex.tryLock() == NO_ERROR) {
384 locked = true;
385 break;
386 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800387 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388 }
389 return locked;
390}
391
392status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
393{
Glenn Kasten44deb052012-02-05 18:09:08 -0800394 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395 dumpPermissionDenial(fd, args);
396 } else {
397 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800398 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399 if (!hardwareLocked) {
400 String8 result(kHardwareLockedString);
401 write(fd, result.string(), result.size());
402 } else {
403 mHardwareLock.unlock();
404 }
405
Eric Laurent81784c32012-11-19 14:55:58 -0800406 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407
408 // failed to lock - AudioFlinger is probably deadlocked
409 if (!locked) {
410 String8 result(kDeadlockedString);
411 write(fd, result.string(), result.size());
412 }
413
Eric Laurent021cf962014-05-13 10:18:14 -0700414 bool clientLocked = dumpTryLock(mClientLock);
415 if (!clientLocked) {
416 String8 result(kClientLockedString);
417 write(fd, result.string(), result.size());
418 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700419
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700420 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700421 mEffectsFactoryHal->dumpEffects(fd);
422 } else {
423 String8 result(kNoEffectsFactory);
424 write(fd, result.string(), result.size());
425 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700426
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700428 if (clientLocked) {
429 mClientLock.unlock();
430 }
431
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432 dumpInternals(fd, args);
433
434 // dump playback threads
435 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
436 mPlaybackThreads.valueAt(i)->dump(fd, args);
437 }
438
439 // dump record threads
440 for (size_t i = 0; i < mRecordThreads.size(); i++) {
441 mRecordThreads.valueAt(i)->dump(fd, args);
442 }
443
Eric Laurentaaa44472014-09-12 17:41:50 -0700444 // dump orphan effect chains
445 if (mOrphanEffectChains.size() != 0) {
446 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
447 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
448 mOrphanEffectChains.valueAt(i)->dump(fd, args);
449 }
450 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700451 // dump all hardware devs
452 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700453 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
454 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700456
Glenn Kasten46909e72013-02-26 09:20:22 -0800457#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700458 // dump the serially shared record tee sink
459 if (mRecordTeeSource != 0) {
460 dumpTee(fd, mRecordTeeSource);
461 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800462#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700463
rago3bd1c872016-09-26 12:58:14 -0700464 BUFLOG_RESET;
465
Glenn Kastend65d73c2012-06-22 17:21:07 -0700466 if (locked) {
467 mLock.unlock();
468 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800469
470 // append a copy of media.log here by forwarding fd to it, but don't attempt
471 // to lookup the service if it's not running, as it will block for a second
472 if (mLogMemoryDealer != 0) {
473 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
474 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700475 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800476 Vector<String16> args;
477 binder->dump(fd, args);
478 }
479 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700480
481 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700482 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700483 bool unreachableMemory = false;
484 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700485 if (arg == String16("-m")) {
486 dumpMem = true;
487 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700488 unreachableMemory = true;
489 }
490 }
491
Andy Hung07b745e2016-05-23 16:21:07 -0700492 if (dumpMem) {
493 dprintf(fd, "\nDumping memory:\n");
494 std::string s = dumpMemoryAddresses(100 /* limit */);
495 write(fd, s.c_str(), s.size());
496 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700497 if (unreachableMemory) {
498 dprintf(fd, "\nDumping unreachable memory:\n");
499 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700500 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700501 write(fd, s.c_str(), s.size());
502 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503 }
504 return NO_ERROR;
505}
506
Eric Laurent021cf962014-05-13 10:18:14 -0700507sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800508{
Eric Laurent021cf962014-05-13 10:18:14 -0700509 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800510 // If pid is already in the mClients wp<> map, then use that entry
511 // (for which promote() is always != 0), otherwise create a new entry and Client.
512 sp<Client> client = mClients.valueFor(pid).promote();
513 if (client == 0) {
514 client = new Client(this, pid);
515 mClients.add(pid, client);
516 }
517
518 return client;
519}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520
Glenn Kasten9e58b552013-01-18 15:09:48 -0800521sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
522{
Glenn Kasten481fb672013-09-30 14:39:28 -0700523 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800524 if (mLogMemoryDealer == 0) {
525 return new NBLog::Writer();
526 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800527 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700528 // Similarly if we can't contact the media.log service, also return a dummy writer
529 if (binder == 0) {
530 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800531 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700532 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
533 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
534 // If allocation fails, consult the vector of previously unregistered writers
535 // and garbage-collect one or more them until an allocation succeeds
536 if (shared == 0) {
537 Mutex::Autolock _l(mUnregisteredWritersLock);
538 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
539 {
540 // Pick the oldest stale writer to garbage-collect
541 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
542 mUnregisteredWriters.removeAt(0);
543 mediaLogService->unregisterWriter(iMemory);
544 // Now the media.log remote reference to IMemory is gone. When our last local
545 // reference to IMemory also drops to zero at end of this block,
546 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
547 }
548 // Re-attempt the allocation
549 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
550 if (shared != 0) {
551 goto success;
552 }
553 }
554 // Even after garbage-collecting all old writers, there is still not enough memory,
555 // so return a dummy writer
556 return new NBLog::Writer();
557 }
558success:
559 mediaLogService->registerWriter(shared, size, name);
560 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800561}
562
563void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
564{
Glenn Kasten685ef092013-02-04 08:15:34 -0800565 if (writer == 0) {
566 return;
567 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800568 sp<IMemory> iMemory(writer->getIMemory());
569 if (iMemory == 0) {
570 return;
571 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700572 // Rather than removing the writer immediately, append it to a queue of old writers to
573 // be garbage-collected later. This allows us to continue to view old logs for a while.
574 Mutex::Autolock _l(mUnregisteredWritersLock);
575 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800576}
577
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578// IAudioFlinger interface
579
580
581sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800582 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800584 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700585 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800586 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700587 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800589 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700590 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800591 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800592 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800593 int clientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800594 status_t *status,
595 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596{
597 sp<PlaybackThread::Track> track;
598 sp<TrackHandle> trackHandle;
599 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800601 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700603 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
604 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
605 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
606 ALOGW_IF(pid != -1 && pid != callingPid,
607 "%s uid %d pid %d tried to pass itself off as pid %d",
608 __func__, callingUid, callingPid, pid);
609 pid = callingPid;
610 }
611
Glenn Kasten263709e2012-01-06 08:40:01 -0800612 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
613 // but if someone uses binder directly they could bypass that and cause us to crash
614 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000615 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616 lStatus = BAD_VALUE;
617 goto Exit;
618 }
619
Glenn Kasten53b5d092014-02-05 10:00:23 -0800620 // further sample rate checks are performed by createTrack_l() depending on the thread type
621 if (sampleRate == 0) {
622 ALOGE("createTrack() invalid sample rate %u", sampleRate);
623 lStatus = BAD_VALUE;
624 goto Exit;
625 }
626
627 // further channel mask checks are performed by createTrack_l() depending on the thread type
628 if (!audio_is_output_channel(channelMask)) {
629 ALOGE("createTrack() invalid channel mask %#x", channelMask);
630 lStatus = BAD_VALUE;
631 goto Exit;
632 }
633
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700634 // further format checks are performed by createTrack_l() depending on the thread type
635 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800636 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700637 lStatus = BAD_VALUE;
638 goto Exit;
639 }
640
Glenn Kasten663c2242013-09-24 11:52:37 -0700641 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
642 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
643 lStatus = BAD_VALUE;
644 goto Exit;
645 }
646
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647 {
648 Mutex::Autolock _l(mLock);
649 PlaybackThread *thread = checkPlaybackThread_l(output);
650 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800651 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652 lStatus = BAD_VALUE;
653 goto Exit;
654 }
655
Eric Laurent021cf962014-05-13 10:18:14 -0700656 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657
Glenn Kastene848bd92014-03-13 15:00:32 -0700658 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700659 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800660 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
661 ALOGE("createTrack() invalid session ID %d", *sessionId);
662 lStatus = BAD_VALUE;
663 goto Exit;
664 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700665 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700666 // check if an effect chain with the same session ID is present on another
667 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700668 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700669 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
670 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700671 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700672 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700673 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700674 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700675 }
Eric Laurentde070132010-07-13 04:45:46 -0700676 }
677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700679 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800680 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 if (sessionId != NULL) {
682 *sessionId = lSessionId;
683 }
684 }
Steve Block3856b092011-10-20 11:56:00 +0100685 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686
687 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800688 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid,
689 clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800690 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700691 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700692
693 // move effect chain to this output thread if an effect on same session was waiting
694 // for a track to be created
695 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700696 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700697 Mutex::Autolock _dl(thread->mLock);
698 Mutex::Autolock _sl(effectThread->mLock);
699 moveEffectChain_l(lSessionId, effectThread, thread, true);
700 }
Eric Laurenta011e352012-03-29 15:51:43 -0700701
702 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700703 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700704 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
705 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700706 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700707 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700708 } else {
709 mPendingSyncEvents[i]->cancel();
710 }
Eric Laurenta011e352012-03-29 15:51:43 -0700711 mPendingSyncEvents.removeAt(i);
712 i--;
713 }
714 }
715 }
Glenn Kastene198c362013-08-13 09:13:36 -0700716
Glenn Kastend848eb42016-03-08 13:42:11 -0800717 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 }
Glenn Kastene198c362013-08-13 09:13:36 -0700719
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700720 if (lStatus != NO_ERROR) {
721 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700722 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700723 // Don't hold mClientLock when releasing the reference on the track as the
724 // destructor will acquire it.
725 {
726 Mutex::Autolock _cl(mClientLock);
727 client.clear();
728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700730 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 }
732
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700733 // return handle to client
734 trackHandle = new TrackHandle(track);
735
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700737 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738 return trackHandle;
739}
740
Glenn Kasten2c073da2016-02-26 09:14:08 -0800741uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742{
743 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800744 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700745 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800746 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 return 0;
748 }
749 return thread->sampleRate();
750}
751
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800752audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753{
754 Mutex::Autolock _l(mLock);
755 PlaybackThread *thread = checkPlaybackThread_l(output);
756 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000757 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800758 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700759 }
760 return thread->format();
761}
762
Glenn Kasten2c073da2016-02-26 09:14:08 -0800763size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764{
765 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800766 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800768 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769 return 0;
770 }
Glenn Kasten58912562012-04-03 10:45:00 -0700771 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
772 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773 return thread->frameCount();
774}
775
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700776size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
777{
778 Mutex::Autolock _l(mLock);
779 ThreadBase *thread = checkThread_l(ioHandle);
780 if (thread == NULL) {
781 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
782 return 0;
783 }
784 return thread->frameCountHAL();
785}
786
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800787uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788{
789 Mutex::Autolock _l(mLock);
790 PlaybackThread *thread = checkPlaybackThread_l(output);
791 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800792 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 return 0;
794 }
795 return thread->latency();
796}
797
798status_t AudioFlinger::setMasterVolume(float value)
799{
Eric Laurenta1884f92011-08-23 08:25:03 -0700800 status_t ret = initCheck();
801 if (ret != NO_ERROR) {
802 return ret;
803 }
804
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 // check calling permissions
806 if (!settingsAllowed()) {
807 return PERMISSION_DENIED;
808 }
809
Eric Laurenta4c5a552012-03-29 10:12:40 -0700810 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700811 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700812
John Grossmanee578c02012-07-23 17:05:46 -0700813 // Set master volume in the HALs which support it.
814 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
815 AutoMutex lock(mHardwareLock);
816 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800817
John Grossmanee578c02012-07-23 17:05:46 -0700818 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
819 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700820 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800821 }
John Grossmanee578c02012-07-23 17:05:46 -0700822 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824
John Grossmanee578c02012-07-23 17:05:46 -0700825 // Now set the master volume in each playback thread. Playback threads
826 // assigned to HALs which do not have master volume support will apply
827 // master volume during the mix operation. Threads with HALs which do
828 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700829 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
830 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
831 continue;
832 }
John Grossmanee578c02012-07-23 17:05:46 -0700833 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835
836 return NO_ERROR;
837}
838
Glenn Kastenf78aee72012-01-04 11:00:47 -0800839status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
Eric Laurenta1884f92011-08-23 08:25:03 -0700841 status_t ret = initCheck();
842 if (ret != NO_ERROR) {
843 return ret;
844 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845
846 // check calling permissions
847 if (!settingsAllowed()) {
848 return PERMISSION_DENIED;
849 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800850 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000851 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 return BAD_VALUE;
853 }
854
855 { // scope for the lock
856 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700857 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700859 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700860 mHardwareStatus = AUDIO_HW_IDLE;
861 }
862
863 if (NO_ERROR == ret) {
864 Mutex::Autolock _l(mLock);
865 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800866 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700867 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 }
869
870 return ret;
871}
872
873status_t AudioFlinger::setMicMute(bool state)
874{
Eric Laurenta1884f92011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700887 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700888 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
889 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700890 if (result != NO_ERROR) {
891 ret = result;
892 }
893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894 mHardwareStatus = AUDIO_HW_IDLE;
895 return ret;
896}
897
898bool AudioFlinger::getMicMute() const
899{
Eric Laurenta1884f92011-08-23 08:25:03 -0700900 status_t ret = initCheck();
901 if (ret != NO_ERROR) {
902 return false;
903 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800904 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700905 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800906 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800908 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700909 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
910 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800911 if (result == NO_ERROR) {
912 mute = mute && state;
913 }
914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800916
917 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918}
919
920status_t AudioFlinger::setMasterMute(bool muted)
921{
John Grossmand8f178d2012-07-20 14:51:35 -0700922 status_t ret = initCheck();
923 if (ret != NO_ERROR) {
924 return ret;
925 }
926
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 // check calling permissions
928 if (!settingsAllowed()) {
929 return PERMISSION_DENIED;
930 }
931
John Grossmanee578c02012-07-23 17:05:46 -0700932 Mutex::Autolock _l(mLock);
933 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700934
John Grossmanee578c02012-07-23 17:05:46 -0700935 // Set master mute in the HALs which support it.
936 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
937 AutoMutex lock(mHardwareLock);
938 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700939
John Grossmanee578c02012-07-23 17:05:46 -0700940 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
941 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700942 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700943 }
John Grossmanee578c02012-07-23 17:05:46 -0700944 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700945 }
946
John Grossmanee578c02012-07-23 17:05:46 -0700947 // Now set the master mute in each playback thread. Playback threads
948 // assigned to HALs which do not have master mute support will apply master
949 // mute during the mix operation. Threads with HALs which do support master
950 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700951 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
952 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
953 continue;
954 }
John Grossmanee578c02012-07-23 17:05:46 -0700955 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700956 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700957
958 return NO_ERROR;
959}
960
961float AudioFlinger::masterVolume() const
962{
Glenn Kasten98067102011-12-13 11:47:54 -0800963 Mutex::Autolock _l(mLock);
964 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965}
966
967bool AudioFlinger::masterMute() const
968{
Glenn Kasten98067102011-12-13 11:47:54 -0800969 Mutex::Autolock _l(mLock);
970 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971}
972
John Grossman4ff14ba2012-02-08 16:37:41 -0800973float AudioFlinger::masterVolume_l() const
974{
John Grossman4ff14ba2012-02-08 16:37:41 -0800975 return mMasterVolume;
976}
977
John Grossmand8f178d2012-07-20 14:51:35 -0700978bool AudioFlinger::masterMute_l() const
979{
John Grossmanee578c02012-07-23 17:05:46 -0700980 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700981}
982
Eric Laurent223fd5c2014-11-11 13:43:36 -0800983status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
984{
985 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
986 ALOGW("setStreamVolume() invalid stream %d", stream);
987 return BAD_VALUE;
988 }
989 pid_t caller = IPCThreadState::self()->getCallingPid();
990 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
991 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
992 return PERMISSION_DENIED;
993 }
994
995 return NO_ERROR;
996}
997
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800998status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
999 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000{
1001 // check calling permissions
1002 if (!settingsAllowed()) {
1003 return PERMISSION_DENIED;
1004 }
1005
Eric Laurent223fd5c2014-11-11 13:43:36 -08001006 status_t status = checkStreamType(stream);
1007 if (status != NO_ERROR) {
1008 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001010 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011
1012 AutoMutex lock(mLock);
1013 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -07001014 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 thread = checkPlaybackThread_l(output);
1016 if (thread == NULL) {
1017 return BAD_VALUE;
1018 }
1019 }
1020
1021 mStreamTypes[stream].volume = value;
1022
1023 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001024 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001025 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 }
1027 } else {
1028 thread->setStreamVolume(stream, value);
1029 }
1030
1031 return NO_ERROR;
1032}
1033
Glenn Kastenfff6d712012-01-12 16:38:12 -08001034status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035{
1036 // check calling permissions
1037 if (!settingsAllowed()) {
1038 return PERMISSION_DENIED;
1039 }
1040
Eric Laurent223fd5c2014-11-11 13:43:36 -08001041 status_t status = checkStreamType(stream);
1042 if (status != NO_ERROR) {
1043 return status;
1044 }
1045 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1046
1047 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001048 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 return BAD_VALUE;
1050 }
1051
Eric Laurent93575202011-01-18 18:39:02 -08001052 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001053 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001054 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001055 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056
1057 return NO_ERROR;
1058}
1059
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001060float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001062 status_t status = checkStreamType(stream);
1063 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 return 0.0f;
1065 }
1066
1067 AutoMutex lock(mLock);
1068 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001069 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 PlaybackThread *thread = checkPlaybackThread_l(output);
1071 if (thread == NULL) {
1072 return 0.0f;
1073 }
1074 volume = thread->streamVolume(stream);
1075 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001076 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 }
1078
1079 return volume;
1080}
1081
Glenn Kastenfff6d712012-01-12 16:38:12 -08001082bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001084 status_t status = checkStreamType(stream);
1085 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 return true;
1087 }
1088
Glenn Kasten6637baa2012-01-09 09:40:36 -08001089 AutoMutex lock(mLock);
1090 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091}
1092
Eric Laurent054d9d32015-04-24 08:48:48 -07001093
1094void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1095{
1096 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1097 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1098 }
1099}
1100
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001101status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001103 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1104 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001105
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 // check calling permissions
1107 if (!settingsAllowed()) {
1108 return PERMISSION_DENIED;
1109 }
1110
Glenn Kasten142f5192014-03-25 17:44:59 -07001111 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1112 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001113 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001114 // result will remain NO_INIT if no audio device is present
1115 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001116 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001117 AutoMutex lock(mHardwareLock);
1118 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1119 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001120 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1121 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001122 // return success if at least one audio device accepts the parameters as not all
1123 // HALs are requested to support all parameters. If no audio device supports the
1124 // requested parameters, the last error is reported.
1125 if (final_result != NO_ERROR) {
1126 final_result = result;
1127 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001128 }
1129 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001130 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001131 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1132 AudioParameter param = AudioParameter(keyValuePairs);
1133 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001134 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1135 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentbee53372011-08-29 12:42:48 -07001136 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001137 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1138 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001139 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001140 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1141 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001142 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001143 // suspend effects associated with those session IDs
1144 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001145 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001146 thread->setEffectSuspended(FX_IID_AEC,
1147 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001148 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001149 thread->setEffectSuspended(FX_IID_NS,
1150 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001151 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001152 }
1153 }
Eric Laurentbee53372011-08-29 12:42:48 -07001154 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001155 }
1156 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001157 String8 screenState;
1158 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001159 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001160 if (isOff != (AudioFlinger::mScreenState & 1)) {
1161 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001162 }
1163 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001164 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 }
1166
1167 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1168 // and the thread is exited once the lock is released
1169 sp<ThreadBase> thread;
1170 {
1171 Mutex::Autolock _l(mLock);
1172 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001173 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001175 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001176 // indicate output device change to all input threads for pre processing
1177 AudioParameter param = AudioParameter(keyValuePairs);
1178 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001179 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1180 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001181 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183 }
1184 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001185 if (thread != 0) {
1186 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187 }
1188 return BAD_VALUE;
1189}
1190
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001191String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001193 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1194 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195
Eric Laurenta4c5a552012-03-29 10:12:40 -07001196 Mutex::Autolock _l(mLock);
1197
Glenn Kasten142f5192014-03-25 17:44:59 -07001198 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001199 String8 out_s8;
1200
Dima Zavin799a70e2011-04-18 16:57:27 -07001201 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001202 String8 s;
1203 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001204 {
1205 AutoMutex lock(mHardwareLock);
1206 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001207 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1208 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001209 mHardwareStatus = AUDIO_HW_IDLE;
1210 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001211 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001212 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001213 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 }
1215
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1217 if (playbackThread != NULL) {
1218 return playbackThread->getParameters(keys);
1219 }
1220 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1221 if (recordThread != NULL) {
1222 return recordThread->getParameters(keys);
1223 }
1224 return String8("");
1225}
1226
Glenn Kastendd8104c2012-07-02 12:42:44 -07001227size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1228 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229{
Eric Laurenta1884f92011-08-23 08:25:03 -07001230 status_t ret = initCheck();
1231 if (ret != NO_ERROR) {
1232 return 0;
1233 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001234 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001235 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001236 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001237 return 0;
1238 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001239
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001240 AutoMutex lock(mHardwareLock);
1241 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001242 audio_config_t config, proposed;
1243 memset(&proposed, 0, sizeof(proposed));
1244 proposed.sample_rate = sampleRate;
1245 proposed.channel_mask = channelMask;
1246 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001247
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001248 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001249 size_t frames;
1250 for (;;) {
1251 // Note: config is currently a const parameter for get_input_buffer_size()
1252 // but we use a copy from proposed in case config changes from the call.
1253 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001254 status_t result = dev->getInputBufferSize(&config, &frames);
1255 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001256 break; // hal success, config is the result
1257 }
1258 // change one parameter of the configuration each iteration to a more "common" value
1259 // to see if the device will support it.
1260 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1261 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1262 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1263 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1264 } else {
1265 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1266 "format %#x, channelMask 0x%X",
1267 sampleRate, format, channelMask);
1268 break; // retries failed, break out of loop with frames == 0.
1269 }
1270 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001271 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001272 if (frames > 0 && config.sample_rate != sampleRate) {
1273 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1274 }
1275 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276}
1277
Glenn Kasten5f972c02014-01-13 09:59:31 -08001278uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280 Mutex::Autolock _l(mLock);
1281
1282 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1283 if (recordThread != NULL) {
1284 return recordThread->getInputFramesLost();
1285 }
1286 return 0;
1287}
1288
1289status_t AudioFlinger::setVoiceVolume(float value)
1290{
Eric Laurenta1884f92011-08-23 08:25:03 -07001291 status_t ret = initCheck();
1292 if (ret != NO_ERROR) {
1293 return ret;
1294 }
1295
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 // check calling permissions
1297 if (!settingsAllowed()) {
1298 return PERMISSION_DENIED;
1299 }
1300
1301 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001302 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001303 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001304 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 mHardwareStatus = AUDIO_HW_IDLE;
1306
1307 return ret;
1308}
1309
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001310status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001311 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001312{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313 Mutex::Autolock _l(mLock);
1314
1315 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1316 if (playbackThread != NULL) {
1317 return playbackThread->getRenderPosition(halFrames, dspFrames);
1318 }
1319
1320 return BAD_VALUE;
1321}
1322
1323void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1324{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001326 if (client == 0) {
1327 return;
1328 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001329 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001330 {
1331 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001332 if (mNotificationClients.indexOfKey(pid) < 0) {
1333 sp<NotificationClient> notificationClient = new NotificationClient(this,
1334 client,
1335 pid);
1336 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337
Eric Laurent021cf962014-05-13 10:18:14 -07001338 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339
Marco Nelissen06b46062014-11-14 07:58:25 -08001340 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001341 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001342 }
1343 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001344
Eric Laurent021cf962014-05-13 10:18:14 -07001345 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001346 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001347 // the config change is always sent from playback or record threads to avoid deadlock
1348 // with AudioSystem::gLock
1349 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1350 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1351 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001352
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001353 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1354 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355 }
1356}
1357
1358void AudioFlinger::removeNotificationClient(pid_t pid)
1359{
1360 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001361 {
1362 Mutex::Autolock _cl(mClientLock);
1363 mNotificationClients.removeItem(pid);
1364 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001365
Steve Block3856b092011-10-20 11:56:00 +01001366 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001367 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001368 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001369 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001370 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001371 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001372 if (ref->mPid == pid) {
1373 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001374 mAudioSessionRefs.removeAt(i);
1375 delete ref;
1376 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001377 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001378 } else {
1379 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001380 }
1381 }
1382 if (removed) {
1383 purgeStaleEffects_l();
1384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385}
1386
Eric Laurent73e26b62015-04-27 16:55:58 -07001387void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001388 const sp<AudioIoDescriptor>& ioDesc,
1389 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390{
Eric Laurent021cf962014-05-13 10:18:14 -07001391 Mutex::Autolock _l(mClientLock);
1392 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001394 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1395 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1396 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397 }
1398}
1399
Eric Laurent021cf962014-05-13 10:18:14 -07001400// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001401void AudioFlinger::removeClient_l(pid_t pid)
1402{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001403 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001404 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405 mClients.removeItem(pid);
1406}
1407
Eric Laurent717e1282012-06-29 16:36:52 -07001408// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001409sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1410 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001411{
1412 sp<PlaybackThread> thread;
1413
1414 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1415 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1416 ALOG_ASSERT(thread == 0);
1417 thread = mPlaybackThreads.valueAt(i);
1418 }
1419 }
1420
1421 return thread;
1422}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425
1426// ----------------------------------------------------------------------------
1427
1428AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1429 : RefBase(),
1430 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001431 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301433 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1434 heapSize *= 1024;
1435 if (!heapSize) {
1436 heapSize = kClientSharedHeapSizeBytes;
1437 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1438 // invalidated tracks
1439 if (!audioFlinger->isLowRamDevice()) {
1440 heapSize *= kClientSharedHeapSizeMultiplier;
1441 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001442 }
1443 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444}
1445
Eric Laurent021cf962014-05-13 10:18:14 -07001446// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447AudioFlinger::Client::~Client()
1448{
1449 mAudioFlinger->removeClient_l(mPid);
1450}
1451
Glenn Kasten435dbe62012-01-30 10:15:48 -08001452sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453{
1454 return mMemoryDealer;
1455}
1456
1457// ----------------------------------------------------------------------------
1458
1459AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1460 const sp<IAudioFlingerClient>& client,
1461 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001462 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463{
1464}
1465
1466AudioFlinger::NotificationClient::~NotificationClient()
1467{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468}
1469
Glenn Kasten0f11b512014-01-31 16:18:54 -08001470void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471{
1472 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001473 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474}
1475
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476
1477// ----------------------------------------------------------------------------
1478
1479sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001480 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001482 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001483 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001484 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001485 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001486 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001487 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001488 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001489 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001490 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001491 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001492 sp<IMemory>& cblk,
1493 sp<IMemory>& buffers,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001494 status_t *status,
1495 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496{
1497 sp<RecordThread::RecordTrack> recordTrack;
1498 sp<RecordHandle> recordHandle;
1499 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001501 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502
Glenn Kastend776ac62014-05-07 09:16:09 -07001503 cblk.clear();
1504 buffers.clear();
1505
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001506 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001507 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1508 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001509 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001510 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1511 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001512 updatePid = true;
1513 }
1514
1515 if (updatePid) {
1516 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1517 ALOGW_IF(pid != -1 && pid != callingPid,
1518 "%s uid %d pid %d tried to pass itself off as pid %d",
1519 __func__, callingUid, callingPid, pid);
1520 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001521 }
1522
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001524 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001525 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 lStatus = PERMISSION_DENIED;
1527 goto Exit;
1528 }
1529
Glenn Kasten53b5d092014-02-05 10:00:23 -08001530 // further sample rate checks are performed by createRecordTrack_l()
1531 if (sampleRate == 0) {
1532 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536
Andy Hung6770c6f2015-04-07 13:43:36 -07001537 // we don't yet support anything other than linear PCM
1538 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001539 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001540 lStatus = BAD_VALUE;
1541 goto Exit;
1542 }
1543
Glenn Kasten53b5d092014-02-05 10:00:23 -08001544 // further channel mask checks are performed by createRecordTrack_l()
1545 if (!audio_is_input_channel(channelMask)) {
1546 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1547 lStatus = BAD_VALUE;
1548 goto Exit;
1549 }
1550
Glenn Kasten05997e22014-03-13 15:08:33 -07001551 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001553 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001555 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 lStatus = BAD_VALUE;
1557 goto Exit;
1558 }
1559
Eric Laurent021cf962014-05-13 10:18:14 -07001560 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001562 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001563 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1564 lStatus = BAD_VALUE;
1565 goto Exit;
1566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 lSessionId = *sessionId;
1568 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001569 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001570 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 if (sessionId != NULL) {
1572 *sessionId = lSessionId;
1573 }
1574 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001575 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001576
Glenn Kasten1879fff2012-07-11 15:36:59 -07001577 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001578 frameCount, lSessionId, notificationFrames,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001579 clientUid, flags, tid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001580 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001581
1582 if (lStatus == NO_ERROR) {
1583 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1584 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001585 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001586 if (chain != 0) {
1587 Mutex::Autolock _l(thread->mLock);
1588 thread->addEffectChain_l(chain);
1589 }
1590 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 }
Glenn Kastene198c362013-08-13 09:13:36 -07001592
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001593 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001594 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001595 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001596 // Don't hold mClientLock when releasing the reference on the track as the
1597 // destructor will acquire it.
1598 {
1599 Mutex::Autolock _cl(mClientLock);
1600 client.clear();
1601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 goto Exit;
1604 }
1605
Glenn Kastend776ac62014-05-07 09:16:09 -07001606 cblk = recordTrack->getCblk();
1607 buffers = recordTrack->getBuffers();
1608
Glenn Kasten2fc14732013-08-05 14:58:14 -07001609 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611
1612Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001613 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 return recordHandle;
1615}
1616
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001617
1618
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619// ----------------------------------------------------------------------------
1620
Eric Laurenta4c5a552012-03-29 10:12:40 -07001621audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1622{
Eric Laurent44622db2014-08-01 19:00:33 -07001623 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001624 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001625 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001626 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001627 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001628 }
1629 Mutex::Autolock _l(mLock);
1630 return loadHwModule_l(name);
1631}
1632
1633// loadHwModule_l() must be called with AudioFlinger::mLock held
1634audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1635{
1636 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1637 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1638 ALOGW("loadHwModule() module %s already loaded", name);
1639 return mAudioHwDevs.keyAt(i);
1640 }
1641 }
1642
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001643 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001644
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001645 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001646 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001647 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001648 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001649 }
1650
1651 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001652 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001653 mHardwareStatus = AUDIO_HW_IDLE;
1654 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001655 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001656 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001657 }
1658
John Grossmanee578c02012-07-23 17:05:46 -07001659 // Check and cache this HAL's level of support for master mute and master
1660 // volume. If this is the first HAL opened, and it supports the get
1661 // methods, use the initial values provided by the HAL as the current
1662 // master mute and volume settings.
1663
1664 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1665 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001666 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001667
1668 if (0 == mAudioHwDevs.size()) {
1669 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001670 float mv;
1671 if (OK == dev->getMasterVolume(&mv)) {
1672 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001673 }
1674
1675 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001676 bool mm;
1677 if (OK == dev->getMasterMute(&mm)) {
1678 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001679 }
1680 }
1681
Eric Laurenta4c5a552012-03-29 10:12:40 -07001682 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001683 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001684 flags = static_cast<AudioHwDevice::Flags>(flags |
1685 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1686 }
1687
1688 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001689 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001690 flags = static_cast<AudioHwDevice::Flags>(flags |
1691 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1692 }
1693
Eric Laurenta4c5a552012-03-29 10:12:40 -07001694 mHardwareStatus = AUDIO_HW_IDLE;
1695 }
1696
Glenn Kastena13cde92016-03-28 15:26:02 -07001697 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001698 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001699
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001700 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001701
1702 return handle;
1703
1704}
1705
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001706// ----------------------------------------------------------------------------
1707
Glenn Kasten3b16c762012-11-14 08:44:39 -08001708uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001709{
1710 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001711 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001712 return thread != NULL ? thread->sampleRate() : 0;
1713}
1714
Glenn Kastene33054e2012-11-14 12:54:39 -08001715size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001716{
1717 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001718 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001719 return thread != NULL ? thread->frameCountHAL() : 0;
1720}
1721
1722// ----------------------------------------------------------------------------
1723
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001724status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1725{
1726 uid_t uid = IPCThreadState::self()->getCallingUid();
1727 if (uid != AID_SYSTEM) {
1728 return PERMISSION_DENIED;
1729 }
1730 Mutex::Autolock _l(mLock);
1731 if (mIsDeviceTypeKnown) {
1732 return INVALID_OPERATION;
1733 }
1734 mIsLowRamDevice = isLowRamDevice;
1735 mIsDeviceTypeKnown = true;
1736 return NO_ERROR;
1737}
1738
Eric Laurent93c3d412014-08-01 14:48:35 -07001739audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1740{
1741 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001742
1743 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1744 if (index >= 0) {
1745 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1746 mHwAvSyncIds.valueAt(index), sessionId);
1747 return mHwAvSyncIds.valueAt(index);
1748 }
1749
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001750 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001751 if (dev == NULL) {
1752 return AUDIO_HW_SYNC_INVALID;
1753 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001754 String8 reply;
1755 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001756 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001757 param = AudioParameter(reply);
1758 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001759
1760 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001761 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001762 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1763 return AUDIO_HW_SYNC_INVALID;
1764 }
1765
1766 // allow only one session for a given HW A/V sync ID.
1767 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1768 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1769 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1770 value, mHwAvSyncIds.keyAt(i));
1771 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001772 break;
1773 }
1774 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001775
1776 mHwAvSyncIds.add(sessionId, value);
1777
1778 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1779 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1780 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001781 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001782 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001783 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001784 thread->setParameters(param.toString());
1785 break;
1786 }
1787 }
1788
1789 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1790 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001791}
1792
Eric Laurent72e3f392015-05-20 14:43:50 -07001793status_t AudioFlinger::systemReady()
1794{
1795 Mutex::Autolock _l(mLock);
1796 ALOGI("%s", __FUNCTION__);
1797 if (mSystemReady) {
1798 ALOGW("%s called twice", __FUNCTION__);
1799 return NO_ERROR;
1800 }
1801 mSystemReady = true;
1802 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1803 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1804 thread->systemReady();
1805 }
1806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1807 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1808 thread->systemReady();
1809 }
1810 return NO_ERROR;
1811}
1812
Eric Laurentfa90e842014-10-17 18:12:31 -07001813// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1814void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1815{
1816 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1817 if (index >= 0) {
1818 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1819 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1820 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001821 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001822 thread->setParameters(param.toString());
1823 }
1824}
1825
1826
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001827// ----------------------------------------------------------------------------
1828
Eric Laurent83b88082014-06-20 18:31:16 -07001829
1830sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001831 audio_io_handle_t *output,
1832 audio_config_t *config,
1833 audio_devices_t devices,
1834 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001835 audio_output_flags_t flags)
1836{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001837 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001838 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001839 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001840 }
1841
Eric Laurentcf2c0212014-07-25 16:20:43 -07001842 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001843 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1844 } else {
1845 // Audio Policy does not currently request a specific output handle.
1846 // If this is ever needed, see openInput_l() for example code.
1847 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1848 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001849 }
Eric Laurent83b88082014-06-20 18:31:16 -07001850
1851 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1852
Eric Laurent83b88082014-06-20 18:31:16 -07001853 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001854 // This if statement allows overriding the audio policy settings
1855 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1856 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1857 // Check only for Normal Mixing mode
1858 if (kEnableExtendedPrecision) {
1859 // Specify format (uncomment one below to choose)
1860 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1861 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1862 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1863 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001864 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001865 }
1866 if (kEnableExtendedChannels) {
1867 // Specify channel mask (uncomment one below to choose)
1868 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1869 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1870 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1871 }
Eric Laurent83b88082014-06-20 18:31:16 -07001872 }
1873
Phil Burk062e67a2015-02-11 13:40:50 -08001874 AudioStreamOut *outputStream = NULL;
1875 status_t status = outHwDev->openOutputStream(
1876 &outputStream,
1877 *output,
1878 devices,
1879 flags,
1880 config,
1881 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001882
1883 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001884
Phil Burk062e67a2015-02-11 13:40:50 -08001885 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001886
1887 PlaybackThread *thread;
1888 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001889 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001890 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001891 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1892 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001893 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001894 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001895 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001896 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001897 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001898 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001899 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001900 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001901 return thread;
1902 }
1903
1904 return 0;
1905}
1906
Eric Laurentcf2c0212014-07-25 16:20:43 -07001907status_t AudioFlinger::openOutput(audio_module_handle_t module,
1908 audio_io_handle_t *output,
1909 audio_config_t *config,
1910 audio_devices_t *devices,
1911 const String8& address,
1912 uint32_t *latencyMs,
1913 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914{
Phil Burk062e67a2015-02-11 13:40:50 -08001915 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001916 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001917 (devices != NULL) ? *devices : 0,
1918 config->sample_rate,
1919 config->format,
1920 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001921 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922
Eric Laurentcf2c0212014-07-25 16:20:43 -07001923 if (*devices == AUDIO_DEVICE_NONE) {
1924 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001926
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 Mutex::Autolock _l(mLock);
1928
Eric Laurentcf2c0212014-07-25 16:20:43 -07001929 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001930 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001931 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932
1933 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001934 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001935
1936 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001937 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001938 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001939 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001940
1941 AutoMutex lock(mHardwareLock);
1942 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001943 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001944 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001945 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001946 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 }
1948
Eric Laurentcf2c0212014-07-25 16:20:43 -07001949 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950}
1951
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001952audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1953 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954{
1955 Mutex::Autolock _l(mLock);
1956 MixerThread *thread1 = checkMixerThread_l(output1);
1957 MixerThread *thread2 = checkMixerThread_l(output2);
1958
1959 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001960 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1961 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001962 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963 }
1964
Glenn Kasteneeecb982016-02-26 10:44:04 -08001965 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001966 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 thread->addOutputTrack(thread2);
1968 mPlaybackThreads.add(id, thread);
1969 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001970 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 return id;
1972}
1973
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001974status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975{
Glenn Kastend96c5722012-04-25 13:44:49 -07001976 return closeOutput_nonvirtual(output);
1977}
1978
1979status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1980{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 // keep strong reference on the playback thread so that
1982 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001983 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984 {
1985 Mutex::Autolock _l(mLock);
1986 thread = checkPlaybackThread_l(output);
1987 if (thread == NULL) {
1988 return BAD_VALUE;
1989 }
1990
Steve Block3856b092011-10-20 11:56:00 +01001991 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001993 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001995 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001996 DuplicatingThread *dupThread =
1997 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001999 }
2000 }
2001 }
2002
2003
2004 mPlaybackThreads.removeItem(output);
2005 // save all effects to the default thread
2006 if (mPlaybackThreads.size()) {
2007 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2008 if (dstThread != NULL) {
2009 // audioflinger lock is held here so the acquisition order of thread locks does not
2010 // matter
2011 Mutex::Autolock _dl(dstThread->mLock);
2012 Mutex::Autolock _sl(thread->mLock);
2013 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
2014 for (size_t i = 0; i < effectChains.size(); i ++) {
2015 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016 }
2017 }
2018 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002019 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2020 ioDesc->mIoHandle = output;
2021 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 }
2023 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002024 // The thread entity (active unit of execution) is no longer running here,
2025 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026
Eric Laurentf6870ae2015-05-08 10:50:03 -07002027 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002028 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 }
Eric Laurent83b88082014-06-20 18:31:16 -07002030
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031 return NO_ERROR;
2032}
2033
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002034void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002035{
2036 AudioStreamOut *out = thread->clearOutput();
2037 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2038 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002039 delete out;
2040}
2041
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002042void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002043{
2044 mPlaybackThreads.removeItem(thread->mId);
2045 thread->exit();
2046 closeOutputFinish(thread);
2047}
2048
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002049status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050{
2051 Mutex::Autolock _l(mLock);
2052 PlaybackThread *thread = checkPlaybackThread_l(output);
2053
2054 if (thread == NULL) {
2055 return BAD_VALUE;
2056 }
2057
Steve Block3856b092011-10-20 11:56:00 +01002058 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 thread->suspend();
2060
2061 return NO_ERROR;
2062}
2063
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002064status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065{
2066 Mutex::Autolock _l(mLock);
2067 PlaybackThread *thread = checkPlaybackThread_l(output);
2068
2069 if (thread == NULL) {
2070 return BAD_VALUE;
2071 }
2072
Steve Block3856b092011-10-20 11:56:00 +01002073 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074
2075 thread->restore();
2076
2077 return NO_ERROR;
2078}
2079
Eric Laurentcf2c0212014-07-25 16:20:43 -07002080status_t AudioFlinger::openInput(audio_module_handle_t module,
2081 audio_io_handle_t *input,
2082 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002083 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002084 const String8& address,
2085 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002086 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087{
Eric Laurent83b88082014-06-20 18:31:16 -07002088 Mutex::Autolock _l(mLock);
2089
Glenn Kastene7d66712015-03-05 13:46:52 -08002090 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002091 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002092 }
2093
Glenn Kastene7d66712015-03-05 13:46:52 -08002094 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002095
2096 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002097 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002098 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002099 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002101 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002102}
Dima Zavin799a70e2011-04-18 16:57:27 -07002103
Eric Laurent83b88082014-06-20 18:31:16 -07002104sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002105 audio_io_handle_t *input,
2106 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002107 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002108 const String8& address,
2109 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002110 audio_input_flags_t flags)
2111{
Glenn Kastene7d66712015-03-05 13:46:52 -08002112 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002113 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002114 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002115 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002116 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002117
Glenn Kasteneeecb982016-02-26 10:44:04 -08002118 // Audio Policy can request a specific handle for hardware hotword.
2119 // The goal here is not to re-open an already opened input.
2120 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002121 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002122 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2123 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2124 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2125 return 0;
2126 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2127 // This should not happen in a transient state with current design.
2128 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2129 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002130 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002131
Eric Laurentcf2c0212014-07-25 16:20:43 -07002132 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002133 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002134 sp<StreamInHalInterface> inStream;
2135 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002136 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Mikhail Naganovf558e022016-11-14 17:45:17 -08002137 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002138 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002139 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002140 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002141 halconfig.sample_rate,
2142 halconfig.format,
2143 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002144 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002145 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002147 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002148 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002149 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002150 audio_is_linear_pcm(config->format) &&
2151 audio_is_linear_pcm(halconfig.format) &&
2152 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002153 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2154 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002155 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002156 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002157 inStream.clear();
2158 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002159 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002160 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 }
2162
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002163 if (status == NO_ERROR && inStream != 0) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002164
Glenn Kasten46909e72013-02-26 09:20:22 -08002165#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002166 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2167 // or (re-)create if current Pipe is idle and does not match the new format
2168 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002169 enum {
2170 TEE_SINK_NO, // don't copy input
2171 TEE_SINK_NEW, // copy input using a new pipe
2172 TEE_SINK_OLD, // copy input using an existing pipe
2173 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002174 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2175 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002176 if (!mTeeSinkInputEnabled) {
2177 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002178 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002179 kind = TEE_SINK_NO;
2180 } else if (mRecordTeeSink == 0) {
2181 kind = TEE_SINK_NEW;
2182 } else if (mRecordTeeSink->getStrongCount() != 1) {
2183 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002184 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002185 kind = TEE_SINK_OLD;
2186 } else {
2187 kind = TEE_SINK_NEW;
2188 }
2189 switch (kind) {
2190 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002191 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002192 size_t numCounterOffers = 0;
2193 const NBAIO_Format offers[1] = {format};
2194 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2195 ALOG_ASSERT(index == 0);
2196 PipeReader *pipeReader = new PipeReader(*pipe);
2197 numCounterOffers = 0;
2198 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2199 ALOG_ASSERT(index == 0);
2200 mRecordTeeSink = pipe;
2201 mRecordTeeSource = pipeReader;
2202 teeSink = pipe;
2203 }
2204 break;
2205 case TEE_SINK_OLD:
2206 teeSink = mRecordTeeSink;
2207 break;
2208 case TEE_SINK_NO:
2209 default:
2210 break;
2211 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002212#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002213
Eric Laurent05067782016-06-01 18:27:28 -07002214 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002215
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002216 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002217 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002218 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002219 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002220 inputStream,
2221 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002222 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002223 devices,
2224 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002225#ifdef TEE_SINK
2226 , teeSink
2227#endif
2228 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002229 mRecordThreads.add(*input, thread);
2230 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002231 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 }
2233
Eric Laurentcf2c0212014-07-25 16:20:43 -07002234 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 return 0;
2236}
2237
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002238status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239{
Glenn Kastend96c5722012-04-25 13:44:49 -07002240 return closeInput_nonvirtual(input);
2241}
2242
2243status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2244{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 // keep strong reference on the record thread so that
2246 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002247 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 {
2249 Mutex::Autolock _l(mLock);
2250 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002251 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 return BAD_VALUE;
2253 }
2254
Steve Block3856b092011-10-20 11:56:00 +01002255 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002256
2257 // If we still have effect chains, it means that a client still holds a handle
2258 // on at least one effect. We must either move the chain to an existing thread with the
2259 // same session ID or put it aside in case a new record thread is opened for a
2260 // new capture on the same session
2261 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002262 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002263 Mutex::Autolock _sl(thread->mLock);
2264 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002265 // Note: maximum one chain per record thread
2266 if (effectChains.size() != 0) {
2267 chain = effectChains[0];
2268 }
2269 }
2270 if (chain != 0) {
2271 // first check if a record thread is already opened with a client on the same session.
2272 // This should only happen in case of overlap between one thread tear down and the
2273 // creation of its replacement
2274 size_t i;
2275 for (i = 0; i < mRecordThreads.size(); i++) {
2276 sp<RecordThread> t = mRecordThreads.valueAt(i);
2277 if (t == thread) {
2278 continue;
2279 }
2280 if (t->hasAudioSession(chain->sessionId()) != 0) {
2281 Mutex::Autolock _l(t->mLock);
2282 ALOGV("closeInput() found thread %d for effect session %d",
2283 t->id(), chain->sessionId());
2284 t->addEffectChain_l(chain);
2285 break;
2286 }
2287 }
2288 // put the chain aside if we could not find a record thread with the same session id.
2289 if (i == mRecordThreads.size()) {
2290 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002291 }
2292 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002293 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2294 ioDesc->mIoHandle = input;
2295 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 mRecordThreads.removeItem(input);
2297 }
Eric Laurent83b88082014-06-20 18:31:16 -07002298 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2299 // we have a different lock for notification client
2300 closeInputFinish(thread);
2301 return NO_ERROR;
2302}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002304void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002305{
2306 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002307 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002308 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002309 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002310 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002311}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002313void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002314{
2315 mRecordThreads.removeItem(thread->mId);
2316 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317}
2318
Glenn Kastend2304db2014-02-03 07:40:31 -08002319status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320{
2321 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002322 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323
2324 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2325 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002326 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328
2329 return NO_ERROR;
2330}
2331
2332
Glenn Kasteneeecb982016-02-26 10:44:04 -08002333audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334{
Glenn Kasten9d003132016-04-06 14:38:09 -07002335 // This is a binder API, so a malicious client could pass in a bad parameter.
2336 // Check for that before calling the internal API nextUniqueId().
2337 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2338 ALOGE("newAudioUniqueId invalid use %d", use);
2339 return AUDIO_UNIQUE_ID_ALLOCATE;
2340 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002341 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342}
2343
Glenn Kastend848eb42016-03-08 13:42:11 -08002344void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002345{
2346 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002347 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002348 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2349 if (pid != -1 && (caller == getpid_cached)) {
2350 caller = pid;
2351 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002352
Eric Laurent021cf962014-05-13 10:18:14 -07002353 {
2354 Mutex::Autolock _cl(mClientLock);
2355 // Ignore requests received from processes not known as notification client. The request
2356 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2357 // called from a different pid leaving a stale session reference. Also we don't know how
2358 // to clear this reference if the client process dies.
2359 if (mNotificationClients.indexOfKey(caller) < 0) {
2360 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2361 return;
2362 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002363 }
2364
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002365 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002366 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002367 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002368 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2369 ref->mCnt++;
2370 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002371 return;
2372 }
2373 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002374 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2375 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002376}
2377
Glenn Kastend848eb42016-03-08 13:42:11 -08002378void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002379{
2380 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002381 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002382 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2383 if (pid != -1 && (caller == getpid_cached)) {
2384 caller = pid;
2385 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002386 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002387 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002388 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002389 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2390 ref->mCnt--;
2391 ALOGV(" decremented refcount to %d", ref->mCnt);
2392 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002393 mAudioSessionRefs.removeAt(i);
2394 delete ref;
2395 purgeStaleEffects_l();
2396 }
2397 return;
2398 }
2399 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002400 // If the caller is mediaserver it is likely that the session being released was acquired
2401 // on behalf of a process not in notification clients and we ignore the warning.
2402 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002403}
2404
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002405bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2406{
2407 size_t num = mAudioSessionRefs.size();
2408 for (size_t i = 0; i < num; i++) {
2409 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2410 if (ref->mSessionid == audioSession) {
2411 return true;
2412 }
2413 }
2414 return false;
2415}
2416
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002417void AudioFlinger::purgeStaleEffects_l() {
2418
Steve Block3856b092011-10-20 11:56:00 +01002419 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002420
2421 Vector< sp<EffectChain> > chains;
2422
2423 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2424 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2425 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2426 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002427 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2428 chains.push(ec);
2429 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002430 }
2431 }
2432 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2433 sp<RecordThread> t = mRecordThreads.valueAt(i);
2434 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2435 sp<EffectChain> ec = t->mEffectChains[j];
2436 chains.push(ec);
2437 }
2438 }
2439
2440 for (size_t i = 0; i < chains.size(); i++) {
2441 sp<EffectChain> ec = chains[i];
2442 int sessionid = ec->sessionId();
2443 sp<ThreadBase> t = ec->mThread.promote();
2444 if (t == 0) {
2445 continue;
2446 }
2447 size_t numsessionrefs = mAudioSessionRefs.size();
2448 bool found = false;
2449 for (size_t k = 0; k < numsessionrefs; k++) {
2450 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002451 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002452 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002453 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002454 found = true;
2455 break;
2456 }
2457 }
2458 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002459 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002460 // remove all effects from the chain
2461 while (ec->mEffects.size()) {
2462 sp<EffectModule> effect = ec->mEffects[0];
2463 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002464 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002465 if (effect->purgeHandles()) {
2466 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002467 }
2468 AudioSystem::unregisterEffect(effect->id());
2469 }
2470 }
2471 }
2472 return;
2473}
2474
Glenn Kasteneeecb982016-02-26 10:44:04 -08002475// checkThread_l() must be called with AudioFlinger::mLock held
2476AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2477{
2478 ThreadBase *thread = NULL;
2479 switch (audio_unique_id_get_use(ioHandle)) {
2480 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2481 thread = checkPlaybackThread_l(ioHandle);
2482 break;
2483 case AUDIO_UNIQUE_ID_USE_INPUT:
2484 thread = checkRecordThread_l(ioHandle);
2485 break;
2486 default:
2487 break;
2488 }
2489 return thread;
2490}
2491
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002493AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494{
Glenn Kastena1117922012-01-26 10:53:32 -08002495 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496}
2497
2498// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002499AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500{
2501 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002502 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503}
2504
2505// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002506AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507{
Glenn Kastena1117922012-01-26 10:53:32 -08002508 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509}
2510
Glenn Kasteneeecb982016-02-26 10:44:04 -08002511audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512{
Glenn Kasten9d003132016-04-06 14:38:09 -07002513 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002514 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002515 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2516 for (int retry = 0; retry < maxRetries; retry++) {
2517 // The cast allows wraparound from max positive to min negative instead of abort
2518 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2519 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2520 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2521 // allow wrap by skipping 0 and -1 for session ids
2522 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2523 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2524 return (audio_unique_id_t) (base | use);
2525 }
2526 }
2527 // We have no way of recovering from wraparound
2528 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2529 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530}
2531
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002532AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002533{
2534 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2535 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002536 if(thread->isDuplicating()) {
2537 continue;
2538 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002539 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002540 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002541 return thread;
2542 }
2543 }
2544 return NULL;
2545}
2546
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002547audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002548{
2549 PlaybackThread *thread = primaryPlaybackThread_l();
2550
2551 if (thread == NULL) {
2552 return 0;
2553 }
2554
Eric Laurentf1c04f92012-08-28 14:26:53 -07002555 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002556}
2557
Glenn Kastena7335632016-06-09 17:09:53 -07002558AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2559{
2560 size_t minFrameCount = 0;
2561 PlaybackThread *minThread = NULL;
2562 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2563 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2564 if (!thread->isDuplicating()) {
2565 size_t frameCount = thread->frameCountHAL();
2566 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2567 (frameCount == minFrameCount && thread->hasFastMixer() &&
2568 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2569 minFrameCount = frameCount;
2570 minThread = thread;
2571 }
2572 }
2573 }
2574 return minThread;
2575}
2576
Eric Laurenta011e352012-03-29 15:51:43 -07002577sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002578 audio_session_t triggerSession,
2579 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002580 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002581 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002582{
2583 Mutex::Autolock _l(mLock);
2584
2585 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2586 status_t playStatus = NAME_NOT_FOUND;
2587 status_t recStatus = NAME_NOT_FOUND;
2588 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2589 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2590 if (playStatus == NO_ERROR) {
2591 return event;
2592 }
2593 }
2594 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2595 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2596 if (recStatus == NO_ERROR) {
2597 return event;
2598 }
2599 }
2600 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2601 mPendingSyncEvents.add(event);
2602 } else {
2603 ALOGV("createSyncEvent() invalid event %d", event->type());
2604 event.clear();
2605 }
2606 return event;
2607}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002608
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609// ----------------------------------------------------------------------------
2610// Effect management
2611// ----------------------------------------------------------------------------
2612
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002613sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2614 return mEffectsFactoryHal;
2615}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616
Glenn Kastenf587ba52012-01-26 16:25:10 -08002617status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618{
2619 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002620 if (mEffectsFactoryHal.get()) {
2621 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2622 } else {
2623 return -ENODEV;
2624 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625}
2626
Glenn Kastenf587ba52012-01-26 16:25:10 -08002627status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628{
2629 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002630 if (mEffectsFactoryHal.get()) {
2631 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2632 } else {
2633 return -ENODEV;
2634 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635}
2636
Glenn Kasten5e92a782012-01-30 07:40:52 -08002637status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002638 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639{
2640 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002641 if (mEffectsFactoryHal.get()) {
2642 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2643 } else {
2644 return -ENODEV;
2645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646}
2647
2648
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002649sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 effect_descriptor_t *pDesc,
2651 const sp<IEffectClient>& effectClient,
2652 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002653 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002654 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002655 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002656 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 status_t *status,
2658 int *id,
2659 int *enabled)
2660{
2661 status_t lStatus = NO_ERROR;
2662 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664
Eric Laurentb6436272016-12-07 19:24:50 -08002665 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2666 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2667 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2668 ALOGW_IF(pid != -1 && pid != callingPid,
2669 "%s uid %d pid %d tried to pass itself off as pid %d",
2670 __func__, callingUid, callingPid, pid);
2671 pid = callingPid;
2672 }
2673
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002674 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2675 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676
2677 if (pDesc == NULL) {
2678 lStatus = BAD_VALUE;
2679 goto Exit;
2680 }
2681
Eric Laurent84e9a102010-09-23 16:10:16 -07002682 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002683 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002684 lStatus = PERMISSION_DENIED;
2685 goto Exit;
2686 }
2687
Dima Zavinfce7a472011-04-19 22:30:36 -07002688 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002689 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002690 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002691 lStatus = PERMISSION_DENIED;
2692 goto Exit;
2693 }
2694
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002695 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002696 lStatus = NO_INIT;
2697 goto Exit;
2698 }
2699
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002701 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002703 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002705 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 goto Exit;
2707 }
2708 } else {
2709 // if uuid is not specified, look for an available implementation
2710 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002711 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002712 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 lStatus = BAD_VALUE;
2714 goto Exit;
2715 }
2716 uint32_t numEffects = 0;
2717 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002718 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 bool found = false;
2720
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002721 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002723 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002724 goto Exit;
2725 }
2726 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002727 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002728 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002729 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 continue;
2731 }
2732 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2733 // If matching type found save effect descriptor. If the session is
2734 // 0 and the effect is not auxiliary, continue enumeration in case
2735 // an auxiliary version of this effect type is available
2736 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002737 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002738 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2740 break;
2741 }
2742 }
2743 }
2744 if (!found) {
2745 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002746 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 goto Exit;
2748 }
2749 // For same effect type, chose auxiliary version over insert version if
2750 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002751 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002753 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 }
2755 }
2756
2757 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002758 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2760 lStatus = INVALID_OPERATION;
2761 goto Exit;
2762 }
2763
Eric Laurent59255e42011-07-27 19:49:51 -07002764 // check recording permission for visualizer
2765 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002766 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002767 lStatus = PERMISSION_DENIED;
2768 goto Exit;
2769 }
2770
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002772 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002773 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002774 // if the output returned by getOutputForEffect() is removed before we lock the
2775 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2776 // and we will exit safely
2777 io = AudioSystem::getOutputForEffect(&desc);
2778 ALOGV("createEffect got output %d", io);
2779 }
2780
2781 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002782
2783 // If output is not specified try to find a matching audio session ID in one of the
2784 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002785 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2786 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002787 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002788 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002789 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2790 // output must be specified by AudioPolicyManager when using session
2791 // AUDIO_SESSION_OUTPUT_STAGE
2792 lStatus = BAD_VALUE;
2793 goto Exit;
2794 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002795 // look for the thread where the specified audio session is present
2796 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2797 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2798 io = mPlaybackThreads.keyAt(i);
2799 break;
2800 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002802 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002803 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2804 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2805 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002806 break;
2807 }
2808 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002809 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002810 // If no output thread contains the requested session ID, default to
2811 // first output. The effect chain will be moved to the correct output
2812 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002813 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002814 io = mPlaybackThreads.keyAt(0);
2815 }
Steve Block3856b092011-10-20 11:56:00 +01002816 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002817 }
2818 ThreadBase *thread = checkRecordThread_l(io);
2819 if (thread == NULL) {
2820 thread = checkPlaybackThread_l(io);
2821 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002822 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002823 lStatus = BAD_VALUE;
2824 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002825 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002826 } else {
2827 // Check if one effect chain was awaiting for an effect to be created on this
2828 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002829 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002830 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002831 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002832 thread->addEffectChain_l(chain);
2833 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002835
Eric Laurent021cf962014-05-13 10:18:14 -07002836 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002838 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002839 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002840 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002841 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 if (handle != 0 && id != NULL) {
2843 *id = handle->id();
2844 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002845 if (handle == 0) {
2846 // remove local strong reference to Client with mClientLock held
2847 Mutex::Autolock _cl(mClientLock);
2848 client.clear();
2849 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 }
2851
2852Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002853 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854 return handle;
2855}
2856
Glenn Kastend848eb42016-03-08 13:42:11 -08002857status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002858 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002859{
Steve Block3856b092011-10-20 11:56:00 +01002860 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002861 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002862 Mutex::Autolock _l(mLock);
2863 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002864 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002865 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866 }
Eric Laurentde070132010-07-13 04:45:46 -07002867 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2868 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002869 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002870 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 }
Eric Laurentde070132010-07-13 04:45:46 -07002872 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2873 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002874 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002875 return BAD_VALUE;
2876 }
2877
2878 Mutex::Autolock _dl(dstThread->mLock);
2879 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002880 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881}
2882
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002883// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002884status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002885 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002886 AudioFlinger::PlaybackThread *dstThread,
2887 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002888{
Steve Block3856b092011-10-20 11:56:00 +01002889 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002890 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002891
Eric Laurent59255e42011-07-27 19:49:51 -07002892 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002893 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002894 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002895 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002896 return INVALID_OPERATION;
2897 }
2898
Eric Laurent4c415062016-06-17 16:14:16 -07002899 // Check whether the destination thread and all effects in the chain are compatible
2900 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002901 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002902 " destination thread %p is not compatible with effects in the chain",
2903 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002904 return INVALID_OPERATION;
2905 }
2906
Eric Laurent39e94f82010-07-28 01:32:47 -07002907 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002908 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002909 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002910 // removed.
2911 srcThread->removeEffectChain_l(chain);
2912
2913 // transfer all effects one by one so that new effect chain is created on new thread with
2914 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002915 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002916 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002917 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002918 Vector< sp<EffectModule> > removed;
2919 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002920 while (effect != 0) {
2921 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002922 removed.add(effect);
2923 status = dstThread->addEffect_l(effect);
2924 if (status != NO_ERROR) {
2925 break;
2926 }
Eric Laurentec35a142011-10-05 17:42:25 -07002927 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2928 if (effect->state() == EffectModule::ACTIVE ||
2929 effect->state() == EffectModule::STOPPING) {
2930 effect->start();
2931 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002932 // if the move request is not received from audio policy manager, the effect must be
2933 // re-registered with the new strategy and output
2934 if (dstChain == 0) {
2935 dstChain = effect->chain().promote();
2936 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002937 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002938 status = NO_INIT;
2939 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002940 }
2941 strategy = dstChain->strategy();
2942 }
2943 if (reRegister) {
2944 AudioSystem::unregisterEffect(effect->id());
2945 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002946 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002947 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002948 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002949 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002950 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002951 }
Eric Laurentde070132010-07-13 04:45:46 -07002952 effect = chain->getEffectFromId_l(0);
2953 }
2954
Eric Laurent5baf2af2013-09-12 17:37:00 -07002955 if (status != NO_ERROR) {
2956 for (size_t i = 0; i < removed.size(); i++) {
2957 srcThread->addEffect_l(removed[i]);
2958 if (dstChain != 0 && reRegister) {
2959 AudioSystem::unregisterEffect(removed[i]->id());
2960 AudioSystem::registerEffect(&removed[i]->desc(),
2961 srcThread->id(),
2962 strategy,
2963 sessionId,
2964 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002965 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002966 }
2967 }
2968 }
2969
2970 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971}
2972
Eric Laurent5baf2af2013-09-12 17:37:00 -07002973bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002974{
2975 if (mGlobalEffectEnableTime != 0 &&
2976 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2977 return true;
2978 }
2979
2980 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2981 sp<EffectChain> ec =
2982 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002983 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002984 return true;
2985 }
2986 }
2987 return false;
2988}
2989
Eric Laurent5baf2af2013-09-12 17:37:00 -07002990void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002991{
2992 Mutex::Autolock _l(mLock);
2993
2994 mGlobalEffectEnableTime = systemTime();
2995
2996 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2997 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2998 if (t->mType == ThreadBase::OFFLOAD) {
2999 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3000 }
3001 }
3002
3003}
3004
Eric Laurentaaa44472014-09-12 17:41:50 -07003005status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3006{
Glenn Kastend848eb42016-03-08 13:42:11 -08003007 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003008 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003009 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003010 if (index >= 0) {
3011 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3012 return ALREADY_EXISTS;
3013 }
3014 mOrphanEffectChains.add(session, chain);
3015 return NO_ERROR;
3016}
3017
3018sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3019{
3020 sp<EffectChain> chain;
3021 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003022 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003023 if (index >= 0) {
3024 chain = mOrphanEffectChains.valueAt(index);
3025 mOrphanEffectChains.removeItemsAt(index);
3026 }
3027 return chain;
3028}
3029
3030bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3031{
3032 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003033 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003034 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003035 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003036 if (index >= 0) {
3037 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003038 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003039 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003040 mOrphanEffectChains.removeItemsAt(index);
3041 }
3042 return true;
3043 }
3044 return false;
3045}
3046
3047
Glenn Kastenda6ef132013-01-10 12:31:01 -08003048struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003049#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3050 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003051};
3052
3053int comparEntry(const void *p1, const void *p2)
3054{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003055 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003056}
3057
Glenn Kasten46909e72013-02-26 09:20:22 -08003058#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003059void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060{
Eric Laurent81784c32012-11-19 14:55:58 -08003061 NBAIO_Source *teeSource = source.get();
3062 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003063 // .wav rotation
3064 // There is a benign race condition if 2 threads call this simultaneously.
3065 // They would both traverse the directory, but the result would simply be
3066 // failures at unlink() which are ignored. It's also unlikely since
3067 // normally dumpsys is only done by bugreport or from the command line.
3068 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003069 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003070 size_t teePathLen = strlen(teePath);
3071 DIR *dir = opendir(teePath);
3072 teePath[teePathLen++] = '/';
3073 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003074#define TEE_MAX_SORT 20 // number of entries to sort
3075#define TEE_MAX_KEEP 10 // number of entries to keep
3076 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003077 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003078 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003079 struct dirent de;
3080 struct dirent *result = NULL;
3081 int rc = readdir_r(dir, &de, &result);
3082 if (rc != 0) {
3083 ALOGW("readdir_r failed %d", rc);
3084 break;
3085 }
3086 if (result == NULL) {
3087 break;
3088 }
3089 if (result != &de) {
3090 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3091 break;
3092 }
3093 // ignore non .wav file entries
3094 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003095 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003096 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3097 continue;
3098 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003099 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003100 }
3101 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003102 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003103 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003104 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3105 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003106 (void) unlink(teePath);
3107 }
3108 }
3109 } else {
3110 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003111 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003112 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003113 }
3114 }
Eric Laurent81784c32012-11-19 14:55:58 -08003115 char teeTime[16];
3116 struct timeval tv;
3117 gettimeofday(&tv, NULL);
3118 struct tm tm;
3119 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003120 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3121 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3122 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3123 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003124 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003125 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003126 char wavHeader[44];
3127 memcpy(wavHeader,
3128 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3129 sizeof(wavHeader));
3130 NBAIO_Format format = teeSource->format();
3131 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003132 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003133 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003134 wavHeader[22] = channelCount; // number of channels
3135 wavHeader[24] = sampleRate; // sample rate
3136 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003137 wavHeader[32] = frameSize; // block alignment
3138 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003139 write(teeFd, wavHeader, sizeof(wavHeader));
3140 size_t total = 0;
3141 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003142#define TEE_SINK_READ 1024 // frames per I/O operation
3143 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003144 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003145 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003146 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003147 bool wasFirstRead = firstRead;
3148 firstRead = false;
3149 if (actual <= 0) {
3150 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3151 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003152 }
Eric Laurent81784c32012-11-19 14:55:58 -08003153 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003154 }
Eric Laurent81784c32012-11-19 14:55:58 -08003155 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003156 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003157 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003158 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003159 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003160 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003161 uint32_t temp = 44 + total * frameSize - 8;
3162 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003163 write(teeFd, &temp, sizeof(temp));
3164 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003165 temp = total * frameSize;
3166 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003167 write(teeFd, &temp, sizeof(temp));
3168 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003169 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003170 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003171 }
Eric Laurent59255e42011-07-27 19:49:51 -07003172 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003173 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003174 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003175 }
Eric Laurent59255e42011-07-27 19:49:51 -07003176 }
3177 }
3178}
Glenn Kasten46909e72013-02-26 09:20:22 -08003179#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003180
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181// ----------------------------------------------------------------------------
3182
3183status_t AudioFlinger::onTransact(
3184 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3185{
3186 return BnAudioFlinger::onTransact(code, data, reply, flags);
3187}
3188
Glenn Kasten63238ef2015-03-02 15:50:29 -08003189} // namespace android