blob: f8ad3dfaf3817ef265cd1a483ae06b03c0d88a31 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
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"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9b3f1522011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070028#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurentae29b762011-03-28 18:37:07 -070034#include <utils/Atomic.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035
Dima Zavin24fc2fb2011-04-19 22:30:36 -070036#include <cutils/bitops.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080037#include <cutils/properties.h>
Glenn Kastene80a4cc2011-12-15 09:51:17 -080038#include <cutils/compiler.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080039
Gloria Wang9b3f1522011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten26f260a2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070044#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
Dima Zavin34bb4192011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070047#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Eric Laurent53334cd2010-06-23 17:38:20 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
Glenn Kasten490909d2011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kastenda494f92011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
Eric Laurent8ed6ed02010-07-13 04:45:46 -070065
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066namespace android {
67
Glenn Kasten62de3db2011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070070
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080071//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072static const float MAX_GAIN = 4096.0f;
Glenn Kasten0632bad2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080079// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070083
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070084static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086
Glenn Kastencbfe2e12011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070089
Eric Laurent464d5b32011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Glenn Kastencbfe2e12011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070095
Eric Laurentf1f5fc82011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block3762c312012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700108 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700109}
110
111static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block3762c312012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700115 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116}
117
Gloria Wang9b3f1522011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten26f260a2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9b3f1522011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin31f188892011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block3762c312012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin31f188892011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kasten62de3db2011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin31f188892011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 : BnAudioFlinger(),
Glenn Kastenc434c902011-12-13 11:53:26 -0800163 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700164 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700165{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700166}
167
168void AudioFlinger::onFirstRef()
169{
Dima Zavin31f188892011-04-18 16:57:27 -0700170 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700171
Eric Laurent01635942011-01-18 18:39:02 -0800172 Mutex::Autolock _l(mLock);
173
Dima Zavin31f188892011-04-18 16:57:27 -0700174 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700175 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700176
Dima Zavin31f188892011-04-18 16:57:27 -0700177 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
178 const hw_module_t *mod;
179 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700180
Dima Zavin31f188892011-04-18 16:57:27 -0700181 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
182 if (rc)
183 continue;
184
Steve Block6215d3f2012-01-04 20:05:49 +0000185 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin31f188892011-04-18 16:57:27 -0700186 mod->name, mod->id);
187 mAudioHwDevs.push(dev);
188
189 if (!mPrimaryHardwareDev) {
190 mPrimaryHardwareDev = dev;
Steve Block6215d3f2012-01-04 20:05:49 +0000191 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700192 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700193 }
194 }
Eric Laurenta553c252009-07-17 12:17:14 -0700195
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700196 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700197
Dima Zavin31f188892011-04-18 16:57:27 -0700198 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block3762c312012-01-06 19:20:56 +0000199 ALOGE("Primary audio interface not found");
Dima Zavin31f188892011-04-18 16:57:27 -0700200 return;
201 }
202
203 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
204 audio_hw_device_t *dev = mAudioHwDevs[i];
205
206 mHardwareStatus = AUDIO_HW_INIT;
207 rc = dev->init_check(dev);
208 if (rc == 0) {
209 AutoMutex lock(mHardwareLock);
210
211 mMode = AUDIO_MODE_NORMAL;
212 mHardwareStatus = AUDIO_HW_SET_MODE;
213 dev->set_mode(dev, mMode);
214 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
215 dev->set_master_volume(dev, 1.0f);
216 mHardwareStatus = AUDIO_HW_IDLE;
217 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700218 }
219}
220
Dima Zavin2986f5b2011-04-19 19:04:32 -0700221status_t AudioFlinger::initCheck() const
222{
223 Mutex::Autolock _l(mLock);
224 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
225 return NO_INIT;
226 return NO_ERROR;
227}
228
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700229AudioFlinger::~AudioFlinger()
230{
Dima Zavin31f188892011-04-18 16:57:27 -0700231 int num_devs = mAudioHwDevs.size();
232
Eric Laurent7954c462009-08-28 10:39:03 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin31f188892011-04-18 16:57:27 -0700241
242 for (int i = 0; i < num_devs; i++) {
243 audio_hw_device_t *dev = mAudioHwDevs[i];
244 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700245 }
Dima Zavin31f188892011-04-18 16:57:27 -0700246 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800247}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800248
Dima Zavin31f188892011-04-18 16:57:27 -0700249audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
250{
251 /* first matching HW device is returned */
252 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
253 audio_hw_device_t *dev = mAudioHwDevs[i];
254 if ((dev->get_supported_devices(dev) & devices) == devices)
255 return dev;
256 }
257 return NULL;
258}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700259
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
261{
262 const size_t SIZE = 256;
263 char buffer[SIZE];
264 String8 result;
265
266 result.append("Clients:\n");
267 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -0800268 sp<Client> client = mClients.valueAt(i).promote();
269 if (client != 0) {
270 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
271 result.append(buffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700272 }
273 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700274
275 result.append("Global session refs:\n");
276 result.append(" session pid cnt\n");
277 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
278 AudioSessionRef *r = mAudioSessionRefs[i];
279 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
280 result.append(buffer);
281 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700282 write(fd, result.string(), result.size());
283 return NO_ERROR;
284}
285
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700286
287status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
288{
289 const size_t SIZE = 256;
290 char buffer[SIZE];
291 String8 result;
Glenn Kastena934c2c2012-01-04 11:02:33 -0800292 hardware_call_state hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700293
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700294 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700295 result.append(buffer);
296 write(fd, result.string(), result.size());
297 return NO_ERROR;
298}
299
300status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
301{
302 const size_t SIZE = 256;
303 char buffer[SIZE];
304 String8 result;
305 snprintf(buffer, SIZE, "Permission Denial: "
306 "can't dump AudioFlinger from pid=%d, uid=%d\n",
307 IPCThreadState::self()->getCallingPid(),
308 IPCThreadState::self()->getCallingUid());
309 result.append(buffer);
310 write(fd, result.string(), result.size());
311 return NO_ERROR;
312}
313
The Android Open Source Project10592532009-03-18 17:39:46 -0700314static bool tryLock(Mutex& mutex)
315{
316 bool locked = false;
317 for (int i = 0; i < kDumpLockRetries; ++i) {
318 if (mutex.tryLock() == NO_ERROR) {
319 locked = true;
320 break;
321 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800322 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700323 }
324 return locked;
325}
326
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700327status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
328{
Glenn Kastenb737dbb2012-01-13 15:54:24 -0800329 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700330 dumpPermissionDenial(fd, args);
331 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700332 // get state of hardware lock
333 bool hardwareLocked = tryLock(mHardwareLock);
334 if (!hardwareLocked) {
335 String8 result(kHardwareLockedString);
336 write(fd, result.string(), result.size());
337 } else {
338 mHardwareLock.unlock();
339 }
340
341 bool locked = tryLock(mLock);
342
343 // failed to lock - AudioFlinger is probably deadlocked
344 if (!locked) {
345 String8 result(kDeadlockedString);
346 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700347 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700348
349 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700350 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351
Eric Laurenta553c252009-07-17 12:17:14 -0700352 // dump playback threads
353 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700354 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700355 }
356
357 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700358 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700359 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361
Dima Zavin31f188892011-04-18 16:57:27 -0700362 // dump all hardware devs
363 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
364 audio_hw_device_t *dev = mAudioHwDevs[i];
365 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700366 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700367 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368 }
369 return NO_ERROR;
370}
371
Eric Laurenta553c252009-07-17 12:17:14 -0700372
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374
375
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376sp<IAudioTrack> AudioFlinger::createTrack(
377 pid_t pid,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800378 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800380 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700381 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800382 int frameCount,
383 uint32_t flags,
384 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700385 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700386 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800387 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700388{
Eric Laurenta553c252009-07-17 12:17:14 -0700389 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700390 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700391 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800392 wp<Client> wclient;
393 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700394 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395
Glenn Kasten6e987a42012-01-06 08:40:01 -0800396 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
397 // but if someone uses binder directly they could bypass that and cause us to crash
398 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000399 ALOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800400 lStatus = BAD_VALUE;
401 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700402 }
403
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800404 {
405 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700406 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700407 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700408 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +0000409 ALOGE("unknown output thread");
Eric Laurenta553c252009-07-17 12:17:14 -0700410 lStatus = BAD_VALUE;
411 goto Exit;
412 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800413
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800414 wclient = mClients.valueFor(pid);
415
416 if (wclient != NULL) {
417 client = wclient.promote();
418 } else {
419 client = new Client(this, pid);
420 mClients.add(pid, client);
421 }
Eric Laurent65b65452010-06-01 23:49:17 -0700422
Steve Block71f2cf12011-10-20 11:56:00 +0100423 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700424 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700425 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700426 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
427 if (mPlaybackThreads.keyAt(i) != output) {
428 // prevent same audio session on different output threads
429 uint32_t sessions = t->hasAudioSession(*sessionId);
430 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block3762c312012-01-06 19:20:56 +0000431 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700432 lStatus = BAD_VALUE;
433 goto Exit;
434 }
435 // check if an effect with same session ID is waiting for a track to be created
436 if (sessions & PlaybackThread::EFFECT_SESSION) {
437 effectThread = t.get();
438 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700439 }
440 }
Eric Laurent65b65452010-06-01 23:49:17 -0700441 lSessionId = *sessionId;
442 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700443 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700444 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700445 if (sessionId != NULL) {
446 *sessionId = lSessionId;
447 }
448 }
Steve Block71f2cf12011-10-20 11:56:00 +0100449 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700450
Eric Laurenta553c252009-07-17 12:17:14 -0700451 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700452 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700453
454 // move effect chain to this output thread if an effect on same session was waiting
455 // for a track to be created
456 if (lStatus == NO_ERROR && effectThread != NULL) {
457 Mutex::Autolock _dl(thread->mLock);
458 Mutex::Autolock _sl(effectThread->mLock);
459 moveEffectChain_l(lSessionId, effectThread, thread, true);
460 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700461 }
462 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800463 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700464 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700465 // remove local strong reference to Client before deleting the Track so that the Client
466 // destructor is called by the TrackBase destructor with mLock held
467 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700468 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800469 }
470
471Exit:
472 if(status) {
473 *status = lStatus;
474 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700475 return trackHandle;
476}
477
Eric Laurentddb78e72009-07-28 08:44:33 -0700478uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479{
Eric Laurenta553c252009-07-17 12:17:14 -0700480 Mutex::Autolock _l(mLock);
481 PlaybackThread *thread = checkPlaybackThread_l(output);
482 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000483 ALOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700484 return 0;
485 }
486 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700487}
488
Eric Laurentddb78e72009-07-28 08:44:33 -0700489int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490{
Eric Laurenta553c252009-07-17 12:17:14 -0700491 Mutex::Autolock _l(mLock);
492 PlaybackThread *thread = checkPlaybackThread_l(output);
493 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000494 ALOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700495 return 0;
496 }
497 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700498}
499
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800500audio_format_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501{
Eric Laurenta553c252009-07-17 12:17:14 -0700502 Mutex::Autolock _l(mLock);
503 PlaybackThread *thread = checkPlaybackThread_l(output);
504 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000505 ALOGW("format() unknown thread %d", output);
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800506 return AUDIO_FORMAT_INVALID;
Eric Laurenta553c252009-07-17 12:17:14 -0700507 }
508 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700509}
510
Eric Laurentddb78e72009-07-28 08:44:33 -0700511size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512{
Eric Laurenta553c252009-07-17 12:17:14 -0700513 Mutex::Autolock _l(mLock);
514 PlaybackThread *thread = checkPlaybackThread_l(output);
515 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000516 ALOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700517 return 0;
518 }
519 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700520}
521
Eric Laurentddb78e72009-07-28 08:44:33 -0700522uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800523{
Eric Laurenta553c252009-07-17 12:17:14 -0700524 Mutex::Autolock _l(mLock);
525 PlaybackThread *thread = checkPlaybackThread_l(output);
526 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000527 ALOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700528 return 0;
529 }
530 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800531}
532
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700533status_t AudioFlinger::setMasterVolume(float value)
534{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700535 status_t ret = initCheck();
536 if (ret != NO_ERROR) {
537 return ret;
538 }
539
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700540 // check calling permissions
541 if (!settingsAllowed()) {
542 return PERMISSION_DENIED;
543 }
544
545 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800546 { // scope for the lock
547 AutoMutex lock(mHardwareLock);
548 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700549 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800550 value = 1.0f;
551 }
552 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700553 }
Eric Laurenta553c252009-07-17 12:17:14 -0700554
Eric Laurent01635942011-01-18 18:39:02 -0800555 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700556 mMasterVolume = value;
557 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700558 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700559
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700560 return NO_ERROR;
561}
562
Glenn Kastenaccb1142012-01-04 11:00:47 -0800563status_t AudioFlinger::setMode(audio_mode_t mode)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700564{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700565 status_t ret = initCheck();
566 if (ret != NO_ERROR) {
567 return ret;
568 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700569
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700570 // check calling permissions
571 if (!settingsAllowed()) {
572 return PERMISSION_DENIED;
573 }
Glenn Kasten01aaf2c2012-01-06 16:47:31 -0800574 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block8564c8d2012-01-05 23:22:43 +0000575 ALOGW("Illegal value: setMode(%d)", mode);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700576 return BAD_VALUE;
577 }
578
Eric Laurent53334cd2010-06-23 17:38:20 -0700579 { // scope for the lock
580 AutoMutex lock(mHardwareLock);
581 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700582 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700583 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800584 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700585
586 if (NO_ERROR == ret) {
587 Mutex::Autolock _l(mLock);
588 mMode = mode;
589 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
590 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700591 }
592
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700593 return ret;
594}
595
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700596status_t AudioFlinger::setMicMute(bool state)
597{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700598 status_t ret = initCheck();
599 if (ret != NO_ERROR) {
600 return ret;
601 }
602
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
608 AutoMutex lock(mHardwareLock);
609 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700610 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700611 mHardwareStatus = AUDIO_HW_IDLE;
612 return ret;
613}
614
615bool AudioFlinger::getMicMute() const
616{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700617 status_t ret = initCheck();
618 if (ret != NO_ERROR) {
619 return false;
620 }
621
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700622 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700623 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700624 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625 mHardwareStatus = AUDIO_HW_IDLE;
626 return state;
627}
628
629status_t AudioFlinger::setMasterMute(bool muted)
630{
631 // check calling permissions
632 if (!settingsAllowed()) {
633 return PERMISSION_DENIED;
634 }
Eric Laurenta553c252009-07-17 12:17:14 -0700635
Eric Laurent01635942011-01-18 18:39:02 -0800636 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700637 mMasterMute = muted;
638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700639 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700640
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700641 return NO_ERROR;
642}
643
644float AudioFlinger::masterVolume() const
645{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800646 Mutex::Autolock _l(mLock);
647 return masterVolume_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700648}
649
650bool AudioFlinger::masterMute() const
651{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800652 Mutex::Autolock _l(mLock);
653 return masterMute_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700654}
655
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800656status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700657{
658 // check calling permissions
659 if (!settingsAllowed()) {
660 return PERMISSION_DENIED;
661 }
662
Glenn Kasten6e987a42012-01-06 08:40:01 -0800663 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000664 ALOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700665 return BAD_VALUE;
666 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800667
Eric Laurenta553c252009-07-17 12:17:14 -0700668 AutoMutex lock(mLock);
669 PlaybackThread *thread = NULL;
670 if (output) {
671 thread = checkPlaybackThread_l(output);
672 if (thread == NULL) {
673 return BAD_VALUE;
674 }
675 }
676
Eric Laurenta553c252009-07-17 12:17:14 -0700677 mStreamTypes[stream].volume = value;
678
679 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700680 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700681 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700682 }
Eric Laurenta553c252009-07-17 12:17:14 -0700683 } else {
684 thread->setStreamVolume(stream, value);
685 }
Eric Laurentef028272009-04-21 07:56:33 -0700686
Eric Laurent415f3e22009-10-21 08:14:22 -0700687 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700688}
689
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800690status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700691{
692 // check calling permissions
693 if (!settingsAllowed()) {
694 return PERMISSION_DENIED;
695 }
696
Glenn Kasten6e987a42012-01-06 08:40:01 -0800697 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700698 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block3762c312012-01-06 19:20:56 +0000699 ALOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700700 return BAD_VALUE;
701 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700702
Eric Laurent01635942011-01-18 18:39:02 -0800703 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700704 mStreamTypes[stream].mute = muted;
705 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700706 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700708 return NO_ERROR;
709}
710
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800711float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700712{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800713 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714 return 0.0f;
715 }
Eric Laurenta553c252009-07-17 12:17:14 -0700716
717 AutoMutex lock(mLock);
718 float volume;
719 if (output) {
720 PlaybackThread *thread = checkPlaybackThread_l(output);
721 if (thread == NULL) {
722 return 0.0f;
723 }
724 volume = thread->streamVolume(stream);
725 } else {
726 volume = mStreamTypes[stream].volume;
727 }
728
Eric Laurentef028272009-04-21 07:56:33 -0700729 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700730}
731
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800732bool AudioFlinger::streamMute(audio_stream_type_t stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700733{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800734 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700735 return true;
736 }
Eric Laurenta553c252009-07-17 12:17:14 -0700737
738 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700739}
740
Eric Laurentddb78e72009-07-28 08:44:33 -0700741status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700742{
Eric Laurenta553c252009-07-17 12:17:14 -0700743 status_t result;
744
Steve Block71f2cf12011-10-20 11:56:00 +0100745 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700746 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
747 // check calling permissions
748 if (!settingsAllowed()) {
749 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800750 }
Eric Laurenta553c252009-07-17 12:17:14 -0700751
752 // ioHandle == 0 means the parameters are global to the audio hardware interface
753 if (ioHandle == 0) {
754 AutoMutex lock(mHardwareLock);
755 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700756 status_t final_result = NO_ERROR;
757 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
758 audio_hw_device_t *dev = mAudioHwDevs[i];
759 result = dev->set_parameters(dev, keyValuePairs.string());
760 final_result = result ?: final_result;
761 }
Eric Laurenta553c252009-07-17 12:17:14 -0700762 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700763 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
764 AudioParameter param = AudioParameter(keyValuePairs);
765 String8 value;
766 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
767 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700768 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
769 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700770 for (size_t i = 0; i < mRecordThreads.size(); i++) {
771 sp<RecordThread> thread = mRecordThreads.valueAt(i);
772 RecordThread::RecordTrack *track = thread->track();
773 if (track != NULL) {
774 audio_devices_t device = (audio_devices_t)(
775 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700776 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700777 thread->setEffectSuspended(FX_IID_AEC,
778 suspend,
779 track->sessionId());
780 thread->setEffectSuspended(FX_IID_NS,
781 suspend,
782 track->sessionId());
783 }
784 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700785 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700786 }
787 }
Dima Zavin31f188892011-04-18 16:57:27 -0700788 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700789 }
790
Eric Laurentb7d94602009-09-29 11:12:57 -0700791 // hold a strong ref on thread in case closeOutput() or closeInput() is called
792 // and the thread is exited once the lock is released
793 sp<ThreadBase> thread;
794 {
795 Mutex::Autolock _l(mLock);
796 thread = checkPlaybackThread_l(ioHandle);
797 if (thread == NULL) {
798 thread = checkRecordThread_l(ioHandle);
Glenn Kasten70ed6b72012-01-10 10:46:34 -0800799 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent464d5b32011-06-17 21:29:58 -0700800 // indicate output device change to all input threads for pre processing
801 AudioParameter param = AudioParameter(keyValuePairs);
802 int value;
803 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
804 for (size_t i = 0; i < mRecordThreads.size(); i++) {
805 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
806 }
807 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700808 }
Eric Laurenta553c252009-07-17 12:17:14 -0700809 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700810 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800811 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800812 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700813 }
Eric Laurenta553c252009-07-17 12:17:14 -0700814 return BAD_VALUE;
815}
816
Eric Laurentddb78e72009-07-28 08:44:33 -0700817String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700818{
Steve Block71f2cf12011-10-20 11:56:00 +0100819// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700820// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
821
822 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700823 String8 out_s8;
824
Dima Zavin31f188892011-04-18 16:57:27 -0700825 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
826 audio_hw_device_t *dev = mAudioHwDevs[i];
827 char *s = dev->get_parameters(dev, keys.string());
828 out_s8 += String8(s);
829 free(s);
830 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700831 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700832 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700833
834 Mutex::Autolock _l(mLock);
835
Eric Laurenta553c252009-07-17 12:17:14 -0700836 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
837 if (playbackThread != NULL) {
838 return playbackThread->getParameters(keys);
839 }
840 RecordThread *recordThread = checkRecordThread_l(ioHandle);
841 if (recordThread != NULL) {
842 return recordThread->getParameters(keys);
843 }
844 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700845}
846
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800847size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700849 status_t ret = initCheck();
850 if (ret != NO_ERROR) {
851 return 0;
852 }
853
Dima Zavin31f188892011-04-18 16:57:27 -0700854 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855}
856
Eric Laurent47d0a922010-02-26 02:47:27 -0800857unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
858{
859 if (ioHandle == 0) {
860 return 0;
861 }
862
863 Mutex::Autolock _l(mLock);
864
865 RecordThread *recordThread = checkRecordThread_l(ioHandle);
866 if (recordThread != NULL) {
867 return recordThread->getInputFramesLost();
868 }
869 return 0;
870}
871
Eric Laurent415f3e22009-10-21 08:14:22 -0700872status_t AudioFlinger::setVoiceVolume(float value)
873{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700874 status_t ret = initCheck();
875 if (ret != NO_ERROR) {
876 return ret;
877 }
878
Eric Laurent415f3e22009-10-21 08:14:22 -0700879 // check calling permissions
880 if (!settingsAllowed()) {
881 return PERMISSION_DENIED;
882 }
883
884 AutoMutex lock(mHardwareLock);
885 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700886 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700887 mHardwareStatus = AUDIO_HW_IDLE;
888
889 return ret;
890}
891
Eric Laurent0986e792010-01-19 17:37:09 -0800892status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
893{
894 status_t status;
895
896 Mutex::Autolock _l(mLock);
897
898 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
899 if (playbackThread != NULL) {
900 return playbackThread->getRenderPosition(halFrames, dspFrames);
901 }
902
903 return BAD_VALUE;
904}
905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
907{
Eric Laurenta553c252009-07-17 12:17:14 -0700908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 Mutex::Autolock _l(mLock);
910
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700911 int pid = IPCThreadState::self()->getCallingPid();
912 if (mNotificationClients.indexOfKey(pid) < 0) {
913 sp<NotificationClient> notificationClient = new NotificationClient(this,
914 client,
915 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100916 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700917
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700918 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700919
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700920 sp<IBinder> binder = client->asBinder();
921 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700923 // the config change is always sent from playback or record threads to avoid deadlock
924 // with AudioSystem::gLock
925 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
926 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
927 }
Eric Laurenta553c252009-07-17 12:17:14 -0700928
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700929 for (size_t i = 0; i < mRecordThreads.size(); i++) {
930 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932 }
933}
934
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700935void AudioFlinger::removeNotificationClient(pid_t pid)
936{
937 Mutex::Autolock _l(mLock);
938
939 int index = mNotificationClients.indexOfKey(pid);
940 if (index >= 0) {
941 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100942 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700943 mNotificationClients.removeItem(pid);
944 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700945
Steve Block71f2cf12011-10-20 11:56:00 +0100946 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700947 int num = mAudioSessionRefs.size();
948 bool removed = false;
949 for (int i = 0; i< num; i++) {
950 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100951 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700952 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100953 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700954 mAudioSessionRefs.removeAt(i);
955 delete ref;
956 removed = true;
957 i--;
958 num--;
959 }
960 }
961 if (removed) {
962 purgeStaleEffects_l();
963 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700964}
965
Eric Laurent296a0ec2009-09-15 07:10:12 -0700966// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700967void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
968{
Eric Laurent49f02be2009-11-19 09:00:56 -0800969 size_t size = mNotificationClients.size();
970 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700971 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700972 }
973}
974
Eric Laurentb9481d82009-09-17 05:12:56 -0700975// removeClient_l() must be called with AudioFlinger::mLock held
976void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700977{
Steve Block71f2cf12011-10-20 11:56:00 +0100978 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979 mClients.removeItem(pid);
980}
981
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700982
Eric Laurenta553c252009-07-17 12:17:14 -0700983// ----------------------------------------------------------------------------
984
Eric Laurent464d5b32011-06-17 21:29:58 -0700985AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700986 : Thread(false),
987 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800988 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), mStandby(false), mId(id), mExiting(false),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700989 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700990{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700991 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992}
993
Eric Laurenta553c252009-07-17 12:17:14 -0700994AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700996 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700997 // do not lock the mutex in destructor
998 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -0700999 if (mPowerManager != 0) {
1000 sp<IBinder> binder = mPowerManager->asBinder();
1001 binder->unlinkToDeath(mDeathRecipient);
1002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003}
1004
Eric Laurenta553c252009-07-17 12:17:14 -07001005void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001006{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001007 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001008 // destroyed in the middle of requestExitAndWait()
1009 sp <ThreadBase> strongMe = this;
1010
Steve Block71f2cf12011-10-20 11:56:00 +01001011 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001012 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08001013 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001014 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001015 requestExit();
1016 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001017 }
Eric Laurenta553c252009-07-17 12:17:14 -07001018 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001019}
Eric Laurenta553c252009-07-17 12:17:14 -07001020
1021uint32_t AudioFlinger::ThreadBase::sampleRate() const
1022{
1023 return mSampleRate;
1024}
1025
1026int AudioFlinger::ThreadBase::channelCount() const
1027{
Eric Laurentb0a01472010-05-14 05:45:46 -07001028 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001029}
1030
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001031audio_format_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001032{
1033 return mFormat;
1034}
1035
1036size_t AudioFlinger::ThreadBase::frameCount() const
1037{
1038 return mFrameCount;
1039}
1040
1041status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1042{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001043 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001044
Steve Block71f2cf12011-10-20 11:56:00 +01001045 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001046 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001047
Eric Laurent8fce46a2009-08-04 09:45:33 -07001048 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001049 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001050 // wait condition with timeout in case the thread loop has exited
1051 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001052 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001053 status = mParamStatus;
1054 mWaitWorkCV.signal();
1055 } else {
1056 status = TIMED_OUT;
1057 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001058 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001059}
1060
1061void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1062{
1063 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001064 sendConfigEvent_l(event, param);
1065}
1066
1067// sendConfigEvent_l() must be called with ThreadBase::mLock held
1068void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1069{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001070 ConfigEvent configEvent;
1071 configEvent.mEvent = event;
1072 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001073 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001074 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001075 mWaitWorkCV.signal();
1076}
1077
1078void AudioFlinger::ThreadBase::processConfigEvents()
1079{
1080 mLock.lock();
1081 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001082 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001083 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001084 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001085 // release mLock before locking AudioFlinger mLock: lock order is always
1086 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001087 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001088 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001089 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001090 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001091 mLock.lock();
1092 }
1093 mLock.unlock();
1094}
1095
Eric Laurent3fdb1262009-11-07 00:01:32 -08001096status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1097{
1098 const size_t SIZE = 256;
1099 char buffer[SIZE];
1100 String8 result;
1101
1102 bool locked = tryLock(mLock);
1103 if (!locked) {
1104 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1105 write(fd, buffer, strlen(buffer));
1106 }
1107
1108 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1113 result.append(buffer);
1114 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1115 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001116 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1117 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001118 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1119 result.append(buffer);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001120 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001121 result.append(buffer);
1122
1123 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1124 result.append(buffer);
1125 result.append(" Index Command");
1126 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1127 snprintf(buffer, SIZE, "\n %02d ", i);
1128 result.append(buffer);
1129 result.append(mNewParameters[i]);
1130 }
1131
1132 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1133 result.append(buffer);
1134 snprintf(buffer, SIZE, " Index event param\n");
1135 result.append(buffer);
1136 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001137 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001138 result.append(buffer);
1139 }
1140 result.append("\n");
1141
1142 write(fd, result.string(), result.size());
1143
1144 if (locked) {
1145 mLock.unlock();
1146 }
1147 return NO_ERROR;
1148}
1149
Eric Laurent1345d332011-07-24 17:49:51 -07001150status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1151{
1152 const size_t SIZE = 256;
1153 char buffer[SIZE];
1154 String8 result;
1155
1156 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1157 write(fd, buffer, strlen(buffer));
1158
1159 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1160 sp<EffectChain> chain = mEffectChains[i];
1161 if (chain != 0) {
1162 chain->dump(fd, args);
1163 }
1164 }
1165 return NO_ERROR;
1166}
1167
Eric Laurent6dbdc402011-07-22 09:04:31 -07001168void AudioFlinger::ThreadBase::acquireWakeLock()
1169{
1170 Mutex::Autolock _l(mLock);
1171 acquireWakeLock_l();
1172}
1173
1174void AudioFlinger::ThreadBase::acquireWakeLock_l()
1175{
1176 if (mPowerManager == 0) {
1177 // use checkService() to avoid blocking if power service is not up yet
1178 sp<IBinder> binder =
1179 defaultServiceManager()->checkService(String16("power"));
1180 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001181 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001182 } else {
1183 mPowerManager = interface_cast<IPowerManager>(binder);
1184 binder->linkToDeath(mDeathRecipient);
1185 }
1186 }
1187 if (mPowerManager != 0) {
1188 sp<IBinder> binder = new BBinder();
1189 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1190 binder,
1191 String16(mName));
1192 if (status == NO_ERROR) {
1193 mWakeLockToken = binder;
1194 }
Steve Block71f2cf12011-10-20 11:56:00 +01001195 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001196 }
1197}
1198
1199void AudioFlinger::ThreadBase::releaseWakeLock()
1200{
1201 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001202 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001203}
1204
1205void AudioFlinger::ThreadBase::releaseWakeLock_l()
1206{
1207 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001208 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001209 if (mPowerManager != 0) {
1210 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1211 }
1212 mWakeLockToken.clear();
1213 }
1214}
1215
1216void AudioFlinger::ThreadBase::clearPowerManager()
1217{
1218 Mutex::Autolock _l(mLock);
1219 releaseWakeLock_l();
1220 mPowerManager.clear();
1221}
1222
1223void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1224{
1225 sp<ThreadBase> thread = mThread.promote();
1226 if (thread != 0) {
1227 thread->clearPowerManager();
1228 }
Steve Block8564c8d2012-01-05 23:22:43 +00001229 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001230}
Eric Laurent1345d332011-07-24 17:49:51 -07001231
Eric Laurentf82fccd2011-07-27 19:49:51 -07001232void AudioFlinger::ThreadBase::setEffectSuspended(
1233 const effect_uuid_t *type, bool suspend, int sessionId)
1234{
1235 Mutex::Autolock _l(mLock);
1236 setEffectSuspended_l(type, suspend, sessionId);
1237}
1238
1239void AudioFlinger::ThreadBase::setEffectSuspended_l(
1240 const effect_uuid_t *type, bool suspend, int sessionId)
1241{
1242 sp<EffectChain> chain;
1243 chain = getEffectChain_l(sessionId);
1244 if (chain != 0) {
1245 if (type != NULL) {
1246 chain->setEffectSuspended_l(type, suspend);
1247 } else {
1248 chain->setEffectSuspendedAll_l(suspend);
1249 }
1250 }
1251
1252 updateSuspendedSessions_l(type, suspend, sessionId);
1253}
1254
1255void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1256{
1257 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1258 if (index < 0) {
1259 return;
1260 }
1261
1262 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1263 mSuspendedSessions.editValueAt(index);
1264
1265 for (size_t i = 0; i < sessionEffects.size(); i++) {
1266 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1267 for (int j = 0; j < desc->mRefCount; j++) {
1268 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1269 chain->setEffectSuspendedAll_l(true);
1270 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001271 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001272 desc->mType.timeLow);
1273 chain->setEffectSuspended_l(&desc->mType, true);
1274 }
1275 }
1276 }
1277}
1278
Eric Laurentf82fccd2011-07-27 19:49:51 -07001279void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1280 bool suspend,
1281 int sessionId)
1282{
1283 int index = mSuspendedSessions.indexOfKey(sessionId);
1284
1285 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1286
1287 if (suspend) {
1288 if (index >= 0) {
1289 sessionEffects = mSuspendedSessions.editValueAt(index);
1290 } else {
1291 mSuspendedSessions.add(sessionId, sessionEffects);
1292 }
1293 } else {
1294 if (index < 0) {
1295 return;
1296 }
1297 sessionEffects = mSuspendedSessions.editValueAt(index);
1298 }
1299
1300
1301 int key = EffectChain::kKeyForSuspendAll;
1302 if (type != NULL) {
1303 key = type->timeLow;
1304 }
1305 index = sessionEffects.indexOfKey(key);
1306
1307 sp <SuspendedSessionDesc> desc;
1308 if (suspend) {
1309 if (index >= 0) {
1310 desc = sessionEffects.valueAt(index);
1311 } else {
1312 desc = new SuspendedSessionDesc();
1313 if (type != NULL) {
1314 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1315 }
1316 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001317 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001318 }
1319 desc->mRefCount++;
1320 } else {
1321 if (index < 0) {
1322 return;
1323 }
1324 desc = sessionEffects.valueAt(index);
1325 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001326 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001327 sessionEffects.removeItemsAt(index);
1328 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001329 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001330 sessionId);
1331 mSuspendedSessions.removeItem(sessionId);
1332 }
1333 }
1334 }
1335 if (!sessionEffects.isEmpty()) {
1336 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1337 }
1338}
1339
1340void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1341 bool enabled,
1342 int sessionId)
1343{
1344 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001345 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1346}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001347
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001348void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1349 bool enabled,
1350 int sessionId)
1351{
Eric Laurent6752ec82011-08-10 10:37:50 -07001352 if (mType != RECORD) {
1353 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1354 // another session. This gives the priority to well behaved effect control panels
1355 // and applications not using global effects.
1356 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1357 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1358 }
1359 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001360
1361 sp<EffectChain> chain = getEffectChain_l(sessionId);
1362 if (chain != 0) {
1363 chain->checkSuspendOnEffectEnabled(effect, enabled);
1364 }
1365}
1366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367// ----------------------------------------------------------------------------
1368
Eric Laurent464d5b32011-06-17 21:29:58 -07001369AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1370 AudioStreamOut* output,
1371 int id,
1372 uint32_t device)
1373 : ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001374 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001375 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001377 snprintf(mName, kNameLength, "AudioOut_%d", id);
1378
Eric Laurenta553c252009-07-17 12:17:14 -07001379 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380
Glenn Kastene6f8a422011-12-13 11:47:54 -08001381 // Assumes constructor is called by AudioFlinger with it's mLock held,
1382 // but it would be safer to explicitly pass these as parameters
1383 mMasterVolume = mAudioFlinger->masterVolume_l();
1384 mMasterMute = mAudioFlinger->masterMute_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001385
Glenn Kasten6e987a42012-01-06 08:40:01 -08001386 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001387 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1388 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1389 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001390 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1391 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten6e987a42012-01-06 08:40:01 -08001392 // initialized by stream_type_t default constructor
1393 // mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395}
1396
Eric Laurenta553c252009-07-17 12:17:14 -07001397AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398{
1399 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400}
1401
Eric Laurenta553c252009-07-17 12:17:14 -07001402status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403{
1404 dumpInternals(fd, args);
1405 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001406 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 return NO_ERROR;
1408}
1409
Eric Laurenta553c252009-07-17 12:17:14 -07001410status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411{
1412 const size_t SIZE = 256;
1413 char buffer[SIZE];
1414 String8 result;
1415
Eric Laurenta553c252009-07-17 12:17:14 -07001416 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001418 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001420 sp<Track> track = mTracks[i];
1421 if (track != 0) {
1422 track->dump(buffer, SIZE);
1423 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425 }
1426
Eric Laurenta553c252009-07-17 12:17:14 -07001427 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001429 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -08001431 sp<Track> track = mActiveTracks[i].promote();
1432 if (track != 0) {
1433 track->dump(buffer, SIZE);
1434 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436 }
1437 write(fd, result.string(), result.size());
1438 return NO_ERROR;
1439}
1440
Eric Laurenta553c252009-07-17 12:17:14 -07001441status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442{
1443 const size_t SIZE = 256;
1444 char buffer[SIZE];
1445 String8 result;
1446
Eric Laurent3fdb1262009-11-07 00:01:32 -08001447 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 result.append(buffer);
1449 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1456 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001457 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1458 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001459 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1460 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001462
1463 dumpBase(fd, args);
1464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 return NO_ERROR;
1466}
1467
1468// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001469status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470{
Eric Laurent828b9772011-08-07 16:32:26 -07001471 status_t status = initCheck();
1472 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001473 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001474 } else {
Steve Block3762c312012-01-06 19:20:56 +00001475 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
Eric Laurent828b9772011-08-07 16:32:26 -07001477 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478}
1479
Eric Laurenta553c252009-07-17 12:17:14 -07001480void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001482 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483}
1484
Eric Laurenta553c252009-07-17 12:17:14 -07001485// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1486sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001488 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001490 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001491 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 int frameCount,
1493 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001494 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 status_t *status)
1496{
1497 sp<Track> track;
1498 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001499
1500 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001501 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1502 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001503 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001504 "for output %p with format %d",
1505 sampleRate, format, channelMask, mOutput, mFormat);
1506 lStatus = BAD_VALUE;
1507 goto Exit;
1508 }
Eric Laurenta553c252009-07-17 12:17:14 -07001509 }
1510 } else {
1511 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1512 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001513 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001514 lStatus = BAD_VALUE;
1515 goto Exit;
1516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518
Eric Laurent464d5b32011-06-17 21:29:58 -07001519 lStatus = initCheck();
1520 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001521 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001522 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524
Eric Laurenta553c252009-07-17 12:17:14 -07001525 { // scope for mLock
1526 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001527
1528 // all tracks in same audio session must share the same routing strategy otherwise
1529 // conflicts will happen when tracks are moved from one output to another by audio policy
1530 // manager
1531 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001532 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001533 for (size_t i = 0; i < mTracks.size(); ++i) {
1534 sp<Track> t = mTracks[i];
1535 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001536 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1537 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001538 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001539 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001540 lStatus = BAD_VALUE;
1541 goto Exit;
1542 }
1543 }
1544 }
1545
Eric Laurenta553c252009-07-17 12:17:14 -07001546 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001547 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001548 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001549 lStatus = NO_MEMORY;
1550 goto Exit;
1551 }
1552 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001553
1554 sp<EffectChain> chain = getEffectChain_l(sessionId);
1555 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001556 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001557 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001558 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001559 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001560 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001561
1562 // invalidate track immediately if the stream type was moved to another thread since
1563 // createTrack() was called by the client process.
1564 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001565 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001566 this, streamType);
1567 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1568 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001569 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001570 lStatus = NO_ERROR;
1571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572Exit:
1573 if(status) {
1574 *status = lStatus;
1575 }
1576 return track;
1577}
1578
Eric Laurenta553c252009-07-17 12:17:14 -07001579uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580{
Eric Laurent828b9772011-08-07 16:32:26 -07001581 Mutex::Autolock _l(mLock);
1582 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001583 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001584 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 return 0;
1586 }
1587}
1588
Eric Laurenta553c252009-07-17 12:17:14 -07001589status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590{
1591 mMasterVolume = value;
1592 return NO_ERROR;
1593}
1594
Eric Laurenta553c252009-07-17 12:17:14 -07001595status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596{
1597 mMasterMute = muted;
1598 return NO_ERROR;
1599}
1600
Eric Laurenta553c252009-07-17 12:17:14 -07001601float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602{
1603 return mMasterVolume;
1604}
1605
Eric Laurenta553c252009-07-17 12:17:14 -07001606bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607{
1608 return mMasterMute;
1609}
1610
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001611status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612{
1613 mStreamTypes[stream].volume = value;
1614 return NO_ERROR;
1615}
1616
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001617status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618{
1619 mStreamTypes[stream].mute = muted;
1620 return NO_ERROR;
1621}
1622
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001623float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624{
1625 return mStreamTypes[stream].volume;
1626}
1627
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001628bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629{
1630 return mStreamTypes[stream].mute;
1631}
1632
Eric Laurenta553c252009-07-17 12:17:14 -07001633// addTrack_l() must be called with ThreadBase::mLock held
1634status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635{
1636 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001637
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001638 // set retry count for buffer fill
1639 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001640 if (mActiveTracks.indexOf(track) < 0) {
1641 // the track is newly added, make sure it fills up all its
1642 // buffers before playing. This is to ensure the client will
1643 // effectively get the latency it requested.
1644 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001645 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001646 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001647 if (track->mainBuffer() != mMixBuffer) {
1648 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1649 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001650 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001651 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001652 }
1653 }
1654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001656 }
Eric Laurenta553c252009-07-17 12:17:14 -07001657
Steve Block71f2cf12011-10-20 11:56:00 +01001658 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001659 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660
1661 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001662}
1663
Eric Laurenta553c252009-07-17 12:17:14 -07001664// destroyTrack_l() must be called with ThreadBase::mLock held
1665void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001666{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001667 track->mState = TrackBase::TERMINATED;
1668 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001669 removeTrack_l(track);
1670 }
1671}
1672
1673void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1674{
1675 mTracks.remove(track);
1676 deleteTrackName_l(track->name());
1677 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1678 if (chain != 0) {
1679 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001680 }
1681}
1682
Eric Laurenta553c252009-07-17 12:17:14 -07001683String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001684{
Eric Laurent828b9772011-08-07 16:32:26 -07001685 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001686 char *s;
1687
Eric Laurent828b9772011-08-07 16:32:26 -07001688 Mutex::Autolock _l(mLock);
1689 if (initCheck() != NO_ERROR) {
1690 return out_s8;
1691 }
1692
Dima Zavin31f188892011-04-18 16:57:27 -07001693 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001694 out_s8 = String8(s);
1695 free(s);
1696 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001697}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001698
Eric Laurent828b9772011-08-07 16:32:26 -07001699// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001700void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001701 AudioSystem::OutputDescriptor desc;
1702 void *param2 = 0;
1703
Steve Block71f2cf12011-10-20 11:56:00 +01001704 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001705
1706 switch (event) {
1707 case AudioSystem::OUTPUT_OPENED:
1708 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001709 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001710 desc.samplingRate = mSampleRate;
1711 desc.format = mFormat;
1712 desc.frameCount = mFrameCount;
1713 desc.latency = latency();
1714 param2 = &desc;
1715 break;
1716
1717 case AudioSystem::STREAM_CONFIG_CHANGED:
1718 param2 = &param;
1719 case AudioSystem::OUTPUT_CLOSED:
1720 default:
1721 break;
1722 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001723 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001724}
1725
1726void AudioFlinger::PlaybackThread::readOutputParameters()
1727{
Dima Zavin31f188892011-04-18 16:57:27 -07001728 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001729 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1730 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001731 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001732 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07001733 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001734
Eric Laurenta553c252009-07-17 12:17:14 -07001735 // FIXME - Current mixer implementation only supports stereo output: Always
1736 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001737 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001738 mMixBuffer = new int16_t[mFrameCount * 2];
1739 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001740
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001741 // force reconfiguration of effect chains and engines to take new buffer size and audio
1742 // parameters into account
1743 // Note that mLock is not held when readOutputParameters() is called from the constructor
1744 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1745 // matter.
1746 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1747 Vector< sp<EffectChain> > effectChains = mEffectChains;
1748 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001749 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001750 }
Eric Laurenta553c252009-07-17 12:17:14 -07001751}
1752
Eric Laurent0986e792010-01-19 17:37:09 -08001753status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1754{
1755 if (halFrames == 0 || dspFrames == 0) {
1756 return BAD_VALUE;
1757 }
Eric Laurent828b9772011-08-07 16:32:26 -07001758 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001759 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001760 return INVALID_OPERATION;
1761 }
Dima Zavin31f188892011-04-18 16:57:27 -07001762 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001763
Dima Zavin31f188892011-04-18 16:57:27 -07001764 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001765}
1766
Eric Laurent493941b2010-07-28 01:32:47 -07001767uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001768{
1769 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001770 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001771 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001772 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001773 }
1774
1775 for (size_t i = 0; i < mTracks.size(); ++i) {
1776 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001777 if (sessionId == track->sessionId() &&
1778 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001779 result |= TRACK_SESSION;
1780 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001781 }
1782 }
1783
Eric Laurent493941b2010-07-28 01:32:47 -07001784 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001785}
1786
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001787uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1788{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001789 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001790 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001791 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1792 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001793 }
1794 for (size_t i = 0; i < mTracks.size(); i++) {
1795 sp<Track> track = mTracks[i];
1796 if (sessionId == track->sessionId() &&
1797 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001798 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001799 }
1800 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001801 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001802}
1803
Eric Laurent53334cd2010-06-23 17:38:20 -07001804
Glenn Kasten5b0135e2012-01-26 09:46:34 -08001805AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent828b9772011-08-07 16:32:26 -07001806{
1807 Mutex::Autolock _l(mLock);
1808 return mOutput;
1809}
1810
1811AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1812{
1813 Mutex::Autolock _l(mLock);
1814 AudioStreamOut *output = mOutput;
1815 mOutput = NULL;
1816 return output;
1817}
1818
1819// this method must always be called either with ThreadBase mLock held or inside the thread loop
1820audio_stream_t* AudioFlinger::PlaybackThread::stream()
1821{
1822 if (mOutput == NULL) {
1823 return NULL;
1824 }
1825 return &mOutput->stream->common;
1826}
1827
Eric Laurent44331692011-12-05 09:47:19 -08001828uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1829{
1830 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1831 // decoding and transfer time. So sleeping for half of the latency would likely cause
1832 // underruns
1833 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1834 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1835 } else {
1836 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1837 }
1838}
1839
Eric Laurenta553c252009-07-17 12:17:14 -07001840// ----------------------------------------------------------------------------
1841
Dima Zavin31f188892011-04-18 16:57:27 -07001842AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001843 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurent35629312012-01-19 10:00:02 -08001844 mAudioMixer(NULL), mPrevMixerStatus(MIXER_IDLE)
Eric Laurenta553c252009-07-17 12:17:14 -07001845{
Eric Laurent464d5b32011-06-17 21:29:58 -07001846 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001847 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1848
1849 // FIXME - Current mixer implementation only supports stereo output
1850 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001851 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001853}
1854
Eric Laurenta553c252009-07-17 12:17:14 -07001855AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001856{
Eric Laurenta553c252009-07-17 12:17:14 -07001857 delete mAudioMixer;
1858}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859
Eric Laurenta553c252009-07-17 12:17:14 -07001860bool AudioFlinger::MixerThread::threadLoop()
1861{
Eric Laurenta553c252009-07-17 12:17:14 -07001862 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08001863 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001864 nsecs_t standbyTime = systemTime();
1865 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001866 // FIXME: Relaxed timing because of a certain device that can't meet latency
1867 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001868 // increase threshold again due to low power audio mode. The way this warning threshold is
1869 // calculated and its usefulness should be reconsidered anyway.
1870 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001871 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001872 bool longStandbyExit = false;
1873 uint32_t activeSleepTime = activeSleepTimeUs();
1874 uint32_t idleSleepTime = idleSleepTimeUs();
1875 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001876 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001877 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001878#ifdef DEBUG_CPU_USAGE
1879 ThreadCpuUsage cpu;
1880 const CentralTendencyStatistics& stats = cpu.statistics();
1881#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882
Eric Laurent6dbdc402011-07-22 09:04:31 -07001883 acquireWakeLock();
1884
Eric Laurenta553c252009-07-17 12:17:14 -07001885 while (!exitPending())
1886 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001887#ifdef DEBUG_CPU_USAGE
1888 cpu.sampleAndEnable();
1889 unsigned n = stats.n();
1890 // cpu.elapsed() is expensive, so don't call it every loop
1891 if ((n & 127) == 1) {
1892 long long elapsed = cpu.elapsed();
1893 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1894 double perLoop = elapsed / (double) n;
1895 double perLoop100 = perLoop * 0.01;
1896 double mean = stats.mean();
1897 double stddev = stats.stddev();
1898 double minimum = stats.minimum();
1899 double maximum = stats.maximum();
1900 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001901 ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
Glenn Kastenda494f92011-07-08 15:26:12 -07001902 elapsed * .000000001, n, perLoop * .000001,
1903 mean * .001,
1904 stddev * .001,
1905 minimum * .001,
1906 maximum * .001,
1907 mean / perLoop100,
1908 stddev / perLoop100,
1909 minimum / perLoop100,
1910 maximum / perLoop100);
1911 }
1912 }
1913#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001914 processConfigEvents();
1915
Eric Laurent059b4be2009-11-09 23:32:22 -08001916 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001917 { // scope for mLock
1918
1919 Mutex::Autolock _l(mLock);
1920
1921 if (checkForNewParameters_l()) {
1922 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001923 // FIXME: Relaxed timing because of a certain device that can't meet latency
1924 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001925 // increase threshold again due to low power audio mode. The way this warning
1926 // threshold is calculated and its usefulness should be reconsidered anyway.
1927 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001928 activeSleepTime = activeSleepTimeUs();
1929 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001930 }
1931
1932 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1933
1934 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001935 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1936 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001937 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001938 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001939 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001940 mStandby = true;
1941 mBytesWritten = 0;
1942 }
1943
1944 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1945 // we're about to wait, flush the binder command buffer
1946 IPCThreadState::self()->flushCommands();
1947
1948 if (exitPending()) break;
1949
Eric Laurent6dbdc402011-07-22 09:04:31 -07001950 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001951 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001952 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001953 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001954 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001955 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001956
Eric Laurent71c44962012-01-17 19:20:12 -08001957 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08001958 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07001959 char value[PROPERTY_VALUE_MAX];
1960 property_get("ro.audio.silent", value, "0");
1961 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001962 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001963 setMasterMute(true);
1964 }
1965 }
1966
1967 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001968 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001969 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001970 continue;
1971 }
1972 }
1973
Eric Laurent059b4be2009-11-09 23:32:22 -08001974 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001975
1976 // prevent any changes in effect chain list and in each effect chain
1977 // during mixing and effect process as the audio buffers could be deleted
1978 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001979 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001980 }
Eric Laurenta553c252009-07-17 12:17:14 -07001981
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001982 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001983 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001984 mAudioMixer->process();
Eric Laurent06092312012-01-23 18:56:59 -08001985 // increase sleep time progressively when application underrun condition clears.
1986 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1987 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1988 // such that we would underrun the audio HAL.
1989 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001990 sleepTimeShift--;
1991 }
Eric Laurent06092312012-01-23 18:56:59 -08001992 sleepTime = 0;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001993 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001994 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001995 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001996 // If no tracks are ready, sleep once for the duration of an output
1997 // buffer size, then write 0s to the output
1998 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001999 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08002000 sleepTime = activeSleepTime >> sleepTimeShift;
2001 if (sleepTime < kMinThreadSleepTimeUs) {
2002 sleepTime = kMinThreadSleepTimeUs;
2003 }
2004 // reduce sleep time in case of consecutive application underruns to avoid
2005 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2006 // duration we would end up writing less data than needed by the audio HAL if
2007 // the condition persists.
2008 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2009 sleepTimeShift++;
2010 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002011 } else {
2012 sleepTime = idleSleepTime;
2013 }
2014 } else if (mBytesWritten != 0 ||
2015 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002016 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002017 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002018 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002019 }
Eric Laurent65b65452010-06-01 23:49:17 -07002020 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002021 }
2022
2023 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002024 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002025 }
2026 // sleepTime == 0 means we must write to audio hardware
2027 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002028 for (size_t i = 0; i < effectChains.size(); i ++) {
2029 effectChains[i]->process_l();
2030 }
2031 // enable changes in effect chain
2032 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002033 mLastWriteTime = systemTime();
2034 mInWrite = true;
2035 mBytesWritten += mixBufferSize;
2036
Dima Zavin31f188892011-04-18 16:57:27 -07002037 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002038 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002039 mNumWrites++;
2040 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002041 nsecs_t now = systemTime();
2042 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002043 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002044 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002045 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00002046 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002047 ns2ms(delta), mNumDelayedWrites, this);
2048 lastWarning = now;
2049 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002050 if (mStandby) {
2051 longStandbyExit = true;
2052 }
Eric Laurenta553c252009-07-17 12:17:14 -07002053 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002054 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002055 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002056 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002057 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002058 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002059 }
2060
2061 // finally let go of all our tracks, without the lock held
2062 // since we can't guarantee the destructors won't acquire that
2063 // same lock.
2064 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002065
2066 // Effect chains will be actually deleted here if they were removed from
2067 // mEffectChains list during mixing or effects processing
2068 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002069 }
2070
2071 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002072 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002073 }
Eric Laurenta553c252009-07-17 12:17:14 -07002074
Eric Laurent6dbdc402011-07-22 09:04:31 -07002075 releaseWakeLock();
2076
Steve Block71f2cf12011-10-20 11:56:00 +01002077 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002078 return false;
2079}
2080
2081// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten789fef12012-01-26 13:37:52 -08002082AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2083 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002084{
2085
Glenn Kasten789fef12012-01-26 13:37:52 -08002086 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002087 // find out which tracks need to be processed
2088 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002089 size_t mixedTracks = 0;
2090 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002091
2092 float masterVolume = mMasterVolume;
2093 bool masterMute = mMasterMute;
2094
Eric Laurent8cc93b92010-08-11 05:20:11 -07002095 if (masterMute) {
2096 masterVolume = 0;
2097 }
Eric Laurent65b65452010-06-01 23:49:17 -07002098 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002099 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002100 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002101 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002102 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002103 masterVolume = (float)((v + (1 << 23)) >> 24);
2104 chain.clear();
2105 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002106
Eric Laurenta553c252009-07-17 12:17:14 -07002107 for (size_t i=0 ; i<count ; i++) {
2108 sp<Track> t = activeTracks[i].promote();
2109 if (t == 0) continue;
2110
Glenn Kasten68deb152011-12-19 15:06:39 -08002111 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002112 Track* const track = t.get();
2113 audio_track_cblk_t* cblk = track->cblk();
2114
2115 // The first time a track is added we wait
2116 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002117 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002118 // make sure that we have enough frames to mix one full buffer.
2119 // enforce this condition only once to enable draining the buffer in case the client
2120 // app does not call stop() and relies on underrun to stop:
Eric Laurent71c44962012-01-17 19:20:12 -08002121 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002122 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002123 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002124 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent71c44962012-01-17 19:20:12 -08002125 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002126 if (t->sampleRate() == (int)mSampleRate) {
2127 minFrames = mFrameCount;
2128 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002129 // +1 for rounding and +1 for additional sample needed for interpolation
2130 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2131 // add frames already consumed but not yet released by the resampler
2132 // because cblk->framesReady() will include these frames
2133 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2134 // the minimum track buffer size is normally twice the number of frames necessary
2135 // to fill one buffer and the resampler should not leave more than one buffer worth
2136 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002137 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002138 }
2139 }
2140 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002141 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002142 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002143 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002144
Eric Laurent65b65452010-06-01 23:49:17 -07002145 mixedTracks++;
2146
2147 // track->mainBuffer() != mMixBuffer means there is an effect chain
2148 // connected to the track
2149 chain.clear();
2150 if (track->mainBuffer() != mMixBuffer) {
2151 chain = getEffectChain_l(track->sessionId());
2152 // Delegate volume control to effect in track effect chain if needed
2153 if (chain != 0) {
2154 tracksWithEffect++;
2155 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002156 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002157 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002158 }
2159 }
2160
2161
2162 int param = AudioMixer::VOLUME;
2163 if (track->mFillingUpStatus == Track::FS_FILLED) {
2164 // no ramp for the first volume setting
2165 track->mFillingUpStatus = Track::FS_ACTIVE;
2166 if (track->mState == TrackBase::RESUMING) {
2167 track->mState = TrackBase::ACTIVE;
2168 param = AudioMixer::RAMP_VOLUME;
2169 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002170 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002171 } else if (cblk->server != 0) {
2172 // If the track is stopped before the first frame was mixed,
2173 // do not apply ramp
2174 param = AudioMixer::RAMP_VOLUME;
2175 }
2176
Eric Laurenta553c252009-07-17 12:17:14 -07002177 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002178 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002179 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002180 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002181 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002182 if (track->isPausing()) {
2183 track->setPaused();
2184 }
2185 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002186
Glenn Kasten871c16c2010-03-05 12:18:01 -08002187 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002188 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002189 float v = masterVolume * typeVolume;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002190 uint32_t vlr = cblk->volumeLR;
2191 vl = vlr & 0xFFFF;
2192 vr = vlr >> 16;
2193 // track volumes come from shared memory, so can't be trusted and must be clamped
2194 if (vl > MAX_GAIN_INT) {
2195 ALOGV("Track left volume out of range: %04X", vl);
2196 vl = MAX_GAIN_INT;
2197 }
2198 if (vr > MAX_GAIN_INT) {
2199 ALOGV("Track right volume out of range: %04X", vr);
2200 vr = MAX_GAIN_INT;
2201 }
2202 // now apply the master volume and stream type volume
2203 vl = (uint32_t)(v * vl) << 12;
2204 vr = (uint32_t)(v * vr) << 12;
2205 // assuming master volume and stream type volume each go up to 1.0,
2206 // vl and vr are now in 8.24 format
Eric Laurenta553c252009-07-17 12:17:14 -07002207
Glenn Kasten4790bd82012-01-03 14:22:33 -08002208 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2209 // send level comes from shared memory and so may be corrupt
Glenn Kasten0632bad2012-01-17 12:20:54 -08002210 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten4790bd82012-01-03 14:22:33 -08002211 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kasten0632bad2012-01-17 12:20:54 -08002212 sendLevel = MAX_GAIN_INT;
Glenn Kasten4790bd82012-01-03 14:22:33 -08002213 }
2214 va = (uint32_t)(v * sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002215 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002216 // Delegate volume control to effect in track effect chain if needed
2217 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2218 // Do not ramp volume if volume is controlled by effect
2219 param = AudioMixer::VOLUME;
2220 track->mHasVolumeController = true;
2221 } else {
2222 // force no volume ramp when volume controller was just disabled or removed
2223 // from effect chain to avoid volume spike
2224 if (track->mHasVolumeController) {
2225 param = AudioMixer::VOLUME;
2226 }
2227 track->mHasVolumeController = false;
2228 }
2229
2230 // Convert volumes from 8.24 to 4.12 format
2231 int16_t left, right, aux;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002232 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002233 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2234 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2235 left = int16_t(v_clamped);
2236 v_clamped = (vr + (1 << 11)) >> 12;
2237 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2238 right = int16_t(v_clamped);
2239
2240 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2241 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002242
Eric Laurent65b65452010-06-01 23:49:17 -07002243 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002244 mAudioMixer->setBufferProvider(name, track);
2245 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002246
Glenn Kasten68deb152011-12-19 15:06:39 -08002247 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2248 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2249 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002250 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002251 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002252 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002253 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002254 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002255 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002256 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002257 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002258 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002259 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002260 AudioMixer::RESAMPLE,
2261 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002262 (void *)(cblk->sampleRate));
2263 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002264 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002265 AudioMixer::TRACK,
2266 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2267 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002268 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002269 AudioMixer::TRACK,
2270 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002271
2272 // reset retry count
2273 track->mRetryCount = kMaxTrackRetries;
Eric Laurent71c44962012-01-17 19:20:12 -08002274 // If one track is ready, set the mixer ready if:
2275 // - the mixer was not ready during previous round OR
2276 // - no other track is not ready
2277 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2278 mixerStatus != MIXER_TRACKS_ENABLED) {
2279 mixerStatus = MIXER_TRACKS_READY;
2280 }
Eric Laurenta553c252009-07-17 12:17:14 -07002281 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002282 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002283 if (track->isStopped()) {
2284 track->reset();
2285 }
2286 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2287 // We have consumed all the buffers of this track.
2288 // Remove it from the list of active tracks.
2289 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002290 } else {
2291 // No buffers for this track. Give it a few chances to
2292 // fill a buffer, then remove it from active list.
2293 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002294 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002295 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002296 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002297 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent71c44962012-01-17 19:20:12 -08002298 // If one track is not ready, mark the mixer also not ready if:
2299 // - the mixer was ready during previous round OR
2300 // - no other track is ready
2301 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2302 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002303 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002304 }
Eric Laurenta553c252009-07-17 12:17:14 -07002305 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002306 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002307 }
2308 }
2309
2310 // remove all the tracks that need to be...
2311 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002312 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002313 for (size_t i=0 ; i<count ; i++) {
2314 const sp<Track>& track = tracksToRemove->itemAt(i);
2315 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002316 if (track->mainBuffer() != mMixBuffer) {
2317 chain = getEffectChain_l(track->sessionId());
2318 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002319 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002320 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002321 }
2322 }
Eric Laurenta553c252009-07-17 12:17:14 -07002323 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002324 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002325 }
2326 }
2327 }
2328
Eric Laurent65b65452010-06-01 23:49:17 -07002329 // mix buffer must be cleared if all tracks are connected to an
2330 // effect chain as in this case the mixer will not write to
2331 // mix buffer and track effects will accumulate into it
2332 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2333 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2334 }
2335
Eric Laurent71c44962012-01-17 19:20:12 -08002336 mPrevMixerStatus = mixerStatus;
Eric Laurent059b4be2009-11-09 23:32:22 -08002337 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002338}
2339
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002340void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002341{
Steve Block71f2cf12011-10-20 11:56:00 +01002342 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002343 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002344 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002345
Eric Laurenta553c252009-07-17 12:17:14 -07002346 size_t size = mTracks.size();
2347 for (size_t i = 0; i < size; i++) {
2348 sp<Track> t = mTracks[i];
2349 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002350 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002351 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002352 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002353 }
2354}
Eric Laurenta553c252009-07-17 12:17:14 -07002355
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002356void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002357{
Steve Block71f2cf12011-10-20 11:56:00 +01002358 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002359 this, streamType, valid);
2360 Mutex::Autolock _l(mLock);
2361
2362 mStreamTypes[streamType].valid = valid;
2363}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364
Eric Laurenta553c252009-07-17 12:17:14 -07002365// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002366int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367{
2368 return mAudioMixer->getTrackName();
2369}
2370
Eric Laurenta553c252009-07-17 12:17:14 -07002371// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002372void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373{
Steve Block71f2cf12011-10-20 11:56:00 +01002374 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 mAudioMixer->deleteTrackName(name);
2376}
2377
Eric Laurenta553c252009-07-17 12:17:14 -07002378// checkForNewParameters_l() must be called with ThreadBase::mLock held
2379bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380{
Eric Laurenta553c252009-07-17 12:17:14 -07002381 bool reconfig = false;
2382
Eric Laurent8fce46a2009-08-04 09:45:33 -07002383 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002384 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002385 String8 keyValuePair = mNewParameters[0];
2386 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002387 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002388
Eric Laurenta553c252009-07-17 12:17:14 -07002389 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2390 reconfig = true;
2391 }
2392 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08002393 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002394 status = BAD_VALUE;
2395 } else {
2396 reconfig = true;
2397 }
2398 }
2399 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002400 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002401 status = BAD_VALUE;
2402 } else {
2403 reconfig = true;
2404 }
2405 }
2406 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2407 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002408 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002409 // if frame count is changed after track creation
2410 if (!mTracks.isEmpty()) {
2411 status = INVALID_OPERATION;
2412 } else {
2413 reconfig = true;
2414 }
2415 }
Eric Laurent65b65452010-06-01 23:49:17 -07002416 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002417 // when changing the audio output device, call addBatteryData to notify
2418 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002419 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002420 uint32_t params = 0;
2421 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002422 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002423 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2424 }
2425
2426 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002427 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002428 // check if any other device (except speaker) is on
2429 if (value & deviceWithoutSpeaker ) {
2430 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2431 }
2432
2433 if (params != 0) {
2434 addBatteryData(params);
2435 }
2436 }
2437
Eric Laurent65b65452010-06-01 23:49:17 -07002438 // forward device change to effects that have requested to be
2439 // aware of attached audio device.
2440 mDevice = (uint32_t)value;
2441 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002442 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002443 }
2444 }
2445
Eric Laurenta553c252009-07-17 12:17:14 -07002446 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002447 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002448 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002449 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002450 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002451 mStandby = true;
2452 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002453 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002454 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002455 }
2456 if (status == NO_ERROR && reconfig) {
2457 delete mAudioMixer;
2458 readOutputParameters();
2459 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2460 for (size_t i = 0; i < mTracks.size() ; i++) {
2461 int name = getTrackName_l();
2462 if (name < 0) break;
2463 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002464 // limit track sample rate to 2 x new output sample rate
2465 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2466 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2467 }
Eric Laurenta553c252009-07-17 12:17:14 -07002468 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002469 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002470 }
2471 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002472
2473 mNewParameters.removeAt(0);
2474
Eric Laurenta553c252009-07-17 12:17:14 -07002475 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002476 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002477 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2478 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002479 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002480 }
2481 return reconfig;
2482}
2483
2484status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2485{
2486 const size_t SIZE = 256;
2487 char buffer[SIZE];
2488 String8 result;
2489
2490 PlaybackThread::dumpInternals(fd, args);
2491
2492 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2493 result.append(buffer);
2494 write(fd, result.string(), result.size());
2495 return NO_ERROR;
2496}
2497
Eric Laurent059b4be2009-11-09 23:32:22 -08002498uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2499{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002500 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002501}
2502
Eric Laurent8448a792010-08-18 18:13:17 -07002503uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2504{
2505 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2506}
2507
Eric Laurenta553c252009-07-17 12:17:14 -07002508// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002509AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002510 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002511{
Eric Laurent464d5b32011-06-17 21:29:58 -07002512 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002513}
2514
2515AudioFlinger::DirectOutputThread::~DirectOutputThread()
2516{
2517}
2518
Eric Laurent65b65452010-06-01 23:49:17 -07002519static inline
2520int32_t mul(int16_t in, int16_t v)
2521{
2522#if defined(__arm__) && !defined(__thumb__)
2523 int32_t out;
2524 asm( "smulbb %[out], %[in], %[v] \n"
2525 : [out]"=r"(out)
2526 : [in]"%r"(in), [v]"r"(v)
2527 : );
2528 return out;
2529#else
2530 return in * int32_t(v);
2531#endif
2532}
2533
2534void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2535{
2536 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002537 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002538 return;
2539 }
2540
2541 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002542 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002543 size_t count = mFrameCount * mChannelCount;
2544 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2545 int16_t *dst = mMixBuffer + count-1;
2546 while(count--) {
2547 *dst-- = (int16_t)(*src--^0x80) << 8;
2548 }
2549 }
2550
2551 size_t frameCount = mFrameCount;
2552 int16_t *out = mMixBuffer;
2553 if (ramp) {
2554 if (mChannelCount == 1) {
2555 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2556 int32_t vlInc = d / (int32_t)frameCount;
2557 int32_t vl = ((int32_t)mLeftVolShort << 16);
2558 do {
2559 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2560 out++;
2561 vl += vlInc;
2562 } while (--frameCount);
2563
2564 } else {
2565 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2566 int32_t vlInc = d / (int32_t)frameCount;
2567 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2568 int32_t vrInc = d / (int32_t)frameCount;
2569 int32_t vl = ((int32_t)mLeftVolShort << 16);
2570 int32_t vr = ((int32_t)mRightVolShort << 16);
2571 do {
2572 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2573 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2574 out += 2;
2575 vl += vlInc;
2576 vr += vrInc;
2577 } while (--frameCount);
2578 }
2579 } else {
2580 if (mChannelCount == 1) {
2581 do {
2582 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2583 out++;
2584 } while (--frameCount);
2585 } else {
2586 do {
2587 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2588 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2589 out += 2;
2590 } while (--frameCount);
2591 }
2592 }
2593
2594 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002595 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002596 size_t count = mFrameCount * mChannelCount;
2597 int16_t *src = mMixBuffer;
2598 uint8_t *dst = (uint8_t *)mMixBuffer;
2599 while(count--) {
2600 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2601 }
2602 }
2603
2604 mLeftVolShort = leftVol;
2605 mRightVolShort = rightVol;
2606}
2607
Eric Laurenta553c252009-07-17 12:17:14 -07002608bool AudioFlinger::DirectOutputThread::threadLoop()
2609{
Glenn Kasten789fef12012-01-26 13:37:52 -08002610 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002611 sp<Track> trackToRemove;
2612 sp<Track> activeTrack;
2613 nsecs_t standbyTime = systemTime();
2614 int8_t *curBuf;
2615 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002616 uint32_t activeSleepTime = activeSleepTimeUs();
2617 uint32_t idleSleepTime = idleSleepTimeUs();
2618 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002619 // use shorter standby delay as on normal output to release
2620 // hardware resources as soon as possible
2621 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002622
Eric Laurent6dbdc402011-07-22 09:04:31 -07002623 acquireWakeLock();
2624
Eric Laurenta553c252009-07-17 12:17:14 -07002625 while (!exitPending())
2626 {
Eric Laurent65b65452010-06-01 23:49:17 -07002627 bool rampVolume;
2628 uint16_t leftVol;
2629 uint16_t rightVol;
2630 Vector< sp<EffectChain> > effectChains;
2631
Eric Laurenta553c252009-07-17 12:17:14 -07002632 processConfigEvents();
2633
Eric Laurent059b4be2009-11-09 23:32:22 -08002634 mixerStatus = MIXER_IDLE;
2635
Eric Laurenta553c252009-07-17 12:17:14 -07002636 { // scope for the mLock
2637
2638 Mutex::Autolock _l(mLock);
2639
2640 if (checkForNewParameters_l()) {
2641 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002642 activeSleepTime = activeSleepTimeUs();
2643 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002644 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002645 }
2646
2647 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002648 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2649 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002650 // wait until we have something to do...
2651 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002652 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002653 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002654 mStandby = true;
2655 mBytesWritten = 0;
2656 }
2657
2658 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2659 // we're about to wait, flush the binder command buffer
2660 IPCThreadState::self()->flushCommands();
2661
2662 if (exitPending()) break;
2663
Eric Laurent6dbdc402011-07-22 09:04:31 -07002664 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002665 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002666 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002667 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002668 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002669
Glenn Kastenb737dbb2012-01-13 15:54:24 -08002670 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07002671 char value[PROPERTY_VALUE_MAX];
2672 property_get("ro.audio.silent", value, "0");
2673 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002674 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002675 setMasterMute(true);
2676 }
2677 }
2678
Eric Laurentef9500f2010-03-11 14:47:00 -08002679 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002680 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002681 continue;
2682 }
2683 }
2684
Eric Laurent65b65452010-06-01 23:49:17 -07002685 effectChains = mEffectChains;
2686
Eric Laurenta553c252009-07-17 12:17:14 -07002687 // find out which tracks need to be processed
2688 if (mActiveTracks.size() != 0) {
2689 sp<Track> t = mActiveTracks[0].promote();
2690 if (t == 0) continue;
2691
2692 Track* const track = t.get();
2693 audio_track_cblk_t* cblk = track->cblk();
2694
2695 // The first time a track is added we wait
2696 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002697 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002698 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002699 {
Steve Block71f2cf12011-10-20 11:56:00 +01002700 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002701
Eric Laurent65b65452010-06-01 23:49:17 -07002702 if (track->mFillingUpStatus == Track::FS_FILLED) {
2703 track->mFillingUpStatus = Track::FS_ACTIVE;
2704 mLeftVolFloat = mRightVolFloat = 0;
2705 mLeftVolShort = mRightVolShort = 0;
2706 if (track->mState == TrackBase::RESUMING) {
2707 track->mState = TrackBase::ACTIVE;
2708 rampVolume = true;
2709 }
2710 } else if (cblk->server != 0) {
2711 // If the track is stopped before the first frame was mixed,
2712 // do not apply ramp
2713 rampVolume = true;
2714 }
Eric Laurenta553c252009-07-17 12:17:14 -07002715 // compute volume for this track
2716 float left, right;
2717 if (track->isMuted() || mMasterMute || track->isPausing() ||
2718 mStreamTypes[track->type()].mute) {
2719 left = right = 0;
2720 if (track->isPausing()) {
2721 track->setPaused();
2722 }
2723 } else {
2724 float typeVolume = mStreamTypes[track->type()].volume;
2725 float v = mMasterVolume * typeVolume;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002726 uint32_t vlr = cblk->volumeLR;
2727 float v_clamped = v * (vlr & 0xFFFF);
Eric Laurenta553c252009-07-17 12:17:14 -07002728 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2729 left = v_clamped/MAX_GAIN;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002730 v_clamped = v * (vlr >> 16);
Eric Laurenta553c252009-07-17 12:17:14 -07002731 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2732 right = v_clamped/MAX_GAIN;
2733 }
2734
Eric Laurent65b65452010-06-01 23:49:17 -07002735 if (left != mLeftVolFloat || right != mRightVolFloat) {
2736 mLeftVolFloat = left;
2737 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002738
Eric Laurent65b65452010-06-01 23:49:17 -07002739 // If audio HAL implements volume control,
2740 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002741 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002742 left = 1.0f;
2743 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002744 }
Eric Laurent65b65452010-06-01 23:49:17 -07002745
2746 // Convert volumes from float to 8.24
2747 uint32_t vl = (uint32_t)(left * (1 << 24));
2748 uint32_t vr = (uint32_t)(right * (1 << 24));
2749
2750 // Delegate volume control to effect in track effect chain if needed
2751 // only one effect chain can be present on DirectOutputThread, so if
2752 // there is one, the track is connected to it
2753 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002754 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002755 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002756 rampVolume = false;
2757 }
2758 }
2759
2760 // Convert volumes from 8.24 to 4.12 format
2761 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2762 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2763 leftVol = (uint16_t)v_clamped;
2764 v_clamped = (vr + (1 << 11)) >> 12;
2765 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2766 rightVol = (uint16_t)v_clamped;
2767 } else {
2768 leftVol = mLeftVolShort;
2769 rightVol = mRightVolShort;
2770 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002771 }
2772
2773 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002774 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002775 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002776 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002777 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002778 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002779 if (track->isStopped()) {
2780 track->reset();
2781 }
2782 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2783 // We have consumed all the buffers of this track.
2784 // Remove it from the list of active tracks.
2785 trackToRemove = track;
2786 } else {
2787 // No buffers for this track. Give it a few chances to
2788 // fill a buffer, then remove it from active list.
2789 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002790 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002791 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002792 } else {
2793 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002794 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002795 }
Eric Laurenta553c252009-07-17 12:17:14 -07002796 }
2797 }
2798
2799 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002800 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002801 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002802 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002803 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002804 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002805 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002806 }
Eric Laurenta553c252009-07-17 12:17:14 -07002807 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002808 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002809 }
2810 }
Eric Laurent65b65452010-06-01 23:49:17 -07002811
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002812 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002813 }
2814
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002815 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002816 AudioBufferProvider::Buffer buffer;
2817 size_t frameCount = mFrameCount;
2818 curBuf = (int8_t *)mMixBuffer;
2819 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002820 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002821 buffer.frameCount = frameCount;
2822 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002823 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002824 memset(curBuf, 0, frameCount * mFrameSize);
2825 break;
2826 }
2827 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2828 frameCount -= buffer.frameCount;
2829 curBuf += buffer.frameCount * mFrameSize;
2830 activeTrack->releaseBuffer(&buffer);
2831 }
2832 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002833 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002834 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002835 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002836 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2837 sleepTime = activeSleepTime;
2838 } else {
2839 sleepTime = idleSleepTime;
2840 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002841 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002842 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002843 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002844 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002845 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002846
Eric Laurentf69a3f82009-09-22 00:35:48 -07002847 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002848 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002849 }
2850 // sleepTime == 0 means we must write to audio hardware
2851 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002852 if (mixerStatus == MIXER_TRACKS_READY) {
2853 applyVolume(leftVol, rightVol, rampVolume);
2854 }
2855 for (size_t i = 0; i < effectChains.size(); i ++) {
2856 effectChains[i]->process_l();
2857 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002858 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002859
Eric Laurentf69a3f82009-09-22 00:35:48 -07002860 mLastWriteTime = systemTime();
2861 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002862 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002863 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002864 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002865 mNumWrites++;
2866 mInWrite = false;
2867 mStandby = false;
2868 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002869 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002870 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002871 }
2872
2873 // finally let go of removed track, without the lock held
2874 // since we can't guarantee the destructors won't acquire that
2875 // same lock.
2876 trackToRemove.clear();
2877 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002878
2879 // Effect chains will be actually deleted here if they were removed from
2880 // mEffectChains list during mixing or effects processing
2881 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002882 }
2883
2884 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002885 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002886 }
Eric Laurenta553c252009-07-17 12:17:14 -07002887
Eric Laurent6dbdc402011-07-22 09:04:31 -07002888 releaseWakeLock();
2889
Steve Block71f2cf12011-10-20 11:56:00 +01002890 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002891 return false;
2892}
2893
2894// getTrackName_l() must be called with ThreadBase::mLock held
2895int AudioFlinger::DirectOutputThread::getTrackName_l()
2896{
2897 return 0;
2898}
2899
2900// deleteTrackName_l() must be called with ThreadBase::mLock held
2901void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2902{
2903}
2904
2905// checkForNewParameters_l() must be called with ThreadBase::mLock held
2906bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2907{
2908 bool reconfig = false;
2909
Eric Laurent8fce46a2009-08-04 09:45:33 -07002910 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002911 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002912 String8 keyValuePair = mNewParameters[0];
2913 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002914 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002915
Eric Laurenta553c252009-07-17 12:17:14 -07002916 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2917 // do not accept frame count changes if tracks are open as the track buffer
2918 // size depends on frame count and correct behavior would not be garantied
2919 // if frame count is changed after track creation
2920 if (!mTracks.isEmpty()) {
2921 status = INVALID_OPERATION;
2922 } else {
2923 reconfig = true;
2924 }
2925 }
2926 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002927 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002928 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002929 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002930 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002931 mStandby = true;
2932 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002933 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002934 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002935 }
2936 if (status == NO_ERROR && reconfig) {
2937 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002938 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002939 }
2940 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002941
2942 mNewParameters.removeAt(0);
2943
Eric Laurenta553c252009-07-17 12:17:14 -07002944 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002945 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002946 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2947 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002948 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002949 }
2950 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002951}
2952
Eric Laurent059b4be2009-11-09 23:32:22 -08002953uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002954{
2955 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002956 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002957 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002958 } else {
2959 time = 10000;
2960 }
2961 return time;
2962}
2963
2964uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2965{
2966 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002967 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002968 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002969 } else {
2970 time = 10000;
2971 }
2972 return time;
2973}
2974
Eric Laurent8448a792010-08-18 18:13:17 -07002975uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2976{
2977 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002978 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002979 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2980 } else {
2981 time = 10000;
2982 }
2983 return time;
2984}
2985
2986
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002987// ----------------------------------------------------------------------------
2988
Eric Laurent49f02be2009-11-19 09:00:56 -08002989AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002990 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002991{
Eric Laurent464d5b32011-06-17 21:29:58 -07002992 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002993 addOutputTrack(mainThread);
2994}
2995
2996AudioFlinger::DuplicatingThread::~DuplicatingThread()
2997{
Eric Laurent0a080292009-12-07 10:53:10 -08002998 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2999 mOutputTracks[i]->destroy();
3000 }
Eric Laurenta553c252009-07-17 12:17:14 -07003001 mOutputTracks.clear();
3002}
3003
3004bool AudioFlinger::DuplicatingThread::threadLoop()
3005{
Eric Laurenta553c252009-07-17 12:17:14 -07003006 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08003007 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003008 nsecs_t standbyTime = systemTime();
3009 size_t mixBufferSize = mFrameCount*mFrameSize;
3010 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07003011 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08003012 uint32_t activeSleepTime = activeSleepTimeUs();
3013 uint32_t idleSleepTime = idleSleepTimeUs();
3014 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07003015 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07003016
Eric Laurent6dbdc402011-07-22 09:04:31 -07003017 acquireWakeLock();
3018
Eric Laurenta553c252009-07-17 12:17:14 -07003019 while (!exitPending())
3020 {
3021 processConfigEvents();
3022
Eric Laurent059b4be2009-11-09 23:32:22 -08003023 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003024 { // scope for the mLock
3025
3026 Mutex::Autolock _l(mLock);
3027
3028 if (checkForNewParameters_l()) {
3029 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003030 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08003031 activeSleepTime = activeSleepTimeUs();
3032 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07003033 }
3034
3035 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3036
3037 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3038 outputTracks.add(mOutputTracks[i]);
3039 }
3040
3041 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003042 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3043 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003044 if (!mStandby) {
3045 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003046 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003047 }
3048 mStandby = true;
3049 mBytesWritten = 0;
3050 }
3051
3052 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3053 // we're about to wait, flush the binder command buffer
3054 IPCThreadState::self()->flushCommands();
3055 outputTracks.clear();
3056
3057 if (exitPending()) break;
3058
Eric Laurent6dbdc402011-07-22 09:04:31 -07003059 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003060 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003061 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003062 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003063 acquireWakeLock_l();
3064
Eric Laurent71c44962012-01-17 19:20:12 -08003065 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08003066 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07003067 char value[PROPERTY_VALUE_MAX];
3068 property_get("ro.audio.silent", value, "0");
3069 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003070 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003071 setMasterMute(true);
3072 }
3073 }
3074
3075 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003076 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003077 continue;
3078 }
3079 }
3080
Eric Laurent059b4be2009-11-09 23:32:22 -08003081 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003082
3083 // prevent any changes in effect chain list and in each effect chain
3084 // during mixing and effect process as the audio buffers could be deleted
3085 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003086 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003087 }
Eric Laurenta553c252009-07-17 12:17:14 -07003088
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003089 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003090 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003091 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003092 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003093 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003094 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003095 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003096 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003097 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003098 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003099 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003100 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3101 sleepTime = activeSleepTime;
3102 } else {
3103 sleepTime = idleSleepTime;
3104 }
Eric Laurent62443f52009-10-05 20:29:18 -07003105 } else if (mBytesWritten != 0) {
3106 // flush remaining overflow buffers in output tracks
3107 for (size_t i = 0; i < outputTracks.size(); i++) {
3108 if (outputTracks[i]->isActive()) {
3109 sleepTime = 0;
3110 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003111 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003112 break;
3113 }
3114 }
Eric Laurenta553c252009-07-17 12:17:14 -07003115 }
3116 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003117
3118 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003119 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003120 }
3121 // sleepTime == 0 means we must write to audio hardware
3122 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003123 for (size_t i = 0; i < effectChains.size(); i ++) {
3124 effectChains[i]->process_l();
3125 }
3126 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003127 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003128
Eric Laurent62443f52009-10-05 20:29:18 -07003129 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003130 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003131 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003132 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003133 mStandby = false;
3134 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003135 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003136 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003137 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003138 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003139 }
3140
3141 // finally let go of all our tracks, without the lock held
3142 // since we can't guarantee the destructors won't acquire that
3143 // same lock.
3144 tracksToRemove.clear();
3145 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003146
3147 // Effect chains will be actually deleted here if they were removed from
3148 // mEffectChains list during mixing or effects processing
3149 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003150 }
3151
Eric Laurent6dbdc402011-07-22 09:04:31 -07003152 releaseWakeLock();
3153
Eric Laurenta553c252009-07-17 12:17:14 -07003154 return false;
3155}
3156
3157void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3158{
3159 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3160 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003161 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003162 mSampleRate,
3163 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003164 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003165 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003166 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003167 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003168 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003169 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003170 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003171 }
Eric Laurenta553c252009-07-17 12:17:14 -07003172}
3173
3174void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3175{
3176 Mutex::Autolock _l(mLock);
3177 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3178 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003179 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003180 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003181 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003182 return;
3183 }
3184 }
Steve Block71f2cf12011-10-20 11:56:00 +01003185 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003186}
3187
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003188void AudioFlinger::DuplicatingThread::updateWaitTime()
3189{
3190 mWaitTimeMs = UINT_MAX;
3191 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3192 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3193 if (strong != NULL) {
3194 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3195 if (waitTimeMs < mWaitTimeMs) {
3196 mWaitTimeMs = waitTimeMs;
3197 }
3198 }
3199 }
3200}
3201
3202
3203bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3204{
3205 for (size_t i = 0; i < outputTracks.size(); i++) {
3206 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3207 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003208 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003209 return false;
3210 }
3211 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3212 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003213 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003214 return false;
3215 }
3216 }
3217 return true;
3218}
3219
3220uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3221{
3222 return (mWaitTimeMs * 1000) / 2;
3223}
3224
Eric Laurenta553c252009-07-17 12:17:14 -07003225// ----------------------------------------------------------------------------
3226
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003227// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003228AudioFlinger::ThreadBase::TrackBase::TrackBase(
3229 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003230 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003231 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003232 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003233 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003234 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003236 const sp<IMemory>& sharedBuffer,
3237 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003238 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003239 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003240 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003241 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003242 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003243 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003244 mClientTid(-1),
3245 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003246 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3247 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003248{
Steve Block71f2cf12011-10-20 11:56:00 +01003249 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003250
Steve Block5baa3a62011-12-20 16:23:08 +00003251 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003252 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003253 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003254 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3255 if (sharedBuffer == 0) {
3256 size += bufferSize;
3257 }
3258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 if (client != NULL) {
3260 mCblkMemory = client->heap()->allocate(size);
3261 if (mCblkMemory != 0) {
3262 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3263 if (mCblk) { // construct the shared structure in-place.
3264 new(mCblk) audio_track_cblk_t();
3265 // clear all buffers
3266 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003267 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003268 mChannelCount = channelCount;
3269 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 if (sharedBuffer == 0) {
3271 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3272 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3273 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003274 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003275 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 } else {
3277 mBuffer = sharedBuffer->pointer();
3278 }
3279 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 } else {
Steve Block3762c312012-01-06 19:20:56 +00003282 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 client->heap()->dump("AudioTrack");
3284 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 } else {
3287 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003288 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 new(mCblk) audio_track_cblk_t();
3290 // clear all buffers
3291 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003292 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003293 mChannelCount = channelCount;
3294 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3296 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3297 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003298 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003299 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003302}
3303
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003304AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003305{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003307 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3308 if (mClient == NULL) {
3309 delete mCblk;
3310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003312 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003313 if (mClient != NULL) {
3314 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3315 mClient.clear();
3316 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003317}
3318
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003319void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003320{
Glenn Kastenc434c902011-12-13 11:53:26 -08003321 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003322 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003323 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003324 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003325}
3326
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003327bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003328 bool result;
3329 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003330
3331 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003332 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003333 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003334 mFlags |= STEPSERVER_FAILED;
3335 }
3336 return result;
3337}
3338
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003339void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003340 audio_track_cblk_t* cblk = this->cblk();
3341
3342 cblk->user = 0;
3343 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003344 cblk->userBase = 0;
3345 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003347 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003348}
3349
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003350sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003351{
3352 return mCblkMemory;
3353}
3354
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003355int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003356 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003357}
3358
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003359int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003360 return (const int)mChannelCount;
3361}
3362
3363uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3364 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003365}
3366
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003367void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003368 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003369 size_t frameSize = cblk->frameSize;
3370 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3371 int8_t *bufferEnd = bufferStart + frames * frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003372
3373 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003374 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003375 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003376 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003377 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003378 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003379 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003380 return 0;
3381 }
3382
3383 return bufferStart;
3384}
3385
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003386// ----------------------------------------------------------------------------
3387
Eric Laurenta553c252009-07-17 12:17:14 -07003388// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3389AudioFlinger::PlaybackThread::Track::Track(
3390 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003391 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003392 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003393 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003394 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003395 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003396 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003397 const sp<IMemory>& sharedBuffer,
3398 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003399 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003400 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3401 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003402{
Eric Laurent8a77a992009-09-09 05:16:08 -07003403 if (mCblk != NULL) {
3404 sp<ThreadBase> baseThread = thread.promote();
3405 if (baseThread != 0) {
3406 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3407 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003408 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003409 }
Steve Block71f2cf12011-10-20 11:56:00 +01003410 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003411 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003412 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003413 }
Eric Laurent8a77a992009-09-09 05:16:08 -07003414 mStreamType = streamType;
3415 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3416 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003417 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003418 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003419}
3420
Eric Laurenta553c252009-07-17 12:17:14 -07003421AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003422{
Steve Block71f2cf12011-10-20 11:56:00 +01003423 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003424 sp<ThreadBase> thread = mThread.promote();
3425 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003426 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003427 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003428 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003429}
3430
Eric Laurenta553c252009-07-17 12:17:14 -07003431void AudioFlinger::PlaybackThread::Track::destroy()
3432{
3433 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3434 // by removing it from mTracks vector, so there is a risk that this Tracks's
3435 // desctructor is called. As the destructor needs to lock mLock,
3436 // we must acquire a strong reference on this Track before locking mLock
3437 // here so that the destructor is called only when exiting this function.
3438 // On the other hand, as long as Track::destroy() is only called by
3439 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3440 // this Track with its member mTrack.
3441 sp<Track> keep(this);
3442 { // scope for mLock
3443 sp<ThreadBase> thread = mThread.promote();
3444 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003445 if (!isOutputTrack()) {
3446 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003447 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003448 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003449 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003450
3451 // to track the speaker usage
3452 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003453 }
3454 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003455 }
Eric Laurenta553c252009-07-17 12:17:14 -07003456 Mutex::Autolock _l(thread->mLock);
3457 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3458 playbackThread->destroyTrack_l(this);
3459 }
3460 }
3461}
3462
3463void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003464{
Glenn Kasten0632bad2012-01-17 12:20:54 -08003465 uint32_t vlr = mCblk->volumeLR;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003466 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003467 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003469 mStreamType,
3470 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003471 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003472 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003473 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003474 mState,
3475 mMute,
3476 mFillingUpStatus,
3477 mCblk->sampleRate,
Glenn Kasten0632bad2012-01-17 12:20:54 -08003478 vlr & 0xFFFF,
3479 vlr >> 16,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003480 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003481 mCblk->user,
3482 (int)mMainBuffer,
3483 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003484}
3485
Eric Laurenta553c252009-07-17 12:17:14 -07003486status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003487{
3488 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003489 uint32_t framesReady;
3490 uint32_t framesReq = buffer->frameCount;
3491
3492 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003493 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3494 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003495 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003496 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3497 }
3498
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003499 framesReady = cblk->framesReady();
3500
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003501 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003502 uint32_t s = cblk->server;
3503 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3504
3505 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3506 if (framesReq > framesReady) {
3507 framesReq = framesReady;
3508 }
3509 if (s + framesReq > bufferEnd) {
3510 framesReq = bufferEnd - s;
3511 }
3512
3513 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003514 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003515
3516 buffer->frameCount = framesReq;
3517 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003518 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003519
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003520getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003521 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003522 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003523 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003524 return NOT_ENOUGH_DATA;
3525}
3526
Eric Laurenta553c252009-07-17 12:17:14 -07003527bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003528 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003529
3530 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003531 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003532 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003533 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003534 return true;
3535 }
3536 return false;
3537}
3538
Eric Laurenta553c252009-07-17 12:17:14 -07003539status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003540{
Eric Laurent49f02be2009-11-19 09:00:56 -08003541 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003542 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003543 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003544 sp<ThreadBase> thread = mThread.promote();
3545 if (thread != 0) {
3546 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003547 track_state state = mState;
Eric Laurent49f02be2009-11-19 09:00:56 -08003548 // here the track could be either new, or restarted
3549 // in both cases "unstop" the track
3550 if (mState == PAUSED) {
3551 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003552 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003553 } else {
3554 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003555 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003556 }
3557
3558 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3559 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003560 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003561 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003562 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003563 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003564
3565 // to track the speaker usage
3566 if (status == NO_ERROR) {
3567 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3568 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003569 }
3570 if (status == NO_ERROR) {
3571 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3572 playbackThread->addTrack_l(this);
3573 } else {
3574 mState = state;
3575 }
3576 } else {
3577 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003578 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003579 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003580}
3581
Eric Laurenta553c252009-07-17 12:17:14 -07003582void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003583{
Steve Block71f2cf12011-10-20 11:56:00 +01003584 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003585 sp<ThreadBase> thread = mThread.promote();
3586 if (thread != 0) {
3587 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003588 track_state state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003589 if (mState > STOPPED) {
3590 mState = STOPPED;
3591 // If the track is not active (PAUSED and buffers full), flush buffers
3592 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3593 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3594 reset();
3595 }
Steve Block71f2cf12011-10-20 11:56:00 +01003596 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003597 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003598 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3599 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003600 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003601 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003602 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003603 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003604
3605 // to track the speaker usage
3606 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003607 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003608 }
3609}
3610
Eric Laurenta553c252009-07-17 12:17:14 -07003611void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003612{
Steve Block71f2cf12011-10-20 11:56:00 +01003613 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003614 sp<ThreadBase> thread = mThread.promote();
3615 if (thread != 0) {
3616 Mutex::Autolock _l(thread->mLock);
3617 if (mState == ACTIVE || mState == RESUMING) {
3618 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003619 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003620 if (!isOutputTrack()) {
3621 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003622 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003623 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003624 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003625 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003626
3627 // to track the speaker usage
3628 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003629 }
Eric Laurenta553c252009-07-17 12:17:14 -07003630 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003631 }
3632}
3633
Eric Laurenta553c252009-07-17 12:17:14 -07003634void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003635{
Steve Block71f2cf12011-10-20 11:56:00 +01003636 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003637 sp<ThreadBase> thread = mThread.promote();
3638 if (thread != 0) {
3639 Mutex::Autolock _l(thread->mLock);
3640 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3641 return;
3642 }
3643 // No point remaining in PAUSED state after a flush => go to
3644 // STOPPED state
3645 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003646
Eric Laurentae29b762011-03-28 18:37:07 -07003647 // do not reset the track if it is still in the process of being stopped or paused.
3648 // this will be done by prepareTracks_l() when the track is stopped.
3649 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3650 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3651 reset();
3652 }
Eric Laurenta553c252009-07-17 12:17:14 -07003653 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003654}
3655
Eric Laurenta553c252009-07-17 12:17:14 -07003656void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003657{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003658 // Do not reset twice to avoid discarding data written just after a flush and before
3659 // the audioflinger thread detects the track is stopped.
3660 if (!mResetDone) {
3661 TrackBase::reset();
3662 // Force underrun condition to avoid false underrun callback until first data is
3663 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003664 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3665 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003666 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003667 mResetDone = true;
3668 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003669}
3670
Eric Laurenta553c252009-07-17 12:17:14 -07003671void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003672{
3673 mMute = muted;
3674}
3675
Eric Laurent65b65452010-06-01 23:49:17 -07003676status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3677{
3678 status_t status = DEAD_OBJECT;
3679 sp<ThreadBase> thread = mThread.promote();
3680 if (thread != 0) {
3681 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3682 status = playbackThread->attachAuxEffect(this, EffectId);
3683 }
3684 return status;
3685}
3686
3687void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3688{
3689 mAuxEffectId = EffectId;
3690 mAuxBuffer = buffer;
3691}
3692
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003693// ----------------------------------------------------------------------------
3694
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003695// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003696AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3697 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003700 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003701 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003703 uint32_t flags,
3704 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003705 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003706 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003707 mOverflow(false)
3708{
Eric Laurent8a77a992009-09-09 05:16:08 -07003709 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003710 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003711 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003712 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003713 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003714 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003715 } else {
3716 mCblk->frameSize = sizeof(int8_t);
3717 }
3718 }
Eric Laurenta553c252009-07-17 12:17:14 -07003719}
3720
3721AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722{
Eric Laurent49f02be2009-11-19 09:00:56 -08003723 sp<ThreadBase> thread = mThread.promote();
3724 if (thread != 0) {
3725 AudioSystem::releaseInput(thread->id());
3726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727}
3728
Eric Laurenta553c252009-07-17 12:17:14 -07003729status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730{
3731 audio_track_cblk_t* cblk = this->cblk();
3732 uint32_t framesAvail;
3733 uint32_t framesReq = buffer->frameCount;
3734
3735 // Check if last stepServer failed, try to step now
3736 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3737 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003738 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3740 }
3741
3742 framesAvail = cblk->framesAvailable_l();
3743
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003744 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 uint32_t s = cblk->server;
3746 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3747
3748 if (framesReq > framesAvail) {
3749 framesReq = framesAvail;
3750 }
3751 if (s + framesReq > bufferEnd) {
3752 framesReq = bufferEnd - s;
3753 }
3754
3755 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003756 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757
3758 buffer->frameCount = framesReq;
3759 return NO_ERROR;
3760 }
3761
3762getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003763 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 buffer->frameCount = 0;
3765 return NOT_ENOUGH_DATA;
3766}
3767
Eric Laurenta553c252009-07-17 12:17:14 -07003768status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769{
Eric Laurenta553c252009-07-17 12:17:14 -07003770 sp<ThreadBase> thread = mThread.promote();
3771 if (thread != 0) {
3772 RecordThread *recordThread = (RecordThread *)thread.get();
3773 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003774 } else {
3775 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777}
3778
Eric Laurenta553c252009-07-17 12:17:14 -07003779void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780{
Eric Laurenta553c252009-07-17 12:17:14 -07003781 sp<ThreadBase> thread = mThread.promote();
3782 if (thread != 0) {
3783 RecordThread *recordThread = (RecordThread *)thread.get();
3784 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003785 TrackBase::reset();
3786 // Force overerrun condition to avoid false overrun callback until first data is
3787 // read from buffer
3788 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790}
3791
Eric Laurent3fdb1262009-11-07 00:01:32 -08003792void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3793{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003794 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003795 (mClient == NULL) ? getpid() : mClient->pid(),
3796 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003797 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003798 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003799 mFrameCount,
3800 mState,
3801 mCblk->sampleRate,
3802 mCblk->server,
3803 mCblk->user);
3804}
3805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003806
3807// ----------------------------------------------------------------------------
3808
Eric Laurenta553c252009-07-17 12:17:14 -07003809AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3810 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003811 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003813 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003814 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003816 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003817 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818{
Eric Laurenta553c252009-07-17 12:17:14 -07003819
3820 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003821 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003822 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003823 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Glenn Kasten0632bad2012-01-17 12:20:54 -08003824 mCblk->volumeLR = (MAX_GAIN_INT << 16) | MAX_GAIN_INT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003825 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003826 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003827 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003828 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3829 mCblk, mBuffer, mCblk->buffers,
3830 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003831 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003832 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07003833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834}
3835
Eric Laurenta553c252009-07-17 12:17:14 -07003836AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837{
Eric Laurent6c30a712009-08-10 23:22:32 -07003838 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839}
3840
Eric Laurenta553c252009-07-17 12:17:14 -07003841status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842{
3843 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003844 if (status != NO_ERROR) {
3845 return status;
3846 }
3847
3848 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 mRetryCount = 127;
3850 return status;
3851}
3852
Eric Laurenta553c252009-07-17 12:17:14 -07003853void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854{
3855 Track::stop();
3856 clearBufferQueue();
3857 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003858 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859}
3860
Eric Laurenta553c252009-07-17 12:17:14 -07003861bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862{
3863 Buffer *pInBuffer;
3864 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003865 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003866 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 inBuffer.frameCount = frames;
3868 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003869
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003870 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003871
Eric Laurent62443f52009-10-05 20:29:18 -07003872 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003873 start();
3874 sp<ThreadBase> thread = mThread.promote();
3875 if (thread != 0) {
3876 MixerThread *mixerThread = (MixerThread *)thread.get();
3877 if (mCblk->frameCount > frames){
3878 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3879 uint32_t startFrames = (mCblk->frameCount - frames);
3880 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003881 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003882 pInBuffer->frameCount = startFrames;
3883 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003884 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003885 mBufferQueue.add(pInBuffer);
3886 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003887 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07003888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 }
Eric Laurenta553c252009-07-17 12:17:14 -07003890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
3892
Eric Laurenta553c252009-07-17 12:17:14 -07003893 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 // First write pending buffers, then new data
3895 if (mBufferQueue.size()) {
3896 pInBuffer = mBufferQueue.itemAt(0);
3897 } else {
3898 pInBuffer = &inBuffer;
3899 }
Eric Laurenta553c252009-07-17 12:17:14 -07003900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 if (pInBuffer->frameCount == 0) {
3902 break;
3903 }
Eric Laurenta553c252009-07-17 12:17:14 -07003904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 if (mOutBuffer.frameCount == 0) {
3906 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003907 nsecs_t startTime = systemTime();
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003908 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003909 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003910 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 break;
3912 }
Eric Laurenta553c252009-07-17 12:17:14 -07003913 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003914 if (waitTimeLeftMs >= waitTimeMs) {
3915 waitTimeLeftMs -= waitTimeMs;
3916 } else {
3917 waitTimeLeftMs = 0;
3918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 }
Eric Laurenta553c252009-07-17 12:17:14 -07003920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003922 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 mCblk->stepUser(outFrames);
3924 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003925 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003927 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 if (pInBuffer->frameCount == 0) {
3930 if (mBufferQueue.size()) {
3931 mBufferQueue.removeAt(0);
3932 delete [] pInBuffer->mBuffer;
3933 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003934 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 } else {
3936 break;
3937 }
3938 }
3939 }
Eric Laurenta553c252009-07-17 12:17:14 -07003940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 // If we could not write all frames, allocate a buffer and queue it for next time.
3942 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003943 sp<ThreadBase> thread = mThread.promote();
3944 if (thread != 0 && !thread->standby()) {
3945 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3946 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003947 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003948 pInBuffer->frameCount = inBuffer.frameCount;
3949 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003950 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003951 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003952 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003953 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003954 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 }
3957 }
Eric Laurenta553c252009-07-17 12:17:14 -07003958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003960 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003962 if (frames == 0 && mBufferQueue.size() == 0) {
3963 if (mCblk->user < mCblk->frameCount) {
3964 frames = mCblk->frameCount - mCblk->user;
3965 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003966 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003967 pInBuffer->frameCount = frames;
3968 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003969 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003970 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003971 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003972 stop();
3973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 }
3975
Eric Laurenta553c252009-07-17 12:17:14 -07003976 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977}
3978
Eric Laurenta553c252009-07-17 12:17:14 -07003979status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980{
3981 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 status_t result;
3983 audio_track_cblk_t* cblk = mCblk;
3984 uint32_t framesReq = buffer->frameCount;
3985
Steve Block71f2cf12011-10-20 11:56:00 +01003986// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 uint32_t framesAvail = cblk->framesAvailable();
3990
Eric Laurenta553c252009-07-17 12:17:14 -07003991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003993 Mutex::Autolock _l(cblk->lock);
3994 goto start_loop_here;
3995 while (framesAvail == 0) {
3996 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003997 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003998 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003999 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004000 }
4001 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4002 if (result != NO_ERROR) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004003 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004004 }
4005 // read the server count again
4006 start_loop_here:
4007 framesAvail = cblk->framesAvailable_l();
4008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 }
4010
Eric Laurenta553c252009-07-17 12:17:14 -07004011// if (framesAvail < framesReq) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004012// return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004013// }
4014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 if (framesReq > framesAvail) {
4016 framesReq = framesAvail;
4017 }
4018
4019 uint32_t u = cblk->user;
4020 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4021
4022 if (u + framesReq > bufferEnd) {
4023 framesReq = bufferEnd - u;
4024 }
4025
4026 buffer->frameCount = framesReq;
4027 buffer->raw = (void *)cblk->buffer(u);
4028 return NO_ERROR;
4029}
4030
4031
Eric Laurenta553c252009-07-17 12:17:14 -07004032void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033{
4034 size_t size = mBufferQueue.size();
4035 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 for (size_t i = 0; i < size; i++) {
4038 pBuffer = mBufferQueue.itemAt(i);
4039 delete [] pBuffer->mBuffer;
4040 delete pBuffer;
4041 }
4042 mBufferQueue.clear();
4043}
4044
4045// ----------------------------------------------------------------------------
4046
4047AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4048 : RefBase(),
4049 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004050 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mPid(pid)
4052{
4053 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4054}
4055
Eric Laurentb9481d82009-09-17 05:12:56 -07004056// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057AudioFlinger::Client::~Client()
4058{
Eric Laurentb9481d82009-09-17 05:12:56 -07004059 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060}
4061
4062const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4063{
4064 return mMemoryDealer;
4065}
4066
4067// ----------------------------------------------------------------------------
4068
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004069AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4070 const sp<IAudioFlingerClient>& client,
4071 pid_t pid)
4072 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4073{
4074}
4075
4076AudioFlinger::NotificationClient::~NotificationClient()
4077{
4078 mClient.clear();
4079}
4080
4081void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4082{
4083 sp<NotificationClient> keep(this);
4084 {
4085 mAudioFlinger->removeNotificationClient(mPid);
4086 }
4087}
4088
4089// ----------------------------------------------------------------------------
4090
Eric Laurenta553c252009-07-17 12:17:14 -07004091AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004092 : BnAudioTrack(),
4093 mTrack(track)
4094{
4095}
4096
4097AudioFlinger::TrackHandle::~TrackHandle() {
4098 // just stop the track on deletion, associated resources
4099 // will be freed from the main thread once all pending buffers have
4100 // been played. Unless it's not in the active track list, in which
4101 // case we free everything now...
4102 mTrack->destroy();
4103}
4104
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004105sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4106 return mTrack->getCblk();
4107}
4108
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004109status_t AudioFlinger::TrackHandle::start() {
4110 return mTrack->start();
4111}
4112
4113void AudioFlinger::TrackHandle::stop() {
4114 mTrack->stop();
4115}
4116
4117void AudioFlinger::TrackHandle::flush() {
4118 mTrack->flush();
4119}
4120
4121void AudioFlinger::TrackHandle::mute(bool e) {
4122 mTrack->mute(e);
4123}
4124
4125void AudioFlinger::TrackHandle::pause() {
4126 mTrack->pause();
4127}
4128
Eric Laurent65b65452010-06-01 23:49:17 -07004129status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4130{
4131 return mTrack->attachAuxEffect(EffectId);
4132}
4133
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004134status_t AudioFlinger::TrackHandle::onTransact(
4135 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4136{
4137 return BnAudioTrack::onTransact(code, data, reply, flags);
4138}
4139
4140// ----------------------------------------------------------------------------
4141
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004142sp<IAudioRecord> AudioFlinger::openRecord(
4143 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004144 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004145 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004146 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004147 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004148 int frameCount,
4149 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004150 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004151 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004152{
Eric Laurenta553c252009-07-17 12:17:14 -07004153 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004154 sp<RecordHandle> recordHandle;
4155 sp<Client> client;
4156 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004157 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004158 RecordThread *thread;
4159 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004160 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004161
4162 // check calling permissions
4163 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004164 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004165 goto Exit;
4166 }
4167
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004168 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004169 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004170 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004171 thread = checkRecordThread_l(input);
4172 if (thread == NULL) {
4173 lStatus = BAD_VALUE;
4174 goto Exit;
4175 }
4176
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004177 wclient = mClients.valueFor(pid);
4178 if (wclient != NULL) {
4179 client = wclient.promote();
4180 } else {
4181 client = new Client(this, pid);
4182 mClients.add(pid, client);
4183 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004184
Eric Laurent65b65452010-06-01 23:49:17 -07004185 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004186 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004187 lSessionId = *sessionId;
4188 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004189 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004190 if (sessionId != NULL) {
4191 *sessionId = lSessionId;
4192 }
4193 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004194 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004195 recordTrack = thread->createRecordTrack_l(client,
4196 sampleRate,
4197 format,
4198 channelMask,
4199 frameCount,
4200 flags,
4201 lSessionId,
4202 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004203 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004204 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004205 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4206 // destructor is called by the TrackBase destructor with mLock held
4207 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 goto Exit;
4210 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004211
4212 // return to handle to client
4213 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004214 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004215
4216Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004217 if (status) {
4218 *status = lStatus;
4219 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004220 return recordHandle;
4221}
4222
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004223// ----------------------------------------------------------------------------
4224
Eric Laurenta553c252009-07-17 12:17:14 -07004225AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004226 : BnAudioRecord(),
4227 mRecordTrack(recordTrack)
4228{
4229}
4230
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004231AudioFlinger::RecordHandle::~RecordHandle() {
4232 stop();
4233}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004234
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004235sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4236 return mRecordTrack->getCblk();
4237}
4238
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004239status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004240 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004241 return mRecordTrack->start();
4242}
4243
4244void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004245 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004246 mRecordTrack->stop();
4247}
4248
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004249status_t AudioFlinger::RecordHandle::onTransact(
4250 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4251{
4252 return BnAudioRecord::onTransact(code, data, reply, flags);
4253}
4254
4255// ----------------------------------------------------------------------------
4256
Eric Laurent464d5b32011-06-17 21:29:58 -07004257AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4258 AudioStreamIn *input,
4259 uint32_t sampleRate,
4260 uint32_t channels,
4261 int id,
4262 uint32_t device) :
4263 ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08004264 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004265{
Eric Laurent464d5b32011-06-17 21:29:58 -07004266 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004267
4268 snprintf(mName, kNameLength, "AudioIn_%d", id);
4269
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004270 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004271 mReqSampleRate = sampleRate;
4272 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004273}
4274
Eric Laurenta553c252009-07-17 12:17:14 -07004275
4276AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004277{
Eric Laurenta553c252009-07-17 12:17:14 -07004278 delete[] mRsmpInBuffer;
Glenn Kastenc434c902011-12-13 11:53:26 -08004279 if (mResampler != NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004280 delete mResampler;
4281 delete[] mRsmpOutBuffer;
4282 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004283}
4284
Eric Laurenta553c252009-07-17 12:17:14 -07004285void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004286{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004287 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004288}
Eric Laurent49f02be2009-11-19 09:00:56 -08004289
Eric Laurent828b9772011-08-07 16:32:26 -07004290status_t AudioFlinger::RecordThread::readyToRun()
4291{
4292 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004293 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004294 return status;
4295}
4296
Eric Laurenta553c252009-07-17 12:17:14 -07004297bool AudioFlinger::RecordThread::threadLoop()
4298{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004299 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004300 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004301 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004302
Eric Laurent4712baa2010-09-30 16:12:31 -07004303 nsecs_t lastWarning = 0;
4304
Eric Laurent6dbdc402011-07-22 09:04:31 -07004305 acquireWakeLock();
4306
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004307 // start recording
4308 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004309
Eric Laurenta553c252009-07-17 12:17:14 -07004310 processConfigEvents();
4311
4312 { // scope for mLock
4313 Mutex::Autolock _l(mLock);
4314 checkForNewParameters_l();
4315 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4316 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004317 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004318 mStandby = true;
4319 }
4320
4321 if (exitPending()) break;
4322
Eric Laurent6dbdc402011-07-22 09:04:31 -07004323 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004324 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004325 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004326 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004327 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004328 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004329 continue;
4330 }
4331 if (mActiveTrack != 0) {
4332 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004333 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004334 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004335 mStandby = true;
4336 }
Eric Laurenta553c252009-07-17 12:17:14 -07004337 mActiveTrack.clear();
4338 mStartStopCond.broadcast();
4339 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004340 if (mReqChannelCount != mActiveTrack->channelCount()) {
4341 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004342 mStartStopCond.broadcast();
4343 } else if (mBytesRead != 0) {
4344 // record start succeeds only if first read from audio input
4345 // succeeds
4346 if (mBytesRead > 0) {
4347 mActiveTrack->mState = TrackBase::ACTIVE;
4348 } else {
4349 mActiveTrack.clear();
4350 }
4351 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004352 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004353 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004354 }
Eric Laurenta553c252009-07-17 12:17:14 -07004355 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004356 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004357 }
4358
4359 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004360 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4361 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004362 unlockEffectChains(effectChains);
4363 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004364 continue;
4365 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004366 for (size_t i = 0; i < effectChains.size(); i ++) {
4367 effectChains[i]->process_l();
4368 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004369
Eric Laurenta553c252009-07-17 12:17:14 -07004370 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004371 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004372 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004373 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004374 // no resampling
4375 while (framesOut) {
4376 size_t framesIn = mFrameCount - mRsmpInIndex;
4377 if (framesIn) {
4378 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4379 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4380 if (framesIn > framesOut)
4381 framesIn = framesOut;
4382 mRsmpInIndex += framesIn;
4383 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004384 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004385 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004386 memcpy(dst, src, framesIn * mFrameSize);
4387 } else {
4388 int16_t *src16 = (int16_t *)src;
4389 int16_t *dst16 = (int16_t *)dst;
4390 if (mChannelCount == 1) {
4391 while (framesIn--) {
4392 *dst16++ = *src16;
4393 *dst16++ = *src16++;
4394 }
4395 } else {
4396 while (framesIn--) {
4397 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4398 src16 += 2;
4399 }
4400 }
4401 }
4402 }
4403 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004404 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004405 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004406 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004407 framesOut = 0;
4408 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004409 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004410 mRsmpInIndex = 0;
4411 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004412 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004413 ALOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004414 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004415 // Force input into standby so that it tries to
4416 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004417 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004418 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004419 }
Eric Laurenta553c252009-07-17 12:17:14 -07004420 mRsmpInIndex = mFrameCount;
4421 framesOut = 0;
4422 buffer.frameCount = 0;
4423 }
4424 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004425 }
4426 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004427 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004428
Eric Laurenta553c252009-07-17 12:17:14 -07004429 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4430 // alter output frame count as if we were expecting stereo samples
4431 if (mChannelCount == 1 && mReqChannelCount == 1) {
4432 framesOut >>= 1;
4433 }
4434 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4435 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4436 // are 32 bit aligned which should be always true.
4437 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004438 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004439 // the resampler always outputs stereo samples: do post stereo to mono conversion
4440 int16_t *src = (int16_t *)mRsmpOutBuffer;
4441 int16_t *dst = buffer.i16;
4442 while (framesOut--) {
4443 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4444 src += 2;
4445 }
4446 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004447 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004448 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004449
Eric Laurenta553c252009-07-17 12:17:14 -07004450 }
4451 mActiveTrack->releaseBuffer(&buffer);
4452 mActiveTrack->overflow();
4453 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004454 // client isn't retrieving buffers fast enough
4455 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004456 if (!mActiveTrack->setOverflow()) {
4457 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004458 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004459 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004460 lastWarning = now;
4461 }
4462 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004463 // Release the processor for a while before asking for a new buffer.
4464 // This will give the application more chance to read from the buffer and
4465 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004466 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004467 }
4468 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004469 // enable changes in effect chain
4470 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004471 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004472 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004473
Eric Laurenta553c252009-07-17 12:17:14 -07004474 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004475 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004476 }
Eric Laurenta553c252009-07-17 12:17:14 -07004477 mActiveTrack.clear();
4478
Eric Laurent49f02be2009-11-19 09:00:56 -08004479 mStartStopCond.broadcast();
4480
Eric Laurent6dbdc402011-07-22 09:04:31 -07004481 releaseWakeLock();
4482
Steve Block71f2cf12011-10-20 11:56:00 +01004483 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004484 return false;
4485}
4486
Eric Laurent464d5b32011-06-17 21:29:58 -07004487
4488sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4489 const sp<AudioFlinger::Client>& client,
4490 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004491 audio_format_t format,
Eric Laurent464d5b32011-06-17 21:29:58 -07004492 int channelMask,
4493 int frameCount,
4494 uint32_t flags,
4495 int sessionId,
4496 status_t *status)
4497{
4498 sp<RecordTrack> track;
4499 status_t lStatus;
4500
4501 lStatus = initCheck();
4502 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004503 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004504 goto Exit;
4505 }
4506
4507 { // scope for mLock
4508 Mutex::Autolock _l(mLock);
4509
4510 track = new RecordTrack(this, client, sampleRate,
4511 format, channelMask, frameCount, flags, sessionId);
4512
4513 if (track->getCblk() == NULL) {
4514 lStatus = NO_MEMORY;
4515 goto Exit;
4516 }
4517
4518 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004519 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4520 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004521 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004522 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4523 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004524 }
4525 lStatus = NO_ERROR;
4526
4527Exit:
4528 if (status) {
4529 *status = lStatus;
4530 }
4531 return track;
4532}
4533
Eric Laurenta553c252009-07-17 12:17:14 -07004534status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004535{
Steve Block71f2cf12011-10-20 11:56:00 +01004536 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004537 sp <ThreadBase> strongMe = this;
4538 status_t status = NO_ERROR;
4539 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004540 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004541 if (mActiveTrack != 0) {
4542 if (recordTrack != mActiveTrack.get()) {
4543 status = -EBUSY;
4544 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004545 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004546 }
4547 return status;
4548 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004549
Eric Laurent49f02be2009-11-19 09:00:56 -08004550 recordTrack->mState = TrackBase::IDLE;
4551 mActiveTrack = recordTrack;
4552 mLock.unlock();
4553 status_t status = AudioSystem::startInput(mId);
4554 mLock.lock();
4555 if (status != NO_ERROR) {
4556 mActiveTrack.clear();
4557 return status;
4558 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004559 mRsmpInIndex = mFrameCount;
4560 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004561 if (mResampler != NULL) {
4562 mResampler->reset();
4563 }
4564 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004565 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004566 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004567 mWaitWorkCV.signal();
4568 // do not wait for mStartStopCond if exiting
4569 if (mExiting) {
4570 mActiveTrack.clear();
4571 status = INVALID_OPERATION;
4572 goto startError;
4573 }
4574 mStartStopCond.wait(mLock);
4575 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004576 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004577 status = BAD_VALUE;
4578 goto startError;
4579 }
Steve Block71f2cf12011-10-20 11:56:00 +01004580 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004581 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004582 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004583startError:
4584 AudioSystem::stopInput(mId);
4585 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004586}
4587
Eric Laurenta553c252009-07-17 12:17:14 -07004588void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004589 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004590 sp <ThreadBase> strongMe = this;
4591 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004592 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004593 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4594 mActiveTrack->mState = TrackBase::PAUSING;
4595 // do not wait for mStartStopCond if exiting
4596 if (mExiting) {
4597 return;
4598 }
4599 mStartStopCond.wait(mLock);
4600 // if we have been restarted, recordTrack == mActiveTrack.get() here
4601 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4602 mLock.unlock();
4603 AudioSystem::stopInput(mId);
4604 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004605 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004606 }
4607 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004608 }
4609}
4610
Eric Laurenta553c252009-07-17 12:17:14 -07004611status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612{
4613 const size_t SIZE = 256;
4614 char buffer[SIZE];
4615 String8 result;
4616 pid_t pid = 0;
4617
Eric Laurent3fdb1262009-11-07 00:01:32 -08004618 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4619 result.append(buffer);
4620
4621 if (mActiveTrack != 0) {
4622 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004623 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004624 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004626
4627 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4628 result.append(buffer);
4629 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4630 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004631 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004632 result.append(buffer);
4633 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4634 result.append(buffer);
4635 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4636 result.append(buffer);
4637
4638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 } else {
4640 result.append("No record client\n");
4641 }
4642 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004643
4644 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004645 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 return NO_ERROR;
4648}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004649
Eric Laurenta553c252009-07-17 12:17:14 -07004650status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4651{
4652 size_t framesReq = buffer->frameCount;
4653 size_t framesReady = mFrameCount - mRsmpInIndex;
4654 int channelCount;
4655
4656 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004657 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004658 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004659 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004660 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004661 // Force input into standby so that it tries to
4662 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004663 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004664 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004665 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004666 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004667 buffer->frameCount = 0;
4668 return NOT_ENOUGH_DATA;
4669 }
4670 mRsmpInIndex = 0;
4671 framesReady = mFrameCount;
4672 }
4673
4674 if (framesReq > framesReady) {
4675 framesReq = framesReady;
4676 }
4677
4678 if (mChannelCount == 1 && mReqChannelCount == 2) {
4679 channelCount = 1;
4680 } else {
4681 channelCount = 2;
4682 }
4683 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4684 buffer->frameCount = framesReq;
4685 return NO_ERROR;
4686}
4687
4688void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4689{
4690 mRsmpInIndex += buffer->frameCount;
4691 buffer->frameCount = 0;
4692}
4693
4694bool AudioFlinger::RecordThread::checkForNewParameters_l()
4695{
4696 bool reconfig = false;
4697
Eric Laurent8fce46a2009-08-04 09:45:33 -07004698 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004699 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004700 String8 keyValuePair = mNewParameters[0];
4701 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004702 int value;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004703 audio_format_t reqFormat = mFormat;
Eric Laurenta553c252009-07-17 12:17:14 -07004704 int reqSamplingRate = mReqSampleRate;
4705 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004706
Eric Laurenta553c252009-07-17 12:17:14 -07004707 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4708 reqSamplingRate = value;
4709 reconfig = true;
4710 }
4711 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004712 reqFormat = (audio_format_t) value;
Eric Laurenta553c252009-07-17 12:17:14 -07004713 reconfig = true;
4714 }
4715 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004716 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004717 reconfig = true;
4718 }
4719 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4720 // do not accept frame count changes if tracks are open as the track buffer
4721 // size depends on frame count and correct behavior would not be garantied
4722 // if frame count is changed after track creation
4723 if (mActiveTrack != 0) {
4724 status = INVALID_OPERATION;
4725 } else {
4726 reconfig = true;
4727 }
4728 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004729 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4730 // forward device change to effects that have requested to be
4731 // aware of attached audio device.
4732 for (size_t i = 0; i < mEffectChains.size(); i++) {
4733 mEffectChains[i]->setDevice_l(value);
4734 }
4735 // store input device and output device but do not forward output device to audio HAL.
4736 // Note that status is ignored by the caller for output device
4737 // (see AudioFlinger::setParameters()
4738 if (value & AUDIO_DEVICE_OUT_ALL) {
4739 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4740 status = BAD_VALUE;
4741 } else {
4742 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004743 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4744 if (mTrack != NULL) {
4745 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004746 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004747 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4748 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4749 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004750 }
4751 mDevice |= (uint32_t)value;
4752 }
Eric Laurenta553c252009-07-17 12:17:14 -07004753 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004754 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004755 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004756 mInput->stream->common.standby(&mInput->stream->common);
4757 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004758 }
4759 if (reconfig) {
4760 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004761 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004762 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004763 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4764 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004765 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004766 status = NO_ERROR;
4767 }
4768 if (status == NO_ERROR) {
4769 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004770 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004771 }
4772 }
4773 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004774
4775 mNewParameters.removeAt(0);
4776
Eric Laurenta553c252009-07-17 12:17:14 -07004777 mParamStatus = status;
4778 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004779 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4780 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004781 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004782 }
4783 return reconfig;
4784}
4785
4786String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4787{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004788 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004789 String8 out_s8 = String8();
4790
4791 Mutex::Autolock _l(mLock);
4792 if (initCheck() != NO_ERROR) {
4793 return out_s8;
4794 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004795
Dima Zavin31f188892011-04-18 16:57:27 -07004796 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004797 out_s8 = String8(s);
4798 free(s);
4799 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004800}
4801
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004802void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004803 AudioSystem::OutputDescriptor desc;
4804 void *param2 = 0;
4805
4806 switch (event) {
4807 case AudioSystem::INPUT_OPENED:
4808 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004809 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004810 desc.samplingRate = mSampleRate;
4811 desc.format = mFormat;
4812 desc.frameCount = mFrameCount;
4813 desc.latency = 0;
4814 param2 = &desc;
4815 break;
4816
4817 case AudioSystem::INPUT_CLOSED:
4818 default:
4819 break;
4820 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004821 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004822}
4823
4824void AudioFlinger::RecordThread::readInputParameters()
4825{
4826 if (mRsmpInBuffer) delete mRsmpInBuffer;
4827 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4828 if (mResampler) delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004829 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004830
Dima Zavin31f188892011-04-18 16:57:27 -07004831 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004832 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4833 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004834 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08004835 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07004836 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004837 mFrameCount = mInputBytes / mFrameSize;
4838 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4839
4840 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4841 {
4842 int channelCount;
4843 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4844 // stereo to mono post process as the resampler always outputs stereo.
4845 if (mChannelCount == 1 && mReqChannelCount == 2) {
4846 channelCount = 1;
4847 } else {
4848 channelCount = 2;
4849 }
4850 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4851 mResampler->setSampleRate(mSampleRate);
4852 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4853 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4854
4855 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4856 if (mChannelCount == 1 && mReqChannelCount == 1) {
4857 mFrameCount >>= 1;
4858 }
4859
4860 }
4861 mRsmpInIndex = mFrameCount;
4862}
4863
Eric Laurent47d0a922010-02-26 02:47:27 -08004864unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4865{
Eric Laurent828b9772011-08-07 16:32:26 -07004866 Mutex::Autolock _l(mLock);
4867 if (initCheck() != NO_ERROR) {
4868 return 0;
4869 }
4870
Dima Zavin31f188892011-04-18 16:57:27 -07004871 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004872}
4873
Eric Laurent464d5b32011-06-17 21:29:58 -07004874uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4875{
4876 Mutex::Autolock _l(mLock);
4877 uint32_t result = 0;
4878 if (getEffectChain_l(sessionId) != 0) {
4879 result = EFFECT_SESSION;
4880 }
4881
4882 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4883 result |= TRACK_SESSION;
4884 }
4885
4886 return result;
4887}
4888
Eric Laurent6639b552011-08-01 09:52:20 -07004889AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4890{
4891 Mutex::Autolock _l(mLock);
4892 return mTrack;
4893}
4894
Glenn Kasten5b0135e2012-01-26 09:46:34 -08004895AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurent828b9772011-08-07 16:32:26 -07004896{
4897 Mutex::Autolock _l(mLock);
4898 return mInput;
4899}
4900
4901AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4902{
4903 Mutex::Autolock _l(mLock);
4904 AudioStreamIn *input = mInput;
4905 mInput = NULL;
4906 return input;
4907}
4908
4909// this method must always be called either with ThreadBase mLock held or inside the thread loop
4910audio_stream_t* AudioFlinger::RecordThread::stream()
4911{
4912 if (mInput == NULL) {
4913 return NULL;
4914 }
4915 return &mInput->stream->common;
4916}
4917
4918
Eric Laurenta553c252009-07-17 12:17:14 -07004919// ----------------------------------------------------------------------------
4920
Eric Laurentddb78e72009-07-28 08:44:33 -07004921int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004922 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004923 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07004924 uint32_t *pChannels,
4925 uint32_t *pLatencyMs,
4926 uint32_t flags)
4927{
4928 status_t status;
4929 PlaybackThread *thread = NULL;
4930 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4931 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004932 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07004933 uint32_t channels = pChannels ? *pChannels : 0;
4934 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004935 audio_stream_out_t *outStream;
4936 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004937
Steve Block71f2cf12011-10-20 11:56:00 +01004938 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004939 pDevices ? *pDevices : 0,
4940 samplingRate,
4941 format,
4942 channels,
4943 flags);
4944
4945 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004946 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004947 }
Dima Zavin31f188892011-04-18 16:57:27 -07004948
Eric Laurenta553c252009-07-17 12:17:14 -07004949 Mutex::Autolock _l(mLock);
4950
Dima Zavin31f188892011-04-18 16:57:27 -07004951 outHwDev = findSuitableHwDev_l(*pDevices);
4952 if (outHwDev == NULL)
4953 return 0;
4954
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004955 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07004956 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004957 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004958 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004959 samplingRate,
4960 format,
4961 channels,
4962 status);
4963
4964 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004965 if (outStream != NULL) {
4966 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004967 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004968
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004969 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4970 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4971 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004972 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004973 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004974 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004975 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004976 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004977 }
Eric Laurent65b65452010-06-01 23:49:17 -07004978 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004979
4980 if (pSamplingRate) *pSamplingRate = samplingRate;
4981 if (pFormat) *pFormat = format;
4982 if (pChannels) *pChannels = channels;
4983 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004984
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004985 // notify client processes of the new output creation
4986 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004987 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004988 }
4989
Eric Laurent9cc489a22009-12-05 05:20:01 -08004990 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004991}
4992
Eric Laurentddb78e72009-07-28 08:44:33 -07004993int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004994{
4995 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004996 MixerThread *thread1 = checkMixerThread_l(output1);
4997 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004998
Eric Laurentddb78e72009-07-28 08:44:33 -07004999 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005000 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005001 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005002 }
5003
Eric Laurent464d5b32011-06-17 21:29:58 -07005004 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005005 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07005006 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07005007 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005008 // notify client processes of the new output creation
5009 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005010 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005011}
5012
Eric Laurentddb78e72009-07-28 08:44:33 -07005013status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005014{
Eric Laurent49018a52009-08-04 08:37:05 -07005015 // keep strong reference on the playback thread so that
5016 // it is not destroyed while exit() is executed
5017 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005018 {
5019 Mutex::Autolock _l(mLock);
5020 thread = checkPlaybackThread_l(output);
5021 if (thread == NULL) {
5022 return BAD_VALUE;
5023 }
5024
Steve Block71f2cf12011-10-20 11:56:00 +01005025 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005026
Eric Laurent464d5b32011-06-17 21:29:58 -07005027 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07005028 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005029 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005030 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005031 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005032 }
5033 }
5034 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07005035 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005036 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005037 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005038 }
5039 thread->exit();
5040
Eric Laurent464d5b32011-06-17 21:29:58 -07005041 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005042 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005043 assert(out != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005044 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005045 out->hwDev->close_output_stream(out->hwDev, out->stream);
5046 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005047 }
Eric Laurenta553c252009-07-17 12:17:14 -07005048 return NO_ERROR;
5049}
5050
Eric Laurentddb78e72009-07-28 08:44:33 -07005051status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005052{
5053 Mutex::Autolock _l(mLock);
5054 PlaybackThread *thread = checkPlaybackThread_l(output);
5055
5056 if (thread == NULL) {
5057 return BAD_VALUE;
5058 }
5059
Steve Block71f2cf12011-10-20 11:56:00 +01005060 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005061 thread->suspend();
5062
5063 return NO_ERROR;
5064}
5065
Eric Laurentddb78e72009-07-28 08:44:33 -07005066status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005067{
5068 Mutex::Autolock _l(mLock);
5069 PlaybackThread *thread = checkPlaybackThread_l(output);
5070
5071 if (thread == NULL) {
5072 return BAD_VALUE;
5073 }
5074
Steve Block71f2cf12011-10-20 11:56:00 +01005075 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005076
5077 thread->restore();
5078
5079 return NO_ERROR;
5080}
5081
Eric Laurentddb78e72009-07-28 08:44:33 -07005082int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005083 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005084 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005085 uint32_t *pChannels,
5086 uint32_t acoustics)
5087{
5088 status_t status;
5089 RecordThread *thread = NULL;
5090 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005091 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005092 uint32_t channels = pChannels ? *pChannels : 0;
5093 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005094 audio_format_t reqFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -07005095 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005096 audio_stream_in_t *inStream;
5097 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005098
5099 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005100 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005101 }
Dima Zavin31f188892011-04-18 16:57:27 -07005102
Eric Laurenta553c252009-07-17 12:17:14 -07005103 Mutex::Autolock _l(mLock);
5104
Dima Zavin31f188892011-04-18 16:57:27 -07005105 inHwDev = findSuitableHwDev_l(*pDevices);
5106 if (inHwDev == NULL)
5107 return 0;
5108
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005109 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005110 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005111 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005112 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005113 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005114 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005115 samplingRate,
5116 format,
5117 channels,
5118 acoustics,
5119 status);
5120
5121 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5122 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5123 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005124 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005125 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005126 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005127 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005128 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005129 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005130 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005131 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005132 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005133 }
5134
Dima Zavin31f188892011-04-18 16:57:27 -07005135 if (inStream != NULL) {
5136 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5137
Eric Laurent464d5b32011-06-17 21:29:58 -07005138 int id = nextUniqueId();
5139 // Start record thread
5140 // RecorThread require both input and output device indication to forward to audio
5141 // pre processing modules
5142 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5143 thread = new RecordThread(this,
5144 input,
5145 reqSamplingRate,
5146 reqChannels,
5147 id,
5148 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005149 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005150 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005151 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5152 if (pFormat) *pFormat = format;
5153 if (pChannels) *pChannels = reqChannels;
5154
Dima Zavin31f188892011-04-18 16:57:27 -07005155 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005156
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005157 // notify client processes of the new input creation
5158 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005159 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005160 }
5161
Eric Laurent9cc489a22009-12-05 05:20:01 -08005162 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005163}
5164
Eric Laurentddb78e72009-07-28 08:44:33 -07005165status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005166{
Eric Laurent49018a52009-08-04 08:37:05 -07005167 // keep strong reference on the record thread so that
5168 // it is not destroyed while exit() is executed
5169 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005170 {
5171 Mutex::Autolock _l(mLock);
5172 thread = checkRecordThread_l(input);
5173 if (thread == NULL) {
5174 return BAD_VALUE;
5175 }
5176
Steve Block71f2cf12011-10-20 11:56:00 +01005177 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005178 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005179 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005180 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005181 }
5182 thread->exit();
5183
Eric Laurent828b9772011-08-07 16:32:26 -07005184 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005185 assert(in != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005186 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005187 in->hwDev->close_input_stream(in->hwDev, in->stream);
5188 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005189
Eric Laurenta553c252009-07-17 12:17:14 -07005190 return NO_ERROR;
5191}
5192
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08005193status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005194{
5195 Mutex::Autolock _l(mLock);
5196 MixerThread *dstThread = checkMixerThread_l(output);
5197 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005198 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005199 return BAD_VALUE;
5200 }
5201
Steve Block71f2cf12011-10-20 11:56:00 +01005202 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005203 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005204
Eric Laurent05ce0942011-08-30 10:18:54 -07005205 dstThread->setStreamValid(stream, true);
5206
Eric Laurenta553c252009-07-17 12:17:14 -07005207 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005208 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005209 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005210 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005211 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005212 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005213 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005214 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005215 }
Eric Laurentd069f322009-09-01 05:56:26 -07005216
Eric Laurenta553c252009-07-17 12:17:14 -07005217 return NO_ERROR;
5218}
5219
Eric Laurent65b65452010-06-01 23:49:17 -07005220
5221int AudioFlinger::newAudioSessionId()
5222{
Eric Laurent464d5b32011-06-17 21:29:58 -07005223 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005224}
5225
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005226void AudioFlinger::acquireAudioSessionId(int audioSession)
5227{
5228 Mutex::Autolock _l(mLock);
5229 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005230 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005231 int num = mAudioSessionRefs.size();
5232 for (int i = 0; i< num; i++) {
5233 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5234 if (ref->sessionid == audioSession && ref->pid == caller) {
5235 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005236 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005237 return;
5238 }
5239 }
5240 AudioSessionRef *ref = new AudioSessionRef();
5241 ref->sessionid = audioSession;
5242 ref->pid = caller;
5243 ref->cnt = 1;
5244 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005245 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005246}
5247
5248void AudioFlinger::releaseAudioSessionId(int audioSession)
5249{
5250 Mutex::Autolock _l(mLock);
5251 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005252 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005253 int num = mAudioSessionRefs.size();
5254 for (int i = 0; i< num; i++) {
5255 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5256 if (ref->sessionid == audioSession && ref->pid == caller) {
5257 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005258 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005259 if (ref->cnt == 0) {
5260 mAudioSessionRefs.removeAt(i);
5261 delete ref;
5262 purgeStaleEffects_l();
5263 }
5264 return;
5265 }
5266 }
Steve Block8564c8d2012-01-05 23:22:43 +00005267 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005268}
5269
5270void AudioFlinger::purgeStaleEffects_l() {
5271
Steve Block71f2cf12011-10-20 11:56:00 +01005272 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005273
5274 Vector< sp<EffectChain> > chains;
5275
5276 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5277 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5278 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5279 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005280 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5281 chains.push(ec);
5282 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005283 }
5284 }
5285 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5286 sp<RecordThread> t = mRecordThreads.valueAt(i);
5287 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5288 sp<EffectChain> ec = t->mEffectChains[j];
5289 chains.push(ec);
5290 }
5291 }
5292
5293 for (size_t i = 0; i < chains.size(); i++) {
5294 sp<EffectChain> ec = chains[i];
5295 int sessionid = ec->sessionId();
5296 sp<ThreadBase> t = ec->mThread.promote();
5297 if (t == 0) {
5298 continue;
5299 }
5300 size_t numsessionrefs = mAudioSessionRefs.size();
5301 bool found = false;
5302 for (size_t k = 0; k < numsessionrefs; k++) {
5303 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5304 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005305 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005306 sessionid, ref->pid, ref->cnt);
5307 found = true;
5308 break;
5309 }
5310 }
5311 if (!found) {
5312 // remove all effects from the chain
5313 while (ec->mEffects.size()) {
5314 sp<EffectModule> effect = ec->mEffects[0];
5315 effect->unPin();
5316 Mutex::Autolock _l (t->mLock);
5317 t->removeEffect_l(effect);
5318 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5319 sp<EffectHandle> handle = effect->mHandles[j].promote();
5320 if (handle != 0) {
5321 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005322 if (handle->mHasControl && handle->mEnabled) {
5323 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5324 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005325 }
5326 }
5327 AudioSystem::unregisterEffect(effect->id());
5328 }
5329 }
5330 }
5331 return;
5332}
5333
Eric Laurenta553c252009-07-17 12:17:14 -07005334// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005335AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005336{
5337 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005338 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5339 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005340 }
Eric Laurenta553c252009-07-17 12:17:14 -07005341 return thread;
5342}
5343
5344// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005345AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005346{
5347 PlaybackThread *thread = checkPlaybackThread_l(output);
5348 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005349 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005350 thread = NULL;
5351 }
5352 }
5353 return (MixerThread *)thread;
5354}
5355
5356// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005357AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005358{
5359 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005360 if (mRecordThreads.indexOfKey(input) >= 0) {
5361 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005362 }
Eric Laurenta553c252009-07-17 12:17:14 -07005363 return thread;
5364}
5365
Eric Laurent464d5b32011-06-17 21:29:58 -07005366uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005367{
Eric Laurent464d5b32011-06-17 21:29:58 -07005368 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005369}
5370
Eric Laurent464d5b32011-06-17 21:29:58 -07005371AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5372{
5373 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5374 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005375 AudioStreamOut *output = thread->getOutput();
5376 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005377 return thread;
5378 }
5379 }
5380 return NULL;
5381}
5382
5383uint32_t AudioFlinger::primaryOutputDevice_l()
5384{
5385 PlaybackThread *thread = primaryPlaybackThread_l();
5386
5387 if (thread == NULL) {
5388 return 0;
5389 }
5390
5391 return thread->device();
5392}
5393
5394
Eric Laurent65b65452010-06-01 23:49:17 -07005395// ----------------------------------------------------------------------------
5396// Effect management
5397// ----------------------------------------------------------------------------
5398
5399
Eric Laurent65b65452010-06-01 23:49:17 -07005400status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5401{
5402 Mutex::Autolock _l(mLock);
5403 return EffectQueryNumberEffects(numEffects);
5404}
5405
Eric Laurent53334cd2010-06-23 17:38:20 -07005406status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005407{
5408 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005409 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005410}
5411
5412status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5413{
5414 Mutex::Autolock _l(mLock);
5415 return EffectGetDescriptor(pUuid, descriptor);
5416}
5417
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005418
Eric Laurent65b65452010-06-01 23:49:17 -07005419sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5420 effect_descriptor_t *pDesc,
5421 const sp<IEffectClient>& effectClient,
5422 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005423 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005424 int sessionId,
5425 status_t *status,
5426 int *id,
5427 int *enabled)
5428{
5429 status_t lStatus = NO_ERROR;
5430 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005431 effect_descriptor_t desc;
5432 sp<Client> client;
5433 wp<Client> wclient;
5434
Steve Block71f2cf12011-10-20 11:56:00 +01005435 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005436 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005437
5438 if (pDesc == NULL) {
5439 lStatus = BAD_VALUE;
5440 goto Exit;
5441 }
5442
Eric Laurent98c92592010-09-23 16:10:16 -07005443 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005444 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005445 lStatus = PERMISSION_DENIED;
5446 goto Exit;
5447 }
5448
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005449 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005450 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005451 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005452 lStatus = PERMISSION_DENIED;
5453 goto Exit;
5454 }
5455
Eric Laurent464d5b32011-06-17 21:29:58 -07005456 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005457 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005458 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005459 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005460 lStatus = BAD_VALUE;
5461 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005462 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005463 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005464 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005465 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005466 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005467 }
5468 }
5469
Eric Laurent65b65452010-06-01 23:49:17 -07005470 {
5471 Mutex::Autolock _l(mLock);
5472
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005473
Eric Laurent65b65452010-06-01 23:49:17 -07005474 if (!EffectIsNullUuid(&pDesc->uuid)) {
5475 // if uuid is specified, request effect descriptor
5476 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5477 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005478 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005479 goto Exit;
5480 }
5481 } else {
5482 // if uuid is not specified, look for an available implementation
5483 // of the required type in effect factory
5484 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005485 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005486 lStatus = BAD_VALUE;
5487 goto Exit;
5488 }
5489 uint32_t numEffects = 0;
5490 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005491 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005492 bool found = false;
5493
5494 lStatus = EffectQueryNumberEffects(&numEffects);
5495 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005496 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005497 goto Exit;
5498 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005499 for (uint32_t i = 0; i < numEffects; i++) {
5500 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005501 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005502 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005503 continue;
5504 }
5505 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5506 // If matching type found save effect descriptor. If the session is
5507 // 0 and the effect is not auxiliary, continue enumeration in case
5508 // an auxiliary version of this effect type is available
5509 found = true;
5510 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005511 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005512 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5513 break;
5514 }
5515 }
5516 }
5517 if (!found) {
5518 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005519 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005520 goto Exit;
5521 }
5522 // For same effect type, chose auxiliary version over insert version if
5523 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005524 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005525 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5526 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5527 }
5528 }
5529
5530 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005531 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005532 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5533 lStatus = INVALID_OPERATION;
5534 goto Exit;
5535 }
5536
Eric Laurentf82fccd2011-07-27 19:49:51 -07005537 // check recording permission for visualizer
5538 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5539 !recordingAllowed()) {
5540 lStatus = PERMISSION_DENIED;
5541 goto Exit;
5542 }
5543
Eric Laurent65b65452010-06-01 23:49:17 -07005544 // return effect descriptor
5545 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5546
5547 // If output is not specified try to find a matching audio session ID in one of the
5548 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005549 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5550 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005551 // Note: io is never 0 when creating an effect on an input
5552 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005553 // look for the thread where the specified audio session is present
5554 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5555 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005556 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005557 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005558 }
Eric Laurent65b65452010-06-01 23:49:17 -07005559 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005560 if (io == 0) {
5561 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5562 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5563 io = mRecordThreads.keyAt(i);
5564 break;
5565 }
5566 }
5567 }
Eric Laurent98c92592010-09-23 16:10:16 -07005568 // If no output thread contains the requested session ID, default to
5569 // first output. The effect chain will be moved to the correct output
5570 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005571 if (io == 0 && mPlaybackThreads.size()) {
5572 io = mPlaybackThreads.keyAt(0);
5573 }
Steve Block71f2cf12011-10-20 11:56:00 +01005574 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005575 }
5576 ThreadBase *thread = checkRecordThread_l(io);
5577 if (thread == NULL) {
5578 thread = checkPlaybackThread_l(io);
5579 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005580 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005581 lStatus = BAD_VALUE;
5582 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005583 }
Eric Laurent65b65452010-06-01 23:49:17 -07005584 }
Eric Laurent98c92592010-09-23 16:10:16 -07005585
Eric Laurent65b65452010-06-01 23:49:17 -07005586 wclient = mClients.valueFor(pid);
5587
5588 if (wclient != NULL) {
5589 client = wclient.promote();
5590 } else {
5591 client = new Client(this, pid);
5592 mClients.add(pid, client);
5593 }
5594
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005595 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005596 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5597 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005598 if (handle != 0 && id != NULL) {
5599 *id = handle->id();
5600 }
5601 }
5602
5603Exit:
5604 if(status) {
5605 *status = lStatus;
5606 }
5607 return handle;
5608}
5609
Eric Laurentf82fccd2011-07-27 19:49:51 -07005610status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005611{
Steve Block71f2cf12011-10-20 11:56:00 +01005612 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005613 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005614 Mutex::Autolock _l(mLock);
5615 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00005616 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005617 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005618 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005619 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5620 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005621 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005622 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005623 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005624 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5625 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005626 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005627 return BAD_VALUE;
5628 }
5629
5630 Mutex::Autolock _dl(dstThread->mLock);
5631 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005632 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005633
Eric Laurent53334cd2010-06-23 17:38:20 -07005634 return NO_ERROR;
5635}
5636
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005637// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005638status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005639 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005640 AudioFlinger::PlaybackThread *dstThread,
5641 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005642{
Steve Block71f2cf12011-10-20 11:56:00 +01005643 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005644 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005645
Eric Laurentf82fccd2011-07-27 19:49:51 -07005646 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005647 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005648 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005649 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005650 return INVALID_OPERATION;
5651 }
5652
Eric Laurent493941b2010-07-28 01:32:47 -07005653 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005654 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005655 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005656 // removed.
5657 srcThread->removeEffectChain_l(chain);
5658
5659 // transfer all effects one by one so that new effect chain is created on new thread with
5660 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005661 int dstOutput = dstThread->id();
5662 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005663 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005664 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5665 while (effect != 0) {
5666 srcThread->removeEffect_l(effect);
5667 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005668 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5669 if (effect->state() == EffectModule::ACTIVE ||
5670 effect->state() == EffectModule::STOPPING) {
5671 effect->start();
5672 }
Eric Laurent493941b2010-07-28 01:32:47 -07005673 // if the move request is not received from audio policy manager, the effect must be
5674 // re-registered with the new strategy and output
5675 if (dstChain == 0) {
5676 dstChain = effect->chain().promote();
5677 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005678 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07005679 srcThread->addEffect_l(effect);
5680 return NO_INIT;
5681 }
5682 strategy = dstChain->strategy();
5683 }
5684 if (reRegister) {
5685 AudioSystem::unregisterEffect(effect->id());
5686 AudioSystem::registerEffect(&effect->desc(),
5687 dstOutput,
5688 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005689 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005690 effect->id());
5691 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005692 effect = chain->getEffectFromId_l(0);
5693 }
5694
5695 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005696}
5697
Eric Laurent464d5b32011-06-17 21:29:58 -07005698
Eric Laurent65b65452010-06-01 23:49:17 -07005699// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005700sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005701 const sp<AudioFlinger::Client>& client,
5702 const sp<IEffectClient>& effectClient,
5703 int32_t priority,
5704 int sessionId,
5705 effect_descriptor_t *desc,
5706 int *enabled,
5707 status_t *status
5708 )
5709{
5710 sp<EffectModule> effect;
5711 sp<EffectHandle> handle;
5712 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005713 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005714 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005715 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005716 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005717
Eric Laurent464d5b32011-06-17 21:29:58 -07005718 lStatus = initCheck();
5719 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00005720 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005721 goto Exit;
5722 }
5723
5724 // Do not allow effects with session ID 0 on direct output or duplicating threads
5725 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005726 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00005727 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005728 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005729 lStatus = BAD_VALUE;
5730 goto Exit;
5731 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005732 // Only Pre processor effects are allowed on input threads and only on input threads
5733 if ((mType == RECORD &&
5734 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5735 (mType != RECORD &&
5736 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005737 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005738 desc->name, desc->flags, mType);
5739 lStatus = BAD_VALUE;
5740 goto Exit;
5741 }
Eric Laurent65b65452010-06-01 23:49:17 -07005742
Steve Block71f2cf12011-10-20 11:56:00 +01005743 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005744
5745 { // scope for mLock
5746 Mutex::Autolock _l(mLock);
5747
5748 // check for existing effect chain with the requested audio session
5749 chain = getEffectChain_l(sessionId);
5750 if (chain == 0) {
5751 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005752 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005753 chain = new EffectChain(this, sessionId);
5754 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005755 chain->setStrategy(getStrategyForSession_l(sessionId));
5756 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005757 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005758 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005759 }
5760
Glenn Kasten70ed6b72012-01-10 10:46:34 -08005761 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005762
5763 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005764 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005765 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005766 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005767 if (lStatus != NO_ERROR) {
5768 goto Exit;
5769 }
5770 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005771 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005772 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005773 lStatus = effect->status();
5774 if (lStatus != NO_ERROR) {
5775 goto Exit;
5776 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005777 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005778 if (lStatus != NO_ERROR) {
5779 goto Exit;
5780 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005781 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005782
5783 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005784 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005785 }
5786 // create effect handle and connect it to effect module
5787 handle = new EffectHandle(effect, client, effectClient, priority);
5788 lStatus = effect->addHandle(handle);
5789 if (enabled) {
5790 *enabled = (int)effect->isEnabled();
5791 }
5792 }
5793
5794Exit:
5795 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005796 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005797 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005798 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005799 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005800 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005801 AudioSystem::unregisterEffect(effect->id());
5802 }
5803 if (chainCreated) {
5804 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005805 }
Eric Laurent65b65452010-06-01 23:49:17 -07005806 handle.clear();
5807 }
5808
5809 if(status) {
5810 *status = lStatus;
5811 }
5812 return handle;
5813}
5814
Eric Laurent464d5b32011-06-17 21:29:58 -07005815sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5816{
5817 sp<EffectModule> effect;
5818
5819 sp<EffectChain> chain = getEffectChain_l(sessionId);
5820 if (chain != 0) {
5821 effect = chain->getEffectFromId_l(effectId);
5822 }
5823 return effect;
5824}
5825
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005826// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5827// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005828status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005829{
5830 // check for existing effect chain with the requested audio session
5831 int sessionId = effect->sessionId();
5832 sp<EffectChain> chain = getEffectChain_l(sessionId);
5833 bool chainCreated = false;
5834
5835 if (chain == 0) {
5836 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005837 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005838 chain = new EffectChain(this, sessionId);
5839 addEffectChain_l(chain);
5840 chain->setStrategy(getStrategyForSession_l(sessionId));
5841 chainCreated = true;
5842 }
Steve Block71f2cf12011-10-20 11:56:00 +01005843 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005844
5845 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005846 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005847 this, effect->desc().name, chain.get());
5848 return BAD_VALUE;
5849 }
5850
5851 status_t status = chain->addEffect_l(effect);
5852 if (status != NO_ERROR) {
5853 if (chainCreated) {
5854 removeEffectChain_l(chain);
5855 }
5856 return status;
5857 }
5858
5859 effect->setDevice(mDevice);
5860 effect->setMode(mAudioFlinger->getMode());
5861 return NO_ERROR;
5862}
5863
Eric Laurent464d5b32011-06-17 21:29:58 -07005864void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005865
Steve Block71f2cf12011-10-20 11:56:00 +01005866 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005867 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005868 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5869 detachAuxEffect_l(effect->id());
5870 }
5871
5872 sp<EffectChain> chain = effect->chain().promote();
5873 if (chain != 0) {
5874 // remove effect chain if removing last effect
5875 if (chain->removeEffect_l(effect) == 0) {
5876 removeEffectChain_l(chain);
5877 }
5878 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00005879 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005880 }
5881}
5882
Eric Laurent464d5b32011-06-17 21:29:58 -07005883void AudioFlinger::ThreadBase::lockEffectChains_l(
5884 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5885{
5886 effectChains = mEffectChains;
5887 for (size_t i = 0; i < mEffectChains.size(); i++) {
5888 mEffectChains[i]->lock();
5889 }
5890}
5891
5892void AudioFlinger::ThreadBase::unlockEffectChains(
5893 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5894{
5895 for (size_t i = 0; i < effectChains.size(); i++) {
5896 effectChains[i]->unlock();
5897 }
5898}
5899
5900sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5901{
5902 Mutex::Autolock _l(mLock);
5903 return getEffectChain_l(sessionId);
5904}
5905
5906sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5907{
5908 sp<EffectChain> chain;
5909
5910 size_t size = mEffectChains.size();
5911 for (size_t i = 0; i < size; i++) {
5912 if (mEffectChains[i]->sessionId() == sessionId) {
5913 chain = mEffectChains[i];
5914 break;
5915 }
5916 }
5917 return chain;
5918}
5919
Glenn Kastenaccb1142012-01-04 11:00:47 -08005920void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent464d5b32011-06-17 21:29:58 -07005921{
5922 Mutex::Autolock _l(mLock);
5923 size_t size = mEffectChains.size();
5924 for (size_t i = 0; i < size; i++) {
5925 mEffectChains[i]->setMode_l(mode);
5926 }
5927}
5928
5929void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005930 const wp<EffectHandle>& handle,
5931 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005932
Eric Laurent53334cd2010-06-23 17:38:20 -07005933 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005934 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005935 // delete the effect module if removing last handle on it
5936 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005937 if (!effect->isPinned() || unpiniflast) {
5938 removeEffect_l(effect);
5939 AudioSystem::unregisterEffect(effect->id());
5940 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005941 }
5942}
5943
Eric Laurent65b65452010-06-01 23:49:17 -07005944status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5945{
5946 int session = chain->sessionId();
5947 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005948 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005949
Steve Block71f2cf12011-10-20 11:56:00 +01005950 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005951 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005952 // Only one effect chain can be present in direct output thread and it uses
5953 // the mix buffer as input
5954 if (mType != DIRECT) {
5955 size_t numSamples = mFrameCount * mChannelCount;
5956 buffer = new int16_t[numSamples];
5957 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005958 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005959 ownsBuffer = true;
5960 }
Eric Laurent65b65452010-06-01 23:49:17 -07005961
Eric Laurent53334cd2010-06-23 17:38:20 -07005962 // Attach all tracks with same session ID to this chain.
5963 for (size_t i = 0; i < mTracks.size(); ++i) {
5964 sp<Track> track = mTracks[i];
5965 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005966 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005967 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005968 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005969 }
5970 }
5971
5972 // indicate all active tracks in the chain
5973 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5974 sp<Track> track = mActiveTracks[i].promote();
5975 if (track == 0) continue;
5976 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005977 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005978 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005979 }
Eric Laurent65b65452010-06-01 23:49:17 -07005980 }
5981 }
5982
Eric Laurent53334cd2010-06-23 17:38:20 -07005983 chain->setInBuffer(buffer, ownsBuffer);
5984 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005985 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005986 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005987 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5988 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005989 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005990 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5991 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005992 // Effect chain for other sessions are inserted at beginning of effect
5993 // chains list to be processed before output mix effects. Relative order between other
5994 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005995 size_t size = mEffectChains.size();
5996 size_t i = 0;
5997 for (i = 0; i < size; i++) {
5998 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005999 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006000 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006001 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07006002
6003 return NO_ERROR;
6004}
6005
6006size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6007{
6008 int session = chain->sessionId();
6009
Steve Block71f2cf12011-10-20 11:56:00 +01006010 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07006011
6012 for (size_t i = 0; i < mEffectChains.size(); i++) {
6013 if (chain == mEffectChains[i]) {
6014 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07006015 // detach all active tracks from the chain
6016 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6017 sp<Track> track = mActiveTracks[i].promote();
6018 if (track == 0) continue;
6019 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01006020 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07006021 chain.get(), session);
6022 chain->decActiveTrackCnt();
6023 }
6024 }
6025
Eric Laurent65b65452010-06-01 23:49:17 -07006026 // detach all tracks with same session ID from this chain
6027 for (size_t i = 0; i < mTracks.size(); ++i) {
6028 sp<Track> track = mTracks[i];
6029 if (session == track->sessionId()) {
6030 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07006031 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07006032 }
6033 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006034 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006035 }
6036 }
6037 return mEffectChains.size();
6038}
6039
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006040status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6041 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006042{
6043 Mutex::Autolock _l(mLock);
6044 return attachAuxEffect_l(track, EffectId);
6045}
6046
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006047status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6048 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006049{
6050 status_t status = NO_ERROR;
6051
6052 if (EffectId == 0) {
6053 track->setAuxBuffer(0, NULL);
6054 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006055 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6056 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006057 if (effect != 0) {
6058 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6059 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6060 } else {
6061 status = INVALID_OPERATION;
6062 }
6063 } else {
6064 status = BAD_VALUE;
6065 }
6066 }
6067 return status;
6068}
6069
6070void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6071{
6072 for (size_t i = 0; i < mTracks.size(); ++i) {
6073 sp<Track> track = mTracks[i];
6074 if (track->auxEffectId() == effectId) {
6075 attachAuxEffect_l(track, 0);
6076 }
6077 }
6078}
6079
Eric Laurent464d5b32011-06-17 21:29:58 -07006080status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6081{
6082 // only one chain per input thread
6083 if (mEffectChains.size() != 0) {
6084 return INVALID_OPERATION;
6085 }
Steve Block71f2cf12011-10-20 11:56:00 +01006086 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006087
6088 chain->setInBuffer(NULL);
6089 chain->setOutBuffer(NULL);
6090
Eric Laurentf82fccd2011-07-27 19:49:51 -07006091 checkSuspendOnAddEffectChain_l(chain);
6092
Eric Laurent464d5b32011-06-17 21:29:58 -07006093 mEffectChains.add(chain);
6094
6095 return NO_ERROR;
6096}
6097
6098size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6099{
Steve Block71f2cf12011-10-20 11:56:00 +01006100 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006101 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006102 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6103 chain.get(), mEffectChains.size(), this);
6104 if (mEffectChains.size() == 1) {
6105 mEffectChains.removeAt(0);
6106 }
6107 return 0;
6108}
6109
Eric Laurent65b65452010-06-01 23:49:17 -07006110// ----------------------------------------------------------------------------
6111// EffectModule implementation
6112// ----------------------------------------------------------------------------
6113
6114#undef LOG_TAG
6115#define LOG_TAG "AudioFlinger::EffectModule"
6116
6117AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6118 const wp<AudioFlinger::EffectChain>& chain,
6119 effect_descriptor_t *desc,
6120 int id,
6121 int sessionId)
6122 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006123 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006124{
Steve Block71f2cf12011-10-20 11:56:00 +01006125 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006126 int lStatus;
6127 sp<ThreadBase> thread = mThread.promote();
6128 if (thread == 0) {
6129 return;
6130 }
Eric Laurent65b65452010-06-01 23:49:17 -07006131
6132 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6133
6134 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006135 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006136
Eric Laurent65b65452010-06-01 23:49:17 -07006137 if (mStatus != NO_ERROR) {
6138 return;
6139 }
6140 lStatus = init();
6141 if (lStatus < 0) {
6142 mStatus = lStatus;
6143 goto Error;
6144 }
6145
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006146 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6147 mPinned = true;
6148 }
Steve Block71f2cf12011-10-20 11:56:00 +01006149 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006150 return;
6151Error:
6152 EffectRelease(mEffectInterface);
6153 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006154 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006155}
6156
6157AudioFlinger::EffectModule::~EffectModule()
6158{
Steve Block71f2cf12011-10-20 11:56:00 +01006159 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006160 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006161 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6162 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6163 sp<ThreadBase> thread = mThread.promote();
6164 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006165 audio_stream_t *stream = thread->stream();
6166 if (stream != NULL) {
6167 stream->remove_audio_effect(stream, mEffectInterface);
6168 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006169 }
6170 }
Eric Laurent65b65452010-06-01 23:49:17 -07006171 // release effect engine
6172 EffectRelease(mEffectInterface);
6173 }
6174}
6175
6176status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6177{
6178 status_t status;
6179
6180 Mutex::Autolock _l(mLock);
6181 // First handle in mHandles has highest priority and controls the effect module
6182 int priority = handle->priority();
6183 size_t size = mHandles.size();
6184 sp<EffectHandle> h;
6185 size_t i;
6186 for (i = 0; i < size; i++) {
6187 h = mHandles[i].promote();
6188 if (h == 0) continue;
6189 if (h->priority() <= priority) break;
6190 }
6191 // if inserted in first place, move effect control from previous owner to this handle
6192 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006193 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006194 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006195 enabled = h->enabled();
6196 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006197 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006198 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006199 status = NO_ERROR;
6200 } else {
6201 status = ALREADY_EXISTS;
6202 }
Steve Block71f2cf12011-10-20 11:56:00 +01006203 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006204 mHandles.insertAt(handle, i);
6205 return status;
6206}
6207
6208size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6209{
6210 Mutex::Autolock _l(mLock);
6211 size_t size = mHandles.size();
6212 size_t i;
6213 for (i = 0; i < size; i++) {
6214 if (mHandles[i] == handle) break;
6215 }
6216 if (i == size) {
6217 return size;
6218 }
Steve Block71f2cf12011-10-20 11:56:00 +01006219 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006220
6221 bool enabled = false;
6222 EffectHandle *hdl = handle.unsafe_get();
6223 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006224 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006225 enabled = hdl->enabled();
6226 }
Eric Laurent65b65452010-06-01 23:49:17 -07006227 mHandles.removeAt(i);
6228 size = mHandles.size();
6229 // if removed from first place, move effect control from this handle to next in line
6230 if (i == 0 && size != 0) {
6231 sp<EffectHandle> h = mHandles[0].promote();
6232 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006233 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006234 }
6235 }
6236
Eric Laurent21b5c472011-07-26 20:54:46 -07006237 // Prevent calls to process() and other functions on effect interface from now on.
6238 // The effect engine will be released by the destructor when the last strong reference on
6239 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006240 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006241 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006242 }
6243
Eric Laurent65b65452010-06-01 23:49:17 -07006244 return size;
6245}
6246
Eric Laurentf82fccd2011-07-27 19:49:51 -07006247sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6248{
6249 Mutex::Autolock _l(mLock);
6250 sp<EffectHandle> handle;
6251 if (mHandles.size() != 0) {
6252 handle = mHandles[0].promote();
6253 }
6254 return handle;
6255}
6256
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006257void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006258{
Steve Block71f2cf12011-10-20 11:56:00 +01006259 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006260 // keep a strong reference on this EffectModule to avoid calling the
6261 // destructor before we exit
6262 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006263 {
6264 sp<ThreadBase> thread = mThread.promote();
6265 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006266 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006267 }
6268 }
6269}
6270
Eric Laurent7d850f22010-07-09 13:34:17 -07006271void AudioFlinger::EffectModule::updateState() {
6272 Mutex::Autolock _l(mLock);
6273
6274 switch (mState) {
6275 case RESTART:
6276 reset_l();
6277 // FALL THROUGH
6278
6279 case STARTING:
6280 // clear auxiliary effect input buffer for next accumulation
6281 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6282 memset(mConfig.inputCfg.buffer.raw,
6283 0,
6284 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6285 }
6286 start_l();
6287 mState = ACTIVE;
6288 break;
6289 case STOPPING:
6290 stop_l();
6291 mDisableWaitCnt = mMaxDisableWaitCnt;
6292 mState = STOPPED;
6293 break;
6294 case STOPPED:
6295 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6296 // turn off sequence.
6297 if (--mDisableWaitCnt == 0) {
6298 reset_l();
6299 mState = IDLE;
6300 }
6301 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006302 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006303 break;
6304 }
6305}
6306
Eric Laurent65b65452010-06-01 23:49:17 -07006307void AudioFlinger::EffectModule::process()
6308{
6309 Mutex::Autolock _l(mLock);
6310
Eric Laurent21b5c472011-07-26 20:54:46 -07006311 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006312 mConfig.inputCfg.buffer.raw == NULL ||
6313 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006314 return;
6315 }
6316
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006317 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006318 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6319 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006320 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006321 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006322 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006323 }
6324
Eric Laurent65b65452010-06-01 23:49:17 -07006325 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006326 int ret = (*mEffectInterface)->process(mEffectInterface,
6327 &mConfig.inputCfg.buffer,
6328 &mConfig.outputCfg.buffer);
6329
6330 // force transition to IDLE state when engine is ready
6331 if (mState == STOPPED && ret == -ENODATA) {
6332 mDisableWaitCnt = 1;
6333 }
Eric Laurent65b65452010-06-01 23:49:17 -07006334
6335 // clear auxiliary effect input buffer for next accumulation
6336 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006337 memset(mConfig.inputCfg.buffer.raw, 0,
6338 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006339 }
6340 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006341 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6342 // If an insert effect is idle and input buffer is different from output buffer,
6343 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006344 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006345 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006346 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6347 int16_t *in = mConfig.inputCfg.buffer.s16;
6348 int16_t *out = mConfig.outputCfg.buffer.s16;
6349 for (size_t i = 0; i < frameCnt; i++) {
6350 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006351 }
Eric Laurent65b65452010-06-01 23:49:17 -07006352 }
6353 }
6354}
6355
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006356void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006357{
6358 if (mEffectInterface == NULL) {
6359 return;
6360 }
6361 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6362}
6363
6364status_t AudioFlinger::EffectModule::configure()
6365{
6366 uint32_t channels;
6367 if (mEffectInterface == NULL) {
6368 return NO_INIT;
6369 }
6370
6371 sp<ThreadBase> thread = mThread.promote();
6372 if (thread == 0) {
6373 return DEAD_OBJECT;
6374 }
6375
6376 // TODO: handle configuration of effects replacing track process
6377 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006378 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006379 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006380 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006381 }
6382
6383 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006384 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006385 } else {
6386 mConfig.inputCfg.channels = channels;
6387 }
6388 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006389 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6390 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006391 mConfig.inputCfg.samplingRate = thread->sampleRate();
6392 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6393 mConfig.inputCfg.bufferProvider.cookie = NULL;
6394 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6395 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6396 mConfig.outputCfg.bufferProvider.cookie = NULL;
6397 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6398 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6399 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6400 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006401 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006402 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006403 // - in other sessions:
6404 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6405 // other effect: overwrites output buffer: input buffer == output buffer
6406 // Auxiliary effect:
6407 // accumulates in output buffer: input buffer != output buffer
6408 // Therefore: accumulate <=> input buffer != output buffer
6409 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6410 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6411 } else {
6412 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6413 }
6414 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6415 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6416 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6417 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6418
Steve Block71f2cf12011-10-20 11:56:00 +01006419 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006420 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6421
Eric Laurent65b65452010-06-01 23:49:17 -07006422 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006423 uint32_t size = sizeof(int);
6424 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006425 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006426 sizeof(effect_config_t),
6427 &mConfig,
6428 &size,
6429 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006430 if (status == 0) {
6431 status = cmdStatus;
6432 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006433
6434 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6435 (1000 * mConfig.outputCfg.buffer.frameCount);
6436
Eric Laurent65b65452010-06-01 23:49:17 -07006437 return status;
6438}
6439
6440status_t AudioFlinger::EffectModule::init()
6441{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006442 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006443 if (mEffectInterface == NULL) {
6444 return NO_INIT;
6445 }
6446 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006447 uint32_t size = sizeof(status_t);
6448 status_t status = (*mEffectInterface)->command(mEffectInterface,
6449 EFFECT_CMD_INIT,
6450 0,
6451 NULL,
6452 &size,
6453 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006454 if (status == 0) {
6455 status = cmdStatus;
6456 }
6457 return status;
6458}
6459
Eric Laurent6fccbd02011-10-05 17:42:25 -07006460status_t AudioFlinger::EffectModule::start()
6461{
6462 Mutex::Autolock _l(mLock);
6463 return start_l();
6464}
6465
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006466status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006467{
6468 if (mEffectInterface == NULL) {
6469 return NO_INIT;
6470 }
6471 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006472 uint32_t size = sizeof(status_t);
6473 status_t status = (*mEffectInterface)->command(mEffectInterface,
6474 EFFECT_CMD_ENABLE,
6475 0,
6476 NULL,
6477 &size,
6478 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006479 if (status == 0) {
6480 status = cmdStatus;
6481 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006482 if (status == 0 &&
6483 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6484 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6485 sp<ThreadBase> thread = mThread.promote();
6486 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006487 audio_stream_t *stream = thread->stream();
6488 if (stream != NULL) {
6489 stream->add_audio_effect(stream, mEffectInterface);
6490 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006491 }
6492 }
Eric Laurent65b65452010-06-01 23:49:17 -07006493 return status;
6494}
6495
Eric Laurent21b5c472011-07-26 20:54:46 -07006496status_t AudioFlinger::EffectModule::stop()
6497{
6498 Mutex::Autolock _l(mLock);
6499 return stop_l();
6500}
6501
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006502status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006503{
6504 if (mEffectInterface == NULL) {
6505 return NO_INIT;
6506 }
6507 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006508 uint32_t size = sizeof(status_t);
6509 status_t status = (*mEffectInterface)->command(mEffectInterface,
6510 EFFECT_CMD_DISABLE,
6511 0,
6512 NULL,
6513 &size,
6514 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006515 if (status == 0) {
6516 status = cmdStatus;
6517 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006518 if (status == 0 &&
6519 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6520 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6521 sp<ThreadBase> thread = mThread.promote();
6522 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006523 audio_stream_t *stream = thread->stream();
6524 if (stream != NULL) {
6525 stream->remove_audio_effect(stream, mEffectInterface);
6526 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006527 }
6528 }
Eric Laurent65b65452010-06-01 23:49:17 -07006529 return status;
6530}
6531
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006532status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6533 uint32_t cmdSize,
6534 void *pCmdData,
6535 uint32_t *replySize,
6536 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006537{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006538 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006539// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006540
Eric Laurent21b5c472011-07-26 20:54:46 -07006541 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006542 return NO_INIT;
6543 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006544 status_t status = (*mEffectInterface)->command(mEffectInterface,
6545 cmdCode,
6546 cmdSize,
6547 pCmdData,
6548 replySize,
6549 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006550 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006551 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006552 for (size_t i = 1; i < mHandles.size(); i++) {
6553 sp<EffectHandle> h = mHandles[i].promote();
6554 if (h != 0) {
6555 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6556 }
6557 }
6558 }
6559 return status;
6560}
6561
6562status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6563{
Eric Laurent6752ec82011-08-10 10:37:50 -07006564
Eric Laurent65b65452010-06-01 23:49:17 -07006565 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006566 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006567
6568 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006569 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6570 if (enabled && status != NO_ERROR) {
6571 return status;
6572 }
6573
Eric Laurent65b65452010-06-01 23:49:17 -07006574 switch (mState) {
6575 // going from disabled to enabled
6576 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006577 mState = STARTING;
6578 break;
6579 case STOPPED:
6580 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006581 break;
6582 case STOPPING:
6583 mState = ACTIVE;
6584 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006585
6586 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006587 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006588 mState = STOPPED;
6589 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006590 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006591 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006592 break;
6593 case ACTIVE:
6594 mState = STOPPING;
6595 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006596 case DESTROYED:
6597 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006598 }
6599 for (size_t i = 1; i < mHandles.size(); i++) {
6600 sp<EffectHandle> h = mHandles[i].promote();
6601 if (h != 0) {
6602 h->setEnabled(enabled);
6603 }
6604 }
6605 }
6606 return NO_ERROR;
6607}
6608
6609bool AudioFlinger::EffectModule::isEnabled()
6610{
6611 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006612 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006613 case STARTING:
6614 case ACTIVE:
6615 return true;
6616 case IDLE:
6617 case STOPPING:
6618 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006619 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006620 default:
6621 return false;
6622 }
6623}
6624
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006625bool AudioFlinger::EffectModule::isProcessEnabled()
6626{
6627 switch (mState) {
6628 case RESTART:
6629 case ACTIVE:
6630 case STOPPING:
6631 case STOPPED:
6632 return true;
6633 case IDLE:
6634 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006635 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006636 default:
6637 return false;
6638 }
6639}
6640
Eric Laurent65b65452010-06-01 23:49:17 -07006641status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6642{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006643 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006644 status_t status = NO_ERROR;
6645
6646 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6647 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006648 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006649 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6650 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006651 status_t cmdStatus;
6652 uint32_t volume[2];
6653 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006654 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006655 volume[0] = *left;
6656 volume[1] = *right;
6657 if (controller) {
6658 pVolume = volume;
6659 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006660 status = (*mEffectInterface)->command(mEffectInterface,
6661 EFFECT_CMD_SET_VOLUME,
6662 size,
6663 volume,
6664 &size,
6665 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006666 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6667 *left = volume[0];
6668 *right = volume[1];
6669 }
6670 }
6671 return status;
6672}
6673
6674status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6675{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006676 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006677 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006678 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6679 // audio pre processing modules on RecordThread can receive both output and
6680 // input device indication in the same call
6681 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6682 if (dev) {
6683 status_t cmdStatus;
6684 uint32_t size = sizeof(status_t);
6685
6686 status = (*mEffectInterface)->command(mEffectInterface,
6687 EFFECT_CMD_SET_DEVICE,
6688 sizeof(uint32_t),
6689 &dev,
6690 &size,
6691 &cmdStatus);
6692 if (status == NO_ERROR) {
6693 status = cmdStatus;
6694 }
6695 }
6696 dev = device & AUDIO_DEVICE_IN_ALL;
6697 if (dev) {
6698 status_t cmdStatus;
6699 uint32_t size = sizeof(status_t);
6700
6701 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6702 EFFECT_CMD_SET_INPUT_DEVICE,
6703 sizeof(uint32_t),
6704 &dev,
6705 &size,
6706 &cmdStatus);
6707 if (status2 == NO_ERROR) {
6708 status2 = cmdStatus;
6709 }
6710 if (status == NO_ERROR) {
6711 status = status2;
6712 }
Eric Laurent65b65452010-06-01 23:49:17 -07006713 }
6714 }
6715 return status;
6716}
6717
Glenn Kastenaccb1142012-01-04 11:00:47 -08006718status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006719{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006720 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006721 status_t status = NO_ERROR;
6722 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006723 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006724 uint32_t size = sizeof(status_t);
6725 status = (*mEffectInterface)->command(mEffectInterface,
6726 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenaccb1142012-01-04 11:00:47 -08006727 sizeof(audio_mode_t),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006728 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006729 &size,
6730 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006731 if (status == NO_ERROR) {
6732 status = cmdStatus;
6733 }
6734 }
6735 return status;
6736}
6737
Eric Laurentf82fccd2011-07-27 19:49:51 -07006738void AudioFlinger::EffectModule::setSuspended(bool suspended)
6739{
6740 Mutex::Autolock _l(mLock);
6741 mSuspended = suspended;
6742}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006743
6744bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006745{
6746 Mutex::Autolock _l(mLock);
6747 return mSuspended;
6748}
6749
Eric Laurent65b65452010-06-01 23:49:17 -07006750status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6751{
6752 const size_t SIZE = 256;
6753 char buffer[SIZE];
6754 String8 result;
6755
6756 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6757 result.append(buffer);
6758
6759 bool locked = tryLock(mLock);
6760 // failed to lock - AudioFlinger is probably deadlocked
6761 if (!locked) {
6762 result.append("\t\tCould not lock Fx mutex:\n");
6763 }
6764
6765 result.append("\t\tSession Status State Engine:\n");
6766 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6767 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6768 result.append(buffer);
6769
6770 result.append("\t\tDescriptor:\n");
6771 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6772 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6773 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6774 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6775 result.append(buffer);
6776 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6777 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6778 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6779 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6780 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006781 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006782 mDescriptor.apiVersion,
6783 mDescriptor.flags);
6784 result.append(buffer);
6785 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6786 mDescriptor.name);
6787 result.append(buffer);
6788 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6789 mDescriptor.implementor);
6790 result.append(buffer);
6791
6792 result.append("\t\t- Input configuration:\n");
6793 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6794 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6795 (uint32_t)mConfig.inputCfg.buffer.raw,
6796 mConfig.inputCfg.buffer.frameCount,
6797 mConfig.inputCfg.samplingRate,
6798 mConfig.inputCfg.channels,
6799 mConfig.inputCfg.format);
6800 result.append(buffer);
6801
6802 result.append("\t\t- Output configuration:\n");
6803 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6804 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6805 (uint32_t)mConfig.outputCfg.buffer.raw,
6806 mConfig.outputCfg.buffer.frameCount,
6807 mConfig.outputCfg.samplingRate,
6808 mConfig.outputCfg.channels,
6809 mConfig.outputCfg.format);
6810 result.append(buffer);
6811
6812 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6813 result.append(buffer);
6814 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6815 for (size_t i = 0; i < mHandles.size(); ++i) {
6816 sp<EffectHandle> handle = mHandles[i].promote();
6817 if (handle != 0) {
6818 handle->dump(buffer, SIZE);
6819 result.append(buffer);
6820 }
6821 }
6822
6823 result.append("\n");
6824
6825 write(fd, result.string(), result.length());
6826
6827 if (locked) {
6828 mLock.unlock();
6829 }
6830
6831 return NO_ERROR;
6832}
6833
6834// ----------------------------------------------------------------------------
6835// EffectHandle implementation
6836// ----------------------------------------------------------------------------
6837
6838#undef LOG_TAG
6839#define LOG_TAG "AudioFlinger::EffectHandle"
6840
6841AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6842 const sp<AudioFlinger::Client>& client,
6843 const sp<IEffectClient>& effectClient,
6844 int32_t priority)
6845 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006846 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006847 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006848{
Steve Block71f2cf12011-10-20 11:56:00 +01006849 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006850
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006851 if (client == 0) {
6852 return;
6853 }
Eric Laurent65b65452010-06-01 23:49:17 -07006854 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6855 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6856 if (mCblkMemory != 0) {
6857 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6858
6859 if (mCblk) {
6860 new(mCblk) effect_param_cblk_t();
6861 mBuffer = (uint8_t *)mCblk + bufOffset;
6862 }
6863 } else {
Steve Block3762c312012-01-06 19:20:56 +00006864 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006865 return;
6866 }
6867}
6868
6869AudioFlinger::EffectHandle::~EffectHandle()
6870{
Steve Block71f2cf12011-10-20 11:56:00 +01006871 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006872 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006873 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006874}
6875
6876status_t AudioFlinger::EffectHandle::enable()
6877{
Steve Block71f2cf12011-10-20 11:56:00 +01006878 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006879 if (!mHasControl) return INVALID_OPERATION;
6880 if (mEffect == 0) return DEAD_OBJECT;
6881
Eric Laurent6752ec82011-08-10 10:37:50 -07006882 if (mEnabled) {
6883 return NO_ERROR;
6884 }
6885
Eric Laurentf82fccd2011-07-27 19:49:51 -07006886 mEnabled = true;
6887
6888 sp<ThreadBase> thread = mEffect->thread().promote();
6889 if (thread != 0) {
6890 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6891 }
6892
6893 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6894 if (mEffect->suspended()) {
6895 return NO_ERROR;
6896 }
6897
Eric Laurent6752ec82011-08-10 10:37:50 -07006898 status_t status = mEffect->setEnabled(true);
6899 if (status != NO_ERROR) {
6900 if (thread != 0) {
6901 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6902 }
6903 mEnabled = false;
6904 }
6905 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006906}
6907
6908status_t AudioFlinger::EffectHandle::disable()
6909{
Steve Block71f2cf12011-10-20 11:56:00 +01006910 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006911 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006912 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006913
Eric Laurent6752ec82011-08-10 10:37:50 -07006914 if (!mEnabled) {
6915 return NO_ERROR;
6916 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006917 mEnabled = false;
6918
6919 if (mEffect->suspended()) {
6920 return NO_ERROR;
6921 }
6922
6923 status_t status = mEffect->setEnabled(false);
6924
6925 sp<ThreadBase> thread = mEffect->thread().promote();
6926 if (thread != 0) {
6927 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6928 }
6929
6930 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006931}
6932
6933void AudioFlinger::EffectHandle::disconnect()
6934{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006935 disconnect(true);
6936}
6937
6938void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6939{
Steve Block71f2cf12011-10-20 11:56:00 +01006940 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006941 if (mEffect == 0) {
6942 return;
6943 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006944 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006945
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006946 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006947 sp<ThreadBase> thread = mEffect->thread().promote();
6948 if (thread != 0) {
6949 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6950 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006951 }
6952
Eric Laurent65b65452010-06-01 23:49:17 -07006953 // release sp on module => module destructor can be called now
6954 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006955 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006956 if (mCblk) {
6957 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6958 }
6959 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006960 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6961 mClient.clear();
6962 }
6963}
6964
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006965status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6966 uint32_t cmdSize,
6967 void *pCmdData,
6968 uint32_t *replySize,
6969 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006970{
Steve Block71f2cf12011-10-20 11:56:00 +01006971// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006972// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006973
6974 // only get parameter command is permitted for applications not controlling the effect
6975 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6976 return INVALID_OPERATION;
6977 }
6978 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006979 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006980
6981 // handle commands that are not forwarded transparently to effect engine
6982 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6983 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6984 // no risk to block the whole media server process or mixer threads is we are stuck here
6985 Mutex::Autolock _l(mCblk->lock);
6986 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6987 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6988 mCblk->serverIndex = 0;
6989 mCblk->clientIndex = 0;
6990 return BAD_VALUE;
6991 }
6992 status_t status = NO_ERROR;
6993 while (mCblk->serverIndex < mCblk->clientIndex) {
6994 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006995 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006996 int *p = (int *)(mBuffer + mCblk->serverIndex);
6997 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006998 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00006999 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07007000 break;
7001 }
Eric Laurent65b65452010-06-01 23:49:17 -07007002 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07007003 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007004 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07007005 mCblk->serverIndex += size;
7006 continue;
7007 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007008 uint32_t psize = sizeof(effect_param_t) +
7009 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7010 param->vsize;
7011 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7012 psize,
7013 p,
7014 &rsize,
7015 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07007016 // stop at first error encountered
7017 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07007018 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07007019 *(int *)pReplyData = reply;
7020 break;
7021 } else if (reply != NO_ERROR) {
7022 *(int *)pReplyData = reply;
7023 break;
Eric Laurent65b65452010-06-01 23:49:17 -07007024 }
7025 mCblk->serverIndex += size;
7026 }
7027 mCblk->serverIndex = 0;
7028 mCblk->clientIndex = 0;
7029 return status;
7030 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007031 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007032 return enable();
7033 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007034 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007035 return disable();
7036 }
7037
7038 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7039}
7040
7041sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7042 return mCblkMemory;
7043}
7044
Eric Laurentf82fccd2011-07-27 19:49:51 -07007045void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007046{
Steve Block71f2cf12011-10-20 11:56:00 +01007047 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007048
7049 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007050 mEnabled = enabled;
7051
Eric Laurent65b65452010-06-01 23:49:17 -07007052 if (signal && mEffectClient != 0) {
7053 mEffectClient->controlStatusChanged(hasControl);
7054 }
7055}
7056
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007057void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7058 uint32_t cmdSize,
7059 void *pCmdData,
7060 uint32_t replySize,
7061 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007062{
7063 if (mEffectClient != 0) {
7064 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7065 }
7066}
7067
7068
7069
7070void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7071{
7072 if (mEffectClient != 0) {
7073 mEffectClient->enableStatusChanged(enabled);
7074 }
7075}
7076
7077status_t AudioFlinger::EffectHandle::onTransact(
7078 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7079{
7080 return BnEffect::onTransact(code, data, reply, flags);
7081}
7082
7083
7084void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7085{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007086 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007087
7088 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7089 (mClient == NULL) ? getpid() : mClient->pid(),
7090 mPriority,
7091 mHasControl,
7092 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007093 mCblk ? mCblk->clientIndex : 0,
7094 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007095 );
7096
7097 if (locked) {
7098 mCblk->lock.unlock();
7099 }
7100}
7101
7102#undef LOG_TAG
7103#define LOG_TAG "AudioFlinger::EffectChain"
7104
7105AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7106 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007107 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007108 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7109 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007110{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007111 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007112 sp<ThreadBase> thread = mThread.promote();
7113 if (thread == 0) {
7114 return;
7115 }
7116 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7117 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007118}
7119
7120AudioFlinger::EffectChain::~EffectChain()
7121{
7122 if (mOwnInBuffer) {
7123 delete mInBuffer;
7124 }
7125
7126}
7127
Eric Laurentf82fccd2011-07-27 19:49:51 -07007128// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007129sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007130{
7131 sp<EffectModule> effect;
7132 size_t size = mEffects.size();
7133
7134 for (size_t i = 0; i < size; i++) {
7135 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7136 effect = mEffects[i];
7137 break;
7138 }
7139 }
7140 return effect;
7141}
7142
Eric Laurentf82fccd2011-07-27 19:49:51 -07007143// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007144sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007145{
7146 sp<EffectModule> effect;
7147 size_t size = mEffects.size();
7148
7149 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007150 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7151 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007152 effect = mEffects[i];
7153 break;
7154 }
7155 }
7156 return effect;
7157}
7158
Eric Laurentf82fccd2011-07-27 19:49:51 -07007159// getEffectFromType_l() must be called with ThreadBase::mLock held
7160sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7161 const effect_uuid_t *type)
7162{
7163 sp<EffectModule> effect;
7164 size_t size = mEffects.size();
7165
7166 for (size_t i = 0; i < size; i++) {
7167 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7168 effect = mEffects[i];
7169 break;
7170 }
7171 }
7172 return effect;
7173}
7174
Eric Laurent65b65452010-06-01 23:49:17 -07007175// Must be called with EffectChain::mLock locked
7176void AudioFlinger::EffectChain::process_l()
7177{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007178 sp<ThreadBase> thread = mThread.promote();
7179 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007180 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007181 return;
7182 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007183 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7184 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007185 // always process effects unless no more tracks are on the session and the effect tail
7186 // has been rendered
7187 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007188 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007189 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007190
Eric Laurentf9c361d2011-11-11 15:42:52 -08007191 if (!tracksOnSession && mTailBufferCount == 0) {
7192 doProcess = false;
7193 }
7194
7195 if (activeTrackCnt() == 0) {
7196 // if no track is active and the effect tail has not been rendered,
7197 // the input buffer must be cleared here as the mixer process will not do it
7198 if (tracksOnSession || mTailBufferCount > 0) {
7199 size_t numSamples = thread->frameCount() * thread->channelCount();
7200 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7201 if (mTailBufferCount > 0) {
7202 mTailBufferCount--;
7203 }
7204 }
7205 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007206 }
7207
Eric Laurent65b65452010-06-01 23:49:17 -07007208 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007209 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007210 for (size_t i = 0; i < size; i++) {
7211 mEffects[i]->process();
7212 }
Eric Laurent65b65452010-06-01 23:49:17 -07007213 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007214 for (size_t i = 0; i < size; i++) {
7215 mEffects[i]->updateState();
7216 }
Eric Laurent65b65452010-06-01 23:49:17 -07007217}
7218
Eric Laurent76c40f72010-07-15 12:50:15 -07007219// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007220status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007221{
7222 effect_descriptor_t desc = effect->desc();
7223 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7224
7225 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007226 effect->setChain(this);
7227 sp<ThreadBase> thread = mThread.promote();
7228 if (thread == 0) {
7229 return NO_INIT;
7230 }
7231 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007232
7233 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7234 // Auxiliary effects are inserted at the beginning of mEffects vector as
7235 // they are processed first and accumulated in chain input buffer
7236 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007237
Eric Laurent65b65452010-06-01 23:49:17 -07007238 // the input buffer for auxiliary effect contains mono samples in
7239 // 32 bit format. This is to avoid saturation in AudoMixer
7240 // accumulation stage. Saturation is done in EffectModule::process() before
7241 // calling the process in effect engine
7242 size_t numSamples = thread->frameCount();
7243 int32_t *buffer = new int32_t[numSamples];
7244 memset(buffer, 0, numSamples * sizeof(int32_t));
7245 effect->setInBuffer((int16_t *)buffer);
7246 // auxiliary effects output samples to chain input buffer for further processing
7247 // by insert effects
7248 effect->setOutBuffer(mInBuffer);
7249 } else {
7250 // Insert effects are inserted at the end of mEffects vector as they are processed
7251 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007252 // Insert effect order as a function of indicated preference:
7253 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7254 // another effect is present
7255 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7256 // last effect claiming first position
7257 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7258 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007259 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007260 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7261 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007262
7263 int size = (int)mEffects.size();
7264 int idx_insert = size;
7265 int idx_insert_first = -1;
7266 int idx_insert_last = -1;
7267
7268 for (int i = 0; i < size; i++) {
7269 effect_descriptor_t d = mEffects[i]->desc();
7270 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7271 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7272 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7273 // check invalid effect chaining combinations
7274 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007275 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007276 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007277 return INVALID_OPERATION;
7278 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007279 // remember position of first insert effect and by default
7280 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007281 if (idx_insert == size) {
7282 idx_insert = i;
7283 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007284 // remember position of last insert effect claiming
7285 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007286 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7287 idx_insert_first = i;
7288 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007289 // remember position of first insert effect claiming
7290 // last position
7291 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7292 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007293 idx_insert_last = i;
7294 }
7295 }
7296 }
7297
Eric Laurent53334cd2010-06-23 17:38:20 -07007298 // modify idx_insert from first position if needed
7299 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7300 if (idx_insert_last != -1) {
7301 idx_insert = idx_insert_last;
7302 } else {
7303 idx_insert = size;
7304 }
7305 } else {
7306 if (idx_insert_first != -1) {
7307 idx_insert = idx_insert_first + 1;
7308 }
Eric Laurent65b65452010-06-01 23:49:17 -07007309 }
7310
7311 // always read samples from chain input buffer
7312 effect->setInBuffer(mInBuffer);
7313
7314 // if last effect in the chain, output samples to chain
7315 // output buffer, otherwise to chain input buffer
7316 if (idx_insert == size) {
7317 if (idx_insert != 0) {
7318 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7319 mEffects[idx_insert-1]->configure();
7320 }
7321 effect->setOutBuffer(mOutBuffer);
7322 } else {
7323 effect->setOutBuffer(mInBuffer);
7324 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007325 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007326
Steve Block71f2cf12011-10-20 11:56:00 +01007327 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007328 }
7329 effect->configure();
7330 return NO_ERROR;
7331}
7332
Eric Laurent76c40f72010-07-15 12:50:15 -07007333// removeEffect_l() must be called with PlaybackThread::mLock held
7334size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007335{
7336 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007337 int size = (int)mEffects.size();
7338 int i;
7339 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7340
7341 for (i = 0; i < size; i++) {
7342 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007343 // calling stop here will remove pre-processing effect from the audio HAL.
7344 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7345 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007346 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7347 mEffects[i]->state() == EffectModule::STOPPING) {
7348 mEffects[i]->stop();
7349 }
Eric Laurent65b65452010-06-01 23:49:17 -07007350 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7351 delete[] effect->inBuffer();
7352 } else {
7353 if (i == size - 1 && i != 0) {
7354 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7355 mEffects[i - 1]->configure();
7356 }
7357 }
7358 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007359 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007360 break;
7361 }
7362 }
Eric Laurent65b65452010-06-01 23:49:17 -07007363
7364 return mEffects.size();
7365}
7366
Eric Laurent76c40f72010-07-15 12:50:15 -07007367// setDevice_l() must be called with PlaybackThread::mLock held
7368void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007369{
7370 size_t size = mEffects.size();
7371 for (size_t i = 0; i < size; i++) {
7372 mEffects[i]->setDevice(device);
7373 }
7374}
7375
Eric Laurent76c40f72010-07-15 12:50:15 -07007376// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenaccb1142012-01-04 11:00:47 -08007377void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007378{
7379 size_t size = mEffects.size();
7380 for (size_t i = 0; i < size; i++) {
7381 mEffects[i]->setMode(mode);
7382 }
7383}
7384
Eric Laurent76c40f72010-07-15 12:50:15 -07007385// setVolume_l() must be called with PlaybackThread::mLock held
7386bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007387{
7388 uint32_t newLeft = *left;
7389 uint32_t newRight = *right;
7390 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007391 int ctrlIdx = -1;
7392 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007393
Eric Laurent76c40f72010-07-15 12:50:15 -07007394 // first update volume controller
7395 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007396 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007397 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7398 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007399 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007400 break;
7401 }
7402 }
7403
7404 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007405 if (hasControl) {
7406 *left = mNewLeftVolume;
7407 *right = mNewRightVolume;
7408 }
7409 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007410 }
7411
7412 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007413 mLeftVolume = newLeft;
7414 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007415
7416 // second get volume update from volume controller
7417 if (ctrlIdx >= 0) {
7418 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007419 mNewLeftVolume = newLeft;
7420 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007421 }
7422 // then indicate volume to all other effects in chain.
7423 // Pass altered volume to effects before volume controller
7424 // and requested volume to effects after controller
7425 uint32_t lVol = newLeft;
7426 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007427
Eric Laurent65b65452010-06-01 23:49:17 -07007428 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007429 if ((int)i == ctrlIdx) continue;
7430 // this also works for ctrlIdx == -1 when there is no volume controller
7431 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007432 lVol = *left;
7433 rVol = *right;
7434 }
7435 mEffects[i]->setVolume(&lVol, &rVol, false);
7436 }
7437 *left = newLeft;
7438 *right = newRight;
7439
7440 return hasControl;
7441}
7442
Eric Laurent65b65452010-06-01 23:49:17 -07007443status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7444{
7445 const size_t SIZE = 256;
7446 char buffer[SIZE];
7447 String8 result;
7448
7449 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7450 result.append(buffer);
7451
7452 bool locked = tryLock(mLock);
7453 // failed to lock - AudioFlinger is probably deadlocked
7454 if (!locked) {
7455 result.append("\tCould not lock mutex:\n");
7456 }
7457
Eric Laurent76c40f72010-07-15 12:50:15 -07007458 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7459 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007460 mEffects.size(),
7461 (uint32_t)mInBuffer,
7462 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007463 mActiveTrackCnt);
7464 result.append(buffer);
7465 write(fd, result.string(), result.size());
7466
7467 for (size_t i = 0; i < mEffects.size(); ++i) {
7468 sp<EffectModule> effect = mEffects[i];
7469 if (effect != 0) {
7470 effect->dump(fd, args);
7471 }
7472 }
7473
7474 if (locked) {
7475 mLock.unlock();
7476 }
7477
7478 return NO_ERROR;
7479}
7480
Eric Laurentf82fccd2011-07-27 19:49:51 -07007481// must be called with ThreadBase::mLock held
7482void AudioFlinger::EffectChain::setEffectSuspended_l(
7483 const effect_uuid_t *type, bool suspend)
7484{
7485 sp<SuspendedEffectDesc> desc;
7486 // use effect type UUID timelow as key as there is no real risk of identical
7487 // timeLow fields among effect type UUIDs.
7488 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7489 if (suspend) {
7490 if (index >= 0) {
7491 desc = mSuspendedEffects.valueAt(index);
7492 } else {
7493 desc = new SuspendedEffectDesc();
7494 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7495 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007496 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007497 }
7498 if (desc->mRefCount++ == 0) {
7499 sp<EffectModule> effect = getEffectIfEnabled(type);
7500 if (effect != 0) {
7501 desc->mEffect = effect;
7502 effect->setSuspended(true);
7503 effect->setEnabled(false);
7504 }
7505 }
7506 } else {
7507 if (index < 0) {
7508 return;
7509 }
7510 desc = mSuspendedEffects.valueAt(index);
7511 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007512 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007513 desc->mRefCount = 1;
7514 }
7515 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007516 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007517 if (desc->mEffect != 0) {
7518 sp<EffectModule> effect = desc->mEffect.promote();
7519 if (effect != 0) {
7520 effect->setSuspended(false);
7521 sp<EffectHandle> handle = effect->controlHandle();
7522 if (handle != 0) {
7523 effect->setEnabled(handle->enabled());
7524 }
7525 }
7526 desc->mEffect.clear();
7527 }
7528 mSuspendedEffects.removeItemsAt(index);
7529 }
7530 }
7531}
7532
7533// must be called with ThreadBase::mLock held
7534void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7535{
7536 sp<SuspendedEffectDesc> desc;
7537
7538 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7539 if (suspend) {
7540 if (index >= 0) {
7541 desc = mSuspendedEffects.valueAt(index);
7542 } else {
7543 desc = new SuspendedEffectDesc();
7544 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007545 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007546 }
7547 if (desc->mRefCount++ == 0) {
7548 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7549 for (size_t i = 0; i < effects.size(); i++) {
7550 setEffectSuspended_l(&effects[i]->desc().type, true);
7551 }
7552 }
7553 } else {
7554 if (index < 0) {
7555 return;
7556 }
7557 desc = mSuspendedEffects.valueAt(index);
7558 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007559 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007560 desc->mRefCount = 1;
7561 }
7562 if (--desc->mRefCount == 0) {
7563 Vector<const effect_uuid_t *> types;
7564 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7565 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7566 continue;
7567 }
7568 types.add(&mSuspendedEffects.valueAt(i)->mType);
7569 }
7570 for (size_t i = 0; i < types.size(); i++) {
7571 setEffectSuspended_l(types[i], false);
7572 }
Steve Block71f2cf12011-10-20 11:56:00 +01007573 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007574 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7575 }
7576 }
7577}
7578
Eric Laurent5e7acae2011-09-23 08:40:41 -07007579
7580// The volume effect is used for automated tests only
7581#ifndef OPENSL_ES_H_
7582static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7583 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7584const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7585#endif //OPENSL_ES_H_
7586
Eric Laurent6752ec82011-08-10 10:37:50 -07007587bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7588{
7589 // auxiliary effects and visualizer are never suspended on output mix
7590 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7591 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007592 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7593 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007594 return false;
7595 }
7596 return true;
7597}
7598
Eric Laurentf82fccd2011-07-27 19:49:51 -07007599Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7600{
7601 Vector< sp<EffectModule> > effects;
7602 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007603 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007604 continue;
7605 }
7606 effects.add(mEffects[i]);
7607 }
7608 return effects;
7609}
7610
7611sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7612 const effect_uuid_t *type)
7613{
7614 sp<EffectModule> effect;
7615 effect = getEffectFromType_l(type);
7616 if (effect != 0 && !effect->isEnabled()) {
7617 effect.clear();
7618 }
7619 return effect;
7620}
7621
7622void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7623 bool enabled)
7624{
7625 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7626 if (enabled) {
7627 if (index < 0) {
7628 // if the effect is not suspend check if all effects are suspended
7629 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7630 if (index < 0) {
7631 return;
7632 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007633 if (!isEffectEligibleForSuspend(effect->desc())) {
7634 return;
7635 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007636 setEffectSuspended_l(&effect->desc().type, enabled);
7637 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007638 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007639 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07007640 return;
7641 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007642 }
Steve Block71f2cf12011-10-20 11:56:00 +01007643 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007644 effect->desc().type.timeLow);
7645 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7646 // if effect is requested to suspended but was not yet enabled, supend it now.
7647 if (desc->mEffect == 0) {
7648 desc->mEffect = effect;
7649 effect->setEnabled(false);
7650 effect->setSuspended(true);
7651 }
7652 } else {
7653 if (index < 0) {
7654 return;
7655 }
Steve Block71f2cf12011-10-20 11:56:00 +01007656 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007657 effect->desc().type.timeLow);
7658 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7659 desc->mEffect.clear();
7660 effect->setSuspended(false);
7661 }
7662}
7663
Eric Laurent65b65452010-06-01 23:49:17 -07007664#undef LOG_TAG
7665#define LOG_TAG "AudioFlinger"
7666
Eric Laurenta553c252009-07-17 12:17:14 -07007667// ----------------------------------------------------------------------------
7668
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007669status_t AudioFlinger::onTransact(
7670 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7671{
7672 return BnAudioFlinger::onTransact(code, data, reply, flags);
7673}
7674
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007675}; // namespace android