blob: 72525cde148aacc7ac69c8605fdbab51c4f40a13 [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
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040#include <media/AudioTrack.h>
41#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080042#include <media/IMediaPlayerService.h>
Glenn Kasten26f260a2012-01-03 15:28:29 -080043#include <media/IMediaDeathNotifier.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044
45#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070046#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070047
Dima Zavin34bb4192011-05-11 14:15:23 -070048#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070049#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050
51#include "AudioMixer.h"
52#include "AudioFlinger.h"
53
Eric Laurent53334cd2010-06-23 17:38:20 -070054#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070055#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070056#include <audio_effects/effect_ns.h>
57#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070058
Glenn Kasten490909d2011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Glenn Kastenda494f92011-07-08 15:26:12 -070061#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070062#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070063// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
Eric Laurent8ed6ed02010-07-13 04:45:46 -070067
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070068namespace android {
69
Glenn Kasten62de3db2011-12-12 09:04:45 -080070static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
71static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070072
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080073//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070075static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070076
77// retry counts for buffer fill timeout
78// 50 * ~20msecs = 1 second
79static const int8_t kMaxTrackRetries = 50;
80static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080081// allow less retry attempts on direct output thread.
82// direct outputs can be a scarce resource in audio hardware and should
83// be released as quickly as possible.
84static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070085
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080087static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070088
Glenn Kastencbfe2e12011-12-13 11:04:14 -080089// don't warn about blocked writes or record buffer overflows more often than this
90static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070091
Eric Laurent464d5b32011-06-17 21:29:58 -070092// RecordThread loop sleep time upon application overrun or audio HAL read error
93static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Glenn Kastencbfe2e12011-12-13 11:04:14 -080095// maximum time to wait for setParameters to complete
96static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070097
Eric Laurentf1f5fc82011-11-22 18:50:29 -080098// minimum sleep time for the mixer thread loop when tracks are active but in underrun
99static const uint32_t kMinThreadSleepTimeUs = 5000;
100// maximum divider applied to the active sleep time in the mixer thread loop
101static const uint32_t kMaxThreadSleepTimeShift = 2;
102
103
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700104// ----------------------------------------------------------------------------
105
106static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700107 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
108 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block3762c312012-01-06 19:20:56 +0000109 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700111}
112
113static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700114 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
115 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block3762c312012-01-06 19:20:56 +0000116 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700117 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700118}
119
Gloria Wang9b3f1522011-02-24 14:51:45 -0800120// To collect the amplifier usage
121static void addBatteryData(uint32_t params) {
Glenn Kasten26f260a2012-01-03 15:28:29 -0800122 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
123 if (service == NULL) {
124 // it already logged
Gloria Wang9b3f1522011-02-24 14:51:45 -0800125 return;
126 }
127
128 service->addBatteryData(params);
129}
130
Dima Zavin31f188892011-04-18 16:57:27 -0700131static int load_audio_interface(const char *if_name, const hw_module_t **mod,
132 audio_hw_device_t **dev)
133{
134 int rc;
135
136 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
137 if (rc)
138 goto out;
139
140 rc = audio_hw_device_open(*mod, dev);
Steve Block3762c312012-01-06 19:20:56 +0000141 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin31f188892011-04-18 16:57:27 -0700142 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
143 if (rc)
144 goto out;
145
146 return 0;
147
148out:
149 *mod = NULL;
150 *dev = NULL;
151 return rc;
152}
153
Glenn Kasten62de3db2011-12-12 09:04:45 -0800154static const char * const audio_interfaces[] = {
Dima Zavin31f188892011-04-18 16:57:27 -0700155 "primary",
156 "a2dp",
157 "usb",
158};
159#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
160
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700161// ----------------------------------------------------------------------------
162
163AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 : BnAudioFlinger(),
Glenn Kastenc434c902011-12-13 11:53:26 -0800165 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700166 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700168}
169
170void AudioFlinger::onFirstRef()
171{
Dima Zavin31f188892011-04-18 16:57:27 -0700172 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700173
Eric Laurent01635942011-01-18 18:39:02 -0800174 Mutex::Autolock _l(mLock);
175
Dima Zavin31f188892011-04-18 16:57:27 -0700176 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700177 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700178
Dima Zavin31f188892011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700182
Dima Zavin31f188892011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Block6215d3f2012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin31f188892011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Block6215d3f2012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700195 }
196 }
Eric Laurenta553c252009-07-17 12:17:14 -0700197
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700199
Dima Zavin31f188892011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block3762c312012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin31f188892011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700220 }
221}
222
Dima Zavin2986f5b2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin31f188892011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Eric Laurent7954c462009-08-28 10:39:03 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin31f188892011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700247 }
Dima Zavin31f188892011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800249}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800250
Dima Zavin31f188892011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700261
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
270 wp<Client> wClient = mClients.valueAt(i);
271 if (wClient != 0) {
272 sp<Client> client = wClient.promote();
273 if (client != 0) {
274 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
275 result.append(buffer);
276 }
277 }
278 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700279
280 result.append("Global session refs:\n");
281 result.append(" session pid cnt\n");
282 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
283 AudioSessionRef *r = mAudioSessionRefs[i];
284 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
285 result.append(buffer);
286 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700287 write(fd, result.string(), result.size());
288 return NO_ERROR;
289}
290
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700291
292status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700297 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700298
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700299 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700300 result.append(buffer);
301 write(fd, result.string(), result.size());
302 return NO_ERROR;
303}
304
305status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
310 snprintf(buffer, SIZE, "Permission Denial: "
311 "can't dump AudioFlinger from pid=%d, uid=%d\n",
312 IPCThreadState::self()->getCallingPid(),
313 IPCThreadState::self()->getCallingUid());
314 result.append(buffer);
315 write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
The Android Open Source Project10592532009-03-18 17:39:46 -0700319static bool tryLock(Mutex& mutex)
320{
321 bool locked = false;
322 for (int i = 0; i < kDumpLockRetries; ++i) {
323 if (mutex.tryLock() == NO_ERROR) {
324 locked = true;
325 break;
326 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800327 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700328 }
329 return locked;
330}
331
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
333{
334 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
335 dumpPermissionDenial(fd, args);
336 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700337 // get state of hardware lock
338 bool hardwareLocked = tryLock(mHardwareLock);
339 if (!hardwareLocked) {
340 String8 result(kHardwareLockedString);
341 write(fd, result.string(), result.size());
342 } else {
343 mHardwareLock.unlock();
344 }
345
346 bool locked = tryLock(mLock);
347
348 // failed to lock - AudioFlinger is probably deadlocked
349 if (!locked) {
350 String8 result(kDeadlockedString);
351 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700352 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353
354 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700355 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
Eric Laurenta553c252009-07-17 12:17:14 -0700357 // dump playback threads
358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700359 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700360 }
361
362 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700363 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700364 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366
Dima Zavin31f188892011-04-18 16:57:27 -0700367 // dump all hardware devs
368 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
369 audio_hw_device_t *dev = mAudioHwDevs[i];
370 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700372 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373 }
374 return NO_ERROR;
375}
376
Eric Laurenta553c252009-07-17 12:17:14 -0700377
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379
380
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700381sp<IAudioTrack> AudioFlinger::createTrack(
382 pid_t pid,
383 int streamType,
384 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700385 uint32_t format,
386 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800387 int frameCount,
388 uint32_t flags,
389 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700390 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700391 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800392 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700393{
Eric Laurenta553c252009-07-17 12:17:14 -0700394 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700396 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800397 wp<Client> wclient;
398 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700399 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700401 if (streamType >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000402 ALOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800403 lStatus = BAD_VALUE;
404 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700405 }
406
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800407 {
408 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700409 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700410 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700411 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +0000412 ALOGE("unknown output thread");
Eric Laurenta553c252009-07-17 12:17:14 -0700413 lStatus = BAD_VALUE;
414 goto Exit;
415 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800416
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800417 wclient = mClients.valueFor(pid);
418
419 if (wclient != NULL) {
420 client = wclient.promote();
421 } else {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
Eric Laurent65b65452010-06-01 23:49:17 -0700425
Steve Block71f2cf12011-10-20 11:56:00 +0100426 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700427 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700428 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700429 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
430 if (mPlaybackThreads.keyAt(i) != output) {
431 // prevent same audio session on different output threads
432 uint32_t sessions = t->hasAudioSession(*sessionId);
433 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block3762c312012-01-06 19:20:56 +0000434 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700435 lStatus = BAD_VALUE;
436 goto Exit;
437 }
438 // check if an effect with same session ID is waiting for a track to be created
439 if (sessions & PlaybackThread::EFFECT_SESSION) {
440 effectThread = t.get();
441 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700442 }
443 }
Eric Laurent65b65452010-06-01 23:49:17 -0700444 lSessionId = *sessionId;
445 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700446 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700447 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700448 if (sessionId != NULL) {
449 *sessionId = lSessionId;
450 }
451 }
Steve Block71f2cf12011-10-20 11:56:00 +0100452 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700453
Eric Laurenta553c252009-07-17 12:17:14 -0700454 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700455 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700456
457 // move effect chain to this output thread if an effect on same session was waiting
458 // for a track to be created
459 if (lStatus == NO_ERROR && effectThread != NULL) {
460 Mutex::Autolock _dl(thread->mLock);
461 Mutex::Autolock _sl(effectThread->mLock);
462 moveEffectChain_l(lSessionId, effectThread, thread, true);
463 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700464 }
465 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800466 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700467 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700468 // remove local strong reference to Client before deleting the Track so that the Client
469 // destructor is called by the TrackBase destructor with mLock held
470 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700471 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800472 }
473
474Exit:
475 if(status) {
476 *status = lStatus;
477 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478 return trackHandle;
479}
480
Eric Laurentddb78e72009-07-28 08:44:33 -0700481uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482{
Eric Laurenta553c252009-07-17 12:17:14 -0700483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000486 ALOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700487 return 0;
488 }
489 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490}
491
Eric Laurentddb78e72009-07-28 08:44:33 -0700492int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700493{
Eric Laurenta553c252009-07-17 12:17:14 -0700494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000497 ALOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700498 return 0;
499 }
500 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501}
502
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700503uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700504{
Eric Laurenta553c252009-07-17 12:17:14 -0700505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000508 ALOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700509 return 0;
510 }
511 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512}
513
Eric Laurentddb78e72009-07-28 08:44:33 -0700514size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700515{
Eric Laurenta553c252009-07-17 12:17:14 -0700516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000519 ALOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700520 return 0;
521 }
522 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700523}
524
Eric Laurentddb78e72009-07-28 08:44:33 -0700525uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800526{
Eric Laurenta553c252009-07-17 12:17:14 -0700527 Mutex::Autolock _l(mLock);
528 PlaybackThread *thread = checkPlaybackThread_l(output);
529 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000530 ALOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700531 return 0;
532 }
533 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800534}
535
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536status_t AudioFlinger::setMasterVolume(float value)
537{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700538 status_t ret = initCheck();
539 if (ret != NO_ERROR) {
540 return ret;
541 }
542
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700543 // check calling permissions
544 if (!settingsAllowed()) {
545 return PERMISSION_DENIED;
546 }
547
548 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800549 { // scope for the lock
550 AutoMutex lock(mHardwareLock);
551 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700552 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800553 value = 1.0f;
554 }
555 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700556 }
Eric Laurenta553c252009-07-17 12:17:14 -0700557
Eric Laurent01635942011-01-18 18:39:02 -0800558 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700559 mMasterVolume = value;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700561 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700562
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563 return NO_ERROR;
564}
565
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700566status_t AudioFlinger::setMode(int mode)
567{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700572
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700577 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Steve Block8564c8d2012-01-05 23:22:43 +0000578 ALOGW("Illegal value: setMode(%d)", mode);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 return BAD_VALUE;
580 }
581
Eric Laurent53334cd2010-06-23 17:38:20 -0700582 { // scope for the lock
583 AutoMutex lock(mHardwareLock);
584 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700585 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800587 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700588
589 if (NO_ERROR == ret) {
590 Mutex::Autolock _l(mLock);
591 mMode = mode;
592 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
593 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700594 }
595
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700596 return ret;
597}
598
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700599status_t AudioFlinger::setMicMute(bool state)
600{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
611 AutoMutex lock(mHardwareLock);
612 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700613 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700614 mHardwareStatus = AUDIO_HW_IDLE;
615 return ret;
616}
617
618bool AudioFlinger::getMicMute() const
619{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return false;
623 }
624
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700625 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700626 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700627 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
629 return state;
630}
631
632status_t AudioFlinger::setMasterMute(bool muted)
633{
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
Eric Laurenta553c252009-07-17 12:17:14 -0700638
Eric Laurent01635942011-01-18 18:39:02 -0800639 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700640 mMasterMute = muted;
641 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700642 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700643
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700644 return NO_ERROR;
645}
646
647float AudioFlinger::masterVolume() const
648{
Eric Laurenta553c252009-07-17 12:17:14 -0700649 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700650}
651
652bool AudioFlinger::masterMute() const
653{
Eric Laurenta553c252009-07-17 12:17:14 -0700654 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700655}
656
Eric Laurentddb78e72009-07-28 08:44:33 -0700657status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700658{
659 // check calling permissions
660 if (!settingsAllowed()) {
661 return PERMISSION_DENIED;
662 }
663
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700664 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000665 ALOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700666 return BAD_VALUE;
667 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800668
Eric Laurenta553c252009-07-17 12:17:14 -0700669 AutoMutex lock(mLock);
670 PlaybackThread *thread = NULL;
671 if (output) {
672 thread = checkPlaybackThread_l(output);
673 if (thread == NULL) {
674 return BAD_VALUE;
675 }
676 }
677
Eric Laurenta553c252009-07-17 12:17:14 -0700678 mStreamTypes[stream].volume = value;
679
680 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700681 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700682 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700683 }
Eric Laurenta553c252009-07-17 12:17:14 -0700684 } else {
685 thread->setStreamVolume(stream, value);
686 }
Eric Laurentef028272009-04-21 07:56:33 -0700687
Eric Laurent415f3e22009-10-21 08:14:22 -0700688 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700689}
690
691status_t AudioFlinger::setStreamMute(int stream, bool muted)
692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700698 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
699 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block3762c312012-01-06 19:20:56 +0000700 ALOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700701 return BAD_VALUE;
702 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700703
Eric Laurent01635942011-01-18 18:39:02 -0800704 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700705 mStreamTypes[stream].mute = muted;
706 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700707 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700709 return NO_ERROR;
710}
711
Eric Laurentddb78e72009-07-28 08:44:33 -0700712float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700713{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700714 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700715 return 0.0f;
716 }
Eric Laurenta553c252009-07-17 12:17:14 -0700717
718 AutoMutex lock(mLock);
719 float volume;
720 if (output) {
721 PlaybackThread *thread = checkPlaybackThread_l(output);
722 if (thread == NULL) {
723 return 0.0f;
724 }
725 volume = thread->streamVolume(stream);
726 } else {
727 volume = mStreamTypes[stream].volume;
728 }
729
Eric Laurentef028272009-04-21 07:56:33 -0700730 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700731}
732
733bool AudioFlinger::streamMute(int stream) const
734{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700735 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700736 return true;
737 }
Eric Laurenta553c252009-07-17 12:17:14 -0700738
739 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700740}
741
Eric Laurentddb78e72009-07-28 08:44:33 -0700742status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700743{
Eric Laurenta553c252009-07-17 12:17:14 -0700744 status_t result;
745
Steve Block71f2cf12011-10-20 11:56:00 +0100746 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700747 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748 // check calling permissions
749 if (!settingsAllowed()) {
750 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800751 }
Eric Laurenta553c252009-07-17 12:17:14 -0700752
753 // ioHandle == 0 means the parameters are global to the audio hardware interface
754 if (ioHandle == 0) {
755 AutoMutex lock(mHardwareLock);
756 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700757 status_t final_result = NO_ERROR;
758 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
759 audio_hw_device_t *dev = mAudioHwDevs[i];
760 result = dev->set_parameters(dev, keyValuePairs.string());
761 final_result = result ?: final_result;
762 }
Eric Laurenta553c252009-07-17 12:17:14 -0700763 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700764 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
765 AudioParameter param = AudioParameter(keyValuePairs);
766 String8 value;
767 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
768 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700769 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700771 for (size_t i = 0; i < mRecordThreads.size(); i++) {
772 sp<RecordThread> thread = mRecordThreads.valueAt(i);
773 RecordThread::RecordTrack *track = thread->track();
774 if (track != NULL) {
775 audio_devices_t device = (audio_devices_t)(
776 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700777 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700778 thread->setEffectSuspended(FX_IID_AEC,
779 suspend,
780 track->sessionId());
781 thread->setEffectSuspended(FX_IID_NS,
782 suspend,
783 track->sessionId());
784 }
785 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700786 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700787 }
788 }
Dima Zavin31f188892011-04-18 16:57:27 -0700789 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700790 }
791
Eric Laurentb7d94602009-09-29 11:12:57 -0700792 // hold a strong ref on thread in case closeOutput() or closeInput() is called
793 // and the thread is exited once the lock is released
794 sp<ThreadBase> thread;
795 {
796 Mutex::Autolock _l(mLock);
797 thread = checkPlaybackThread_l(ioHandle);
798 if (thread == NULL) {
799 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700800 } else if (thread.get() == primaryPlaybackThread_l()) {
801 // indicate output device change to all input threads for pre processing
802 AudioParameter param = AudioParameter(keyValuePairs);
803 int value;
804 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
805 for (size_t i = 0; i < mRecordThreads.size(); i++) {
806 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
807 }
808 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700809 }
Eric Laurenta553c252009-07-17 12:17:14 -0700810 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700811 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800812 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800813 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700814 }
Eric Laurenta553c252009-07-17 12:17:14 -0700815 return BAD_VALUE;
816}
817
Eric Laurentddb78e72009-07-28 08:44:33 -0700818String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700819{
Steve Block71f2cf12011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin31f188892011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700832 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700833 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700834
835 Mutex::Autolock _l(mLock);
836
Eric Laurenta553c252009-07-17 12:17:14 -0700837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700846}
847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
849{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin31f188892011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856}
857
Eric Laurent47d0a922010-02-26 02:47:27 -0800858unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
Eric Laurent415f3e22009-10-21 08:14:22 -0700873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Eric Laurent415f3e22009-10-21 08:14:22 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
Eric Laurent0986e792010-01-19 17:37:09 -0800893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
894{
895 status_t status;
896
897 Mutex::Autolock _l(mLock);
898
899 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
900 if (playbackThread != NULL) {
901 return playbackThread->getRenderPosition(halFrames, dspFrames);
902 }
903
904 return BAD_VALUE;
905}
906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
908{
Eric Laurenta553c252009-07-17 12:17:14 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 Mutex::Autolock _l(mLock);
911
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700912 int pid = IPCThreadState::self()->getCallingPid();
913 if (mNotificationClients.indexOfKey(pid) < 0) {
914 sp<NotificationClient> notificationClient = new NotificationClient(this,
915 client,
916 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100917 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700918
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700919 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700920
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700921 sp<IBinder> binder = client->asBinder();
922 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700924 // the config change is always sent from playback or record threads to avoid deadlock
925 // with AudioSystem::gLock
926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
927 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
928 }
Eric Laurenta553c252009-07-17 12:17:14 -0700929
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
933 }
934}
935
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700936void AudioFlinger::removeNotificationClient(pid_t pid)
937{
938 Mutex::Autolock _l(mLock);
939
940 int index = mNotificationClients.indexOfKey(pid);
941 if (index >= 0) {
942 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100943 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700944 mNotificationClients.removeItem(pid);
945 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700946
Steve Block71f2cf12011-10-20 11:56:00 +0100947 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700948 int num = mAudioSessionRefs.size();
949 bool removed = false;
950 for (int i = 0; i< num; i++) {
951 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100952 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700953 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100954 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700955 mAudioSessionRefs.removeAt(i);
956 delete ref;
957 removed = true;
958 i--;
959 num--;
960 }
961 }
962 if (removed) {
963 purgeStaleEffects_l();
964 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700965}
966
Eric Laurent296a0ec2009-09-15 07:10:12 -0700967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700968void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
969{
Eric Laurent49f02be2009-11-19 09:00:56 -0800970 size_t size = mNotificationClients.size();
971 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700972 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700973 }
974}
975
Eric Laurentb9481d82009-09-17 05:12:56 -0700976// removeClient_l() must be called with AudioFlinger::mLock held
977void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700978{
Steve Block71f2cf12011-10-20 11:56:00 +0100979 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 -0700980 mClients.removeItem(pid);
981}
982
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700983
Eric Laurenta553c252009-07-17 12:17:14 -0700984// ----------------------------------------------------------------------------
985
Eric Laurent464d5b32011-06-17 21:29:58 -0700986AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700987 : Thread(false),
988 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700989 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
990 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700991{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700992 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993}
994
Eric Laurenta553c252009-07-17 12:17:14 -0700995AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700997 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700998 // do not lock the mutex in destructor
999 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001000 if (mPowerManager != 0) {
1001 sp<IBinder> binder = mPowerManager->asBinder();
1002 binder->unlinkToDeath(mDeathRecipient);
1003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004}
1005
Eric Laurenta553c252009-07-17 12:17:14 -07001006void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001007{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001008 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001009 // destroyed in the middle of requestExitAndWait()
1010 sp <ThreadBase> strongMe = this;
1011
Steve Block71f2cf12011-10-20 11:56:00 +01001012 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001013 {
1014 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001015 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001016 requestExit();
1017 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001018 }
Eric Laurenta553c252009-07-17 12:17:14 -07001019 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001020}
Eric Laurenta553c252009-07-17 12:17:14 -07001021
1022uint32_t AudioFlinger::ThreadBase::sampleRate() const
1023{
1024 return mSampleRate;
1025}
1026
1027int AudioFlinger::ThreadBase::channelCount() const
1028{
Eric Laurentb0a01472010-05-14 05:45:46 -07001029 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001030}
1031
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001032uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001033{
1034 return mFormat;
1035}
1036
1037size_t AudioFlinger::ThreadBase::frameCount() const
1038{
1039 return mFrameCount;
1040}
1041
1042status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1043{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001044 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001045
Steve Block71f2cf12011-10-20 11:56:00 +01001046 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001047 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001048
Eric Laurent8fce46a2009-08-04 09:45:33 -07001049 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001050 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001051 // wait condition with timeout in case the thread loop has exited
1052 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001053 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001054 status = mParamStatus;
1055 mWaitWorkCV.signal();
1056 } else {
1057 status = TIMED_OUT;
1058 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001059 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001060}
1061
1062void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1063{
1064 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001065 sendConfigEvent_l(event, param);
1066}
1067
1068// sendConfigEvent_l() must be called with ThreadBase::mLock held
1069void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1070{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001071 ConfigEvent configEvent;
1072 configEvent.mEvent = event;
1073 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001074 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001075 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001076 mWaitWorkCV.signal();
1077}
1078
1079void AudioFlinger::ThreadBase::processConfigEvents()
1080{
1081 mLock.lock();
1082 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001083 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001084 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001085 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001086 // release mLock before locking AudioFlinger mLock: lock order is always
1087 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001088 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001089 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001090 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001091 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001092 mLock.lock();
1093 }
1094 mLock.unlock();
1095}
1096
Eric Laurent3fdb1262009-11-07 00:01:32 -08001097status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1098{
1099 const size_t SIZE = 256;
1100 char buffer[SIZE];
1101 String8 result;
1102
1103 bool locked = tryLock(mLock);
1104 if (!locked) {
1105 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1106 write(fd, buffer, strlen(buffer));
1107 }
1108
1109 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1116 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001117 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1118 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001119 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1120 result.append(buffer);
1121 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1122 result.append(buffer);
1123
1124 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1125 result.append(buffer);
1126 result.append(" Index Command");
1127 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1128 snprintf(buffer, SIZE, "\n %02d ", i);
1129 result.append(buffer);
1130 result.append(mNewParameters[i]);
1131 }
1132
1133 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1134 result.append(buffer);
1135 snprintf(buffer, SIZE, " Index event param\n");
1136 result.append(buffer);
1137 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001138 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001139 result.append(buffer);
1140 }
1141 result.append("\n");
1142
1143 write(fd, result.string(), result.size());
1144
1145 if (locked) {
1146 mLock.unlock();
1147 }
1148 return NO_ERROR;
1149}
1150
Eric Laurent1345d332011-07-24 17:49:51 -07001151status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1152{
1153 const size_t SIZE = 256;
1154 char buffer[SIZE];
1155 String8 result;
1156
1157 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1158 write(fd, buffer, strlen(buffer));
1159
1160 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1161 sp<EffectChain> chain = mEffectChains[i];
1162 if (chain != 0) {
1163 chain->dump(fd, args);
1164 }
1165 }
1166 return NO_ERROR;
1167}
1168
Eric Laurent6dbdc402011-07-22 09:04:31 -07001169void AudioFlinger::ThreadBase::acquireWakeLock()
1170{
1171 Mutex::Autolock _l(mLock);
1172 acquireWakeLock_l();
1173}
1174
1175void AudioFlinger::ThreadBase::acquireWakeLock_l()
1176{
1177 if (mPowerManager == 0) {
1178 // use checkService() to avoid blocking if power service is not up yet
1179 sp<IBinder> binder =
1180 defaultServiceManager()->checkService(String16("power"));
1181 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001182 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001183 } else {
1184 mPowerManager = interface_cast<IPowerManager>(binder);
1185 binder->linkToDeath(mDeathRecipient);
1186 }
1187 }
1188 if (mPowerManager != 0) {
1189 sp<IBinder> binder = new BBinder();
1190 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1191 binder,
1192 String16(mName));
1193 if (status == NO_ERROR) {
1194 mWakeLockToken = binder;
1195 }
Steve Block71f2cf12011-10-20 11:56:00 +01001196 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001197 }
1198}
1199
1200void AudioFlinger::ThreadBase::releaseWakeLock()
1201{
1202 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001203 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001204}
1205
1206void AudioFlinger::ThreadBase::releaseWakeLock_l()
1207{
1208 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001209 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001210 if (mPowerManager != 0) {
1211 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1212 }
1213 mWakeLockToken.clear();
1214 }
1215}
1216
1217void AudioFlinger::ThreadBase::clearPowerManager()
1218{
1219 Mutex::Autolock _l(mLock);
1220 releaseWakeLock_l();
1221 mPowerManager.clear();
1222}
1223
1224void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1225{
1226 sp<ThreadBase> thread = mThread.promote();
1227 if (thread != 0) {
1228 thread->clearPowerManager();
1229 }
Steve Block8564c8d2012-01-05 23:22:43 +00001230 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001231}
Eric Laurent1345d332011-07-24 17:49:51 -07001232
Eric Laurentf82fccd2011-07-27 19:49:51 -07001233void AudioFlinger::ThreadBase::setEffectSuspended(
1234 const effect_uuid_t *type, bool suspend, int sessionId)
1235{
1236 Mutex::Autolock _l(mLock);
1237 setEffectSuspended_l(type, suspend, sessionId);
1238}
1239
1240void AudioFlinger::ThreadBase::setEffectSuspended_l(
1241 const effect_uuid_t *type, bool suspend, int sessionId)
1242{
1243 sp<EffectChain> chain;
1244 chain = getEffectChain_l(sessionId);
1245 if (chain != 0) {
1246 if (type != NULL) {
1247 chain->setEffectSuspended_l(type, suspend);
1248 } else {
1249 chain->setEffectSuspendedAll_l(suspend);
1250 }
1251 }
1252
1253 updateSuspendedSessions_l(type, suspend, sessionId);
1254}
1255
1256void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1257{
1258 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1259 if (index < 0) {
1260 return;
1261 }
1262
1263 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1264 mSuspendedSessions.editValueAt(index);
1265
1266 for (size_t i = 0; i < sessionEffects.size(); i++) {
1267 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1268 for (int j = 0; j < desc->mRefCount; j++) {
1269 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1270 chain->setEffectSuspendedAll_l(true);
1271 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001272 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001273 desc->mType.timeLow);
1274 chain->setEffectSuspended_l(&desc->mType, true);
1275 }
1276 }
1277 }
1278}
1279
Eric Laurentf82fccd2011-07-27 19:49:51 -07001280void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1281 bool suspend,
1282 int sessionId)
1283{
1284 int index = mSuspendedSessions.indexOfKey(sessionId);
1285
1286 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1287
1288 if (suspend) {
1289 if (index >= 0) {
1290 sessionEffects = mSuspendedSessions.editValueAt(index);
1291 } else {
1292 mSuspendedSessions.add(sessionId, sessionEffects);
1293 }
1294 } else {
1295 if (index < 0) {
1296 return;
1297 }
1298 sessionEffects = mSuspendedSessions.editValueAt(index);
1299 }
1300
1301
1302 int key = EffectChain::kKeyForSuspendAll;
1303 if (type != NULL) {
1304 key = type->timeLow;
1305 }
1306 index = sessionEffects.indexOfKey(key);
1307
1308 sp <SuspendedSessionDesc> desc;
1309 if (suspend) {
1310 if (index >= 0) {
1311 desc = sessionEffects.valueAt(index);
1312 } else {
1313 desc = new SuspendedSessionDesc();
1314 if (type != NULL) {
1315 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1316 }
1317 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001319 }
1320 desc->mRefCount++;
1321 } else {
1322 if (index < 0) {
1323 return;
1324 }
1325 desc = sessionEffects.valueAt(index);
1326 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001328 sessionEffects.removeItemsAt(index);
1329 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001330 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001331 sessionId);
1332 mSuspendedSessions.removeItem(sessionId);
1333 }
1334 }
1335 }
1336 if (!sessionEffects.isEmpty()) {
1337 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1338 }
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1342 bool enabled,
1343 int sessionId)
1344{
1345 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001346 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1347}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001348
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001349void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1350 bool enabled,
1351 int sessionId)
1352{
Eric Laurent6752ec82011-08-10 10:37:50 -07001353 if (mType != RECORD) {
1354 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1355 // another session. This gives the priority to well behaved effect control panels
1356 // and applications not using global effects.
1357 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1358 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1359 }
1360 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001361
1362 sp<EffectChain> chain = getEffectChain_l(sessionId);
1363 if (chain != 0) {
1364 chain->checkSuspendOnEffectEnabled(effect, enabled);
1365 }
1366}
1367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368// ----------------------------------------------------------------------------
1369
Eric Laurent464d5b32011-06-17 21:29:58 -07001370AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1371 AudioStreamOut* output,
1372 int id,
1373 uint32_t device)
1374 : ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001375 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001378 snprintf(mName, kNameLength, "AudioOut_%d", id);
1379
Eric Laurenta553c252009-07-17 12:17:14 -07001380 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381
Eric Laurenta553c252009-07-17 12:17:14 -07001382 mMasterVolume = mAudioFlinger->masterVolume();
1383 mMasterMute = mAudioFlinger->masterMute();
1384
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001385 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001386 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1387 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001388 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390}
1391
Eric Laurenta553c252009-07-17 12:17:14 -07001392AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393{
1394 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395}
1396
Eric Laurenta553c252009-07-17 12:17:14 -07001397status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398{
1399 dumpInternals(fd, args);
1400 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001401 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 return NO_ERROR;
1403}
1404
Eric Laurenta553c252009-07-17 12:17:14 -07001405status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406{
1407 const size_t SIZE = 256;
1408 char buffer[SIZE];
1409 String8 result;
1410
Eric Laurenta553c252009-07-17 12:17:14 -07001411 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001413 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 -08001414 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001415 sp<Track> track = mTracks[i];
1416 if (track != 0) {
1417 track->dump(buffer, SIZE);
1418 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420 }
1421
Eric Laurenta553c252009-07-17 12:17:14 -07001422 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001424 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 -08001425 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001426 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 if (wTrack != 0) {
1428 sp<Track> track = wTrack.promote();
1429 if (track != 0) {
1430 track->dump(buffer, SIZE);
1431 result.append(buffer);
1432 }
1433 }
1434 }
1435 write(fd, result.string(), result.size());
1436 return NO_ERROR;
1437}
1438
Eric Laurenta553c252009-07-17 12:17:14 -07001439status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440{
1441 const size_t SIZE = 256;
1442 char buffer[SIZE];
1443 String8 result;
1444
Eric Laurent3fdb1262009-11-07 00:01:32 -08001445 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 result.append(buffer);
1447 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1454 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001455 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1456 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001457 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1458 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001460
1461 dumpBase(fd, args);
1462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 return NO_ERROR;
1464}
1465
1466// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001467status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468{
Eric Laurent828b9772011-08-07 16:32:26 -07001469 status_t status = initCheck();
1470 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001471 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001472 } else {
Steve Block3762c312012-01-06 19:20:56 +00001473 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
Eric Laurent828b9772011-08-07 16:32:26 -07001475 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476}
1477
Eric Laurenta553c252009-07-17 12:17:14 -07001478void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001480 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481}
1482
Eric Laurenta553c252009-07-17 12:17:14 -07001483// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1484sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 const sp<AudioFlinger::Client>& client,
1486 int streamType,
1487 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001488 uint32_t format,
1489 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 int frameCount,
1491 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001492 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 status_t *status)
1494{
1495 sp<Track> track;
1496 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001497
1498 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001499 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1500 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001501 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001502 "for output %p with format %d",
1503 sampleRate, format, channelMask, mOutput, mFormat);
1504 lStatus = BAD_VALUE;
1505 goto Exit;
1506 }
Eric Laurenta553c252009-07-17 12:17:14 -07001507 }
1508 } else {
1509 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1510 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001511 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001512 lStatus = BAD_VALUE;
1513 goto Exit;
1514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
Eric Laurent464d5b32011-06-17 21:29:58 -07001517 lStatus = initCheck();
1518 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001519 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001520 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
Eric Laurenta553c252009-07-17 12:17:14 -07001523 { // scope for mLock
1524 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001525
1526 // all tracks in same audio session must share the same routing strategy otherwise
1527 // conflicts will happen when tracks are moved from one output to another by audio policy
1528 // manager
1529 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001530 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001531 for (size_t i = 0; i < mTracks.size(); ++i) {
1532 sp<Track> t = mTracks[i];
1533 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001534 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1535 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001536 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001537 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001538 lStatus = BAD_VALUE;
1539 goto Exit;
1540 }
1541 }
1542 }
1543
Eric Laurenta553c252009-07-17 12:17:14 -07001544 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001545 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001546 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001547 lStatus = NO_MEMORY;
1548 goto Exit;
1549 }
1550 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001551
1552 sp<EffectChain> chain = getEffectChain_l(sessionId);
1553 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001554 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001555 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001556 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001557 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001558 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001559
1560 // invalidate track immediately if the stream type was moved to another thread since
1561 // createTrack() was called by the client process.
1562 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001563 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001564 this, streamType);
1565 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1566 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001567 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001568 lStatus = NO_ERROR;
1569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570Exit:
1571 if(status) {
1572 *status = lStatus;
1573 }
1574 return track;
1575}
1576
Eric Laurenta553c252009-07-17 12:17:14 -07001577uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578{
Eric Laurent828b9772011-08-07 16:32:26 -07001579 Mutex::Autolock _l(mLock);
1580 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001581 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001582 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 return 0;
1584 }
1585}
1586
Eric Laurenta553c252009-07-17 12:17:14 -07001587status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588{
1589 mMasterVolume = value;
1590 return NO_ERROR;
1591}
1592
Eric Laurenta553c252009-07-17 12:17:14 -07001593status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594{
1595 mMasterMute = muted;
1596 return NO_ERROR;
1597}
1598
Eric Laurenta553c252009-07-17 12:17:14 -07001599float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600{
1601 return mMasterVolume;
1602}
1603
Eric Laurenta553c252009-07-17 12:17:14 -07001604bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605{
1606 return mMasterMute;
1607}
1608
Eric Laurenta553c252009-07-17 12:17:14 -07001609status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610{
1611 mStreamTypes[stream].volume = value;
1612 return NO_ERROR;
1613}
1614
Eric Laurenta553c252009-07-17 12:17:14 -07001615status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616{
1617 mStreamTypes[stream].mute = muted;
1618 return NO_ERROR;
1619}
1620
Eric Laurenta553c252009-07-17 12:17:14 -07001621float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622{
1623 return mStreamTypes[stream].volume;
1624}
1625
Eric Laurenta553c252009-07-17 12:17:14 -07001626bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627{
1628 return mStreamTypes[stream].mute;
1629}
1630
Eric Laurenta553c252009-07-17 12:17:14 -07001631// addTrack_l() must be called with ThreadBase::mLock held
1632status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633{
1634 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001635
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001636 // set retry count for buffer fill
1637 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001638 if (mActiveTracks.indexOf(track) < 0) {
1639 // the track is newly added, make sure it fills up all its
1640 // buffers before playing. This is to ensure the client will
1641 // effectively get the latency it requested.
1642 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001643 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001644 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001645 if (track->mainBuffer() != mMixBuffer) {
1646 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1647 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001648 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001649 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001650 }
1651 }
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001654 }
Eric Laurenta553c252009-07-17 12:17:14 -07001655
Steve Block71f2cf12011-10-20 11:56:00 +01001656 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001657 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658
1659 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001660}
1661
Eric Laurenta553c252009-07-17 12:17:14 -07001662// destroyTrack_l() must be called with ThreadBase::mLock held
1663void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001664{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001665 track->mState = TrackBase::TERMINATED;
1666 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001667 removeTrack_l(track);
1668 }
1669}
1670
1671void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1672{
1673 mTracks.remove(track);
1674 deleteTrackName_l(track->name());
1675 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1676 if (chain != 0) {
1677 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001678 }
1679}
1680
Eric Laurenta553c252009-07-17 12:17:14 -07001681String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001682{
Eric Laurent828b9772011-08-07 16:32:26 -07001683 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001684 char *s;
1685
Eric Laurent828b9772011-08-07 16:32:26 -07001686 Mutex::Autolock _l(mLock);
1687 if (initCheck() != NO_ERROR) {
1688 return out_s8;
1689 }
1690
Dima Zavin31f188892011-04-18 16:57:27 -07001691 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001692 out_s8 = String8(s);
1693 free(s);
1694 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001695}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001696
Eric Laurent828b9772011-08-07 16:32:26 -07001697// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001698void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001699 AudioSystem::OutputDescriptor desc;
1700 void *param2 = 0;
1701
Steve Block71f2cf12011-10-20 11:56:00 +01001702 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001703
1704 switch (event) {
1705 case AudioSystem::OUTPUT_OPENED:
1706 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001707 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001708 desc.samplingRate = mSampleRate;
1709 desc.format = mFormat;
1710 desc.frameCount = mFrameCount;
1711 desc.latency = latency();
1712 param2 = &desc;
1713 break;
1714
1715 case AudioSystem::STREAM_CONFIG_CHANGED:
1716 param2 = &param;
1717 case AudioSystem::OUTPUT_CLOSED:
1718 default:
1719 break;
1720 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001721 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001722}
1723
1724void AudioFlinger::PlaybackThread::readOutputParameters()
1725{
Dima Zavin31f188892011-04-18 16:57:27 -07001726 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001727 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1728 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001729 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1730 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1731 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001732
Eric Laurenta553c252009-07-17 12:17:14 -07001733 // FIXME - Current mixer implementation only supports stereo output: Always
1734 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001735 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001736 mMixBuffer = new int16_t[mFrameCount * 2];
1737 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001738
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001739 // force reconfiguration of effect chains and engines to take new buffer size and audio
1740 // parameters into account
1741 // Note that mLock is not held when readOutputParameters() is called from the constructor
1742 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1743 // matter.
1744 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1745 Vector< sp<EffectChain> > effectChains = mEffectChains;
1746 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001747 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001748 }
Eric Laurenta553c252009-07-17 12:17:14 -07001749}
1750
Eric Laurent0986e792010-01-19 17:37:09 -08001751status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1752{
1753 if (halFrames == 0 || dspFrames == 0) {
1754 return BAD_VALUE;
1755 }
Eric Laurent828b9772011-08-07 16:32:26 -07001756 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001757 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001758 return INVALID_OPERATION;
1759 }
Dima Zavin31f188892011-04-18 16:57:27 -07001760 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001761
Dima Zavin31f188892011-04-18 16:57:27 -07001762 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001763}
1764
Eric Laurent493941b2010-07-28 01:32:47 -07001765uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001766{
1767 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001768 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001769 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001770 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001771 }
1772
1773 for (size_t i = 0; i < mTracks.size(); ++i) {
1774 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001775 if (sessionId == track->sessionId() &&
1776 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001777 result |= TRACK_SESSION;
1778 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001779 }
1780 }
1781
Eric Laurent493941b2010-07-28 01:32:47 -07001782 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001783}
1784
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001785uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1786{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001787 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001788 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001789 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1790 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001791 }
1792 for (size_t i = 0; i < mTracks.size(); i++) {
1793 sp<Track> track = mTracks[i];
1794 if (sessionId == track->sessionId() &&
1795 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001796 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001797 }
1798 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001799 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001800}
1801
Eric Laurent53334cd2010-06-23 17:38:20 -07001802
Eric Laurent828b9772011-08-07 16:32:26 -07001803AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1804{
1805 Mutex::Autolock _l(mLock);
1806 return mOutput;
1807}
1808
1809AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1810{
1811 Mutex::Autolock _l(mLock);
1812 AudioStreamOut *output = mOutput;
1813 mOutput = NULL;
1814 return output;
1815}
1816
1817// this method must always be called either with ThreadBase mLock held or inside the thread loop
1818audio_stream_t* AudioFlinger::PlaybackThread::stream()
1819{
1820 if (mOutput == NULL) {
1821 return NULL;
1822 }
1823 return &mOutput->stream->common;
1824}
1825
Eric Laurent44331692011-12-05 09:47:19 -08001826uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1827{
1828 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1829 // decoding and transfer time. So sleeping for half of the latency would likely cause
1830 // underruns
1831 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1832 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1833 } else {
1834 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1835 }
1836}
1837
Eric Laurenta553c252009-07-17 12:17:14 -07001838// ----------------------------------------------------------------------------
1839
Dima Zavin31f188892011-04-18 16:57:27 -07001840AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001841 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001842 mAudioMixer(NULL)
Eric Laurenta553c252009-07-17 12:17:14 -07001843{
Eric Laurent464d5b32011-06-17 21:29:58 -07001844 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001845 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1846
1847 // FIXME - Current mixer implementation only supports stereo output
1848 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001849 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001851}
1852
Eric Laurenta553c252009-07-17 12:17:14 -07001853AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001854{
Eric Laurenta553c252009-07-17 12:17:14 -07001855 delete mAudioMixer;
1856}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857
Eric Laurenta553c252009-07-17 12:17:14 -07001858bool AudioFlinger::MixerThread::threadLoop()
1859{
Eric Laurenta553c252009-07-17 12:17:14 -07001860 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001861 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001862 nsecs_t standbyTime = systemTime();
1863 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001864 // FIXME: Relaxed timing because of a certain device that can't meet latency
1865 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001866 // increase threshold again due to low power audio mode. The way this warning threshold is
1867 // calculated and its usefulness should be reconsidered anyway.
1868 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001869 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001870 bool longStandbyExit = false;
1871 uint32_t activeSleepTime = activeSleepTimeUs();
1872 uint32_t idleSleepTime = idleSleepTimeUs();
1873 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001874 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001875 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001876#ifdef DEBUG_CPU_USAGE
1877 ThreadCpuUsage cpu;
1878 const CentralTendencyStatistics& stats = cpu.statistics();
1879#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880
Eric Laurent6dbdc402011-07-22 09:04:31 -07001881 acquireWakeLock();
1882
Eric Laurenta553c252009-07-17 12:17:14 -07001883 while (!exitPending())
1884 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001885#ifdef DEBUG_CPU_USAGE
1886 cpu.sampleAndEnable();
1887 unsigned n = stats.n();
1888 // cpu.elapsed() is expensive, so don't call it every loop
1889 if ((n & 127) == 1) {
1890 long long elapsed = cpu.elapsed();
1891 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1892 double perLoop = elapsed / (double) n;
1893 double perLoop100 = perLoop * 0.01;
1894 double mean = stats.mean();
1895 double stddev = stats.stddev();
1896 double minimum = stats.minimum();
1897 double maximum = stats.maximum();
1898 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001899 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 -07001900 elapsed * .000000001, n, perLoop * .000001,
1901 mean * .001,
1902 stddev * .001,
1903 minimum * .001,
1904 maximum * .001,
1905 mean / perLoop100,
1906 stddev / perLoop100,
1907 minimum / perLoop100,
1908 maximum / perLoop100);
1909 }
1910 }
1911#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001912 processConfigEvents();
1913
Eric Laurent059b4be2009-11-09 23:32:22 -08001914 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001915 { // scope for mLock
1916
1917 Mutex::Autolock _l(mLock);
1918
1919 if (checkForNewParameters_l()) {
1920 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001921 // FIXME: Relaxed timing because of a certain device that can't meet latency
1922 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001923 // increase threshold again due to low power audio mode. The way this warning
1924 // threshold is calculated and its usefulness should be reconsidered anyway.
1925 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001926 activeSleepTime = activeSleepTimeUs();
1927 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001928 }
1929
1930 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1931
1932 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001933 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1934 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001935 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001936 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001937 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001938 mStandby = true;
1939 mBytesWritten = 0;
1940 }
1941
1942 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1943 // we're about to wait, flush the binder command buffer
1944 IPCThreadState::self()->flushCommands();
1945
1946 if (exitPending()) break;
1947
Eric Laurent6dbdc402011-07-22 09:04:31 -07001948 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001949 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001950 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001951 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001952 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001953 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001954
1955 if (mMasterMute == false) {
1956 char value[PROPERTY_VALUE_MAX];
1957 property_get("ro.audio.silent", value, "0");
1958 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001959 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001960 setMasterMute(true);
1961 }
1962 }
1963
1964 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001965 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001966 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001967 continue;
1968 }
1969 }
1970
Eric Laurent059b4be2009-11-09 23:32:22 -08001971 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001972
1973 // prevent any changes in effect chain list and in each effect chain
1974 // during mixing and effect process as the audio buffers could be deleted
1975 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001976 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001977 }
Eric Laurenta553c252009-07-17 12:17:14 -07001978
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001979 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001980 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001981 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001982 sleepTime = 0;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001983 // increase sleep time progressively when application underrun condition clears
1984 if (sleepTimeShift > 0) {
1985 sleepTimeShift--;
1986 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001987 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001988 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001989 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001990 // If no tracks are ready, sleep once for the duration of an output
1991 // buffer size, then write 0s to the output
1992 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001993 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001994 sleepTime = activeSleepTime >> sleepTimeShift;
1995 if (sleepTime < kMinThreadSleepTimeUs) {
1996 sleepTime = kMinThreadSleepTimeUs;
1997 }
1998 // reduce sleep time in case of consecutive application underruns to avoid
1999 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2000 // duration we would end up writing less data than needed by the audio HAL if
2001 // the condition persists.
2002 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2003 sleepTimeShift++;
2004 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002005 } else {
2006 sleepTime = idleSleepTime;
2007 }
2008 } else if (mBytesWritten != 0 ||
2009 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002010 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002011 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002012 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002013 }
Eric Laurent65b65452010-06-01 23:49:17 -07002014 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002015 }
2016
2017 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002018 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002019 }
2020 // sleepTime == 0 means we must write to audio hardware
2021 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002022 for (size_t i = 0; i < effectChains.size(); i ++) {
2023 effectChains[i]->process_l();
2024 }
2025 // enable changes in effect chain
2026 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002027 mLastWriteTime = systemTime();
2028 mInWrite = true;
2029 mBytesWritten += mixBufferSize;
2030
Dima Zavin31f188892011-04-18 16:57:27 -07002031 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002032 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002033 mNumWrites++;
2034 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002035 nsecs_t now = systemTime();
2036 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002037 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002038 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002039 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00002040 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002041 ns2ms(delta), mNumDelayedWrites, this);
2042 lastWarning = now;
2043 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002044 if (mStandby) {
2045 longStandbyExit = true;
2046 }
Eric Laurenta553c252009-07-17 12:17:14 -07002047 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002048 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002049 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002050 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002051 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002052 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002053 }
2054
2055 // finally let go of all our tracks, without the lock held
2056 // since we can't guarantee the destructors won't acquire that
2057 // same lock.
2058 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002059
2060 // Effect chains will be actually deleted here if they were removed from
2061 // mEffectChains list during mixing or effects processing
2062 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002063 }
2064
2065 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002066 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002067 }
Eric Laurenta553c252009-07-17 12:17:14 -07002068
Eric Laurent6dbdc402011-07-22 09:04:31 -07002069 releaseWakeLock();
2070
Steve Block71f2cf12011-10-20 11:56:00 +01002071 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002072 return false;
2073}
2074
2075// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002076uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002077{
2078
Eric Laurent059b4be2009-11-09 23:32:22 -08002079 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002080 // find out which tracks need to be processed
2081 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002082 size_t mixedTracks = 0;
2083 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002084
2085 float masterVolume = mMasterVolume;
2086 bool masterMute = mMasterMute;
2087
Eric Laurent8cc93b92010-08-11 05:20:11 -07002088 if (masterMute) {
2089 masterVolume = 0;
2090 }
Eric Laurent65b65452010-06-01 23:49:17 -07002091 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002092 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002093 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002094 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002095 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002096 masterVolume = (float)((v + (1 << 23)) >> 24);
2097 chain.clear();
2098 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002099
Eric Laurenta553c252009-07-17 12:17:14 -07002100 for (size_t i=0 ; i<count ; i++) {
2101 sp<Track> t = activeTracks[i].promote();
2102 if (t == 0) continue;
2103
Glenn Kasten68deb152011-12-19 15:06:39 -08002104 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002105 Track* const track = t.get();
2106 audio_track_cblk_t* cblk = track->cblk();
2107
2108 // The first time a track is added we wait
2109 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002110 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002111 // make sure that we have enough frames to mix one full buffer.
2112 // enforce this condition only once to enable draining the buffer in case the client
2113 // app does not call stop() and relies on underrun to stop:
2114 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2115 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002116 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002117 if (!track->isStopped() && !track->isPausing() &&
2118 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002119 if (t->sampleRate() == (int)mSampleRate) {
2120 minFrames = mFrameCount;
2121 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002122 // +1 for rounding and +1 for additional sample needed for interpolation
2123 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2124 // add frames already consumed but not yet released by the resampler
2125 // because cblk->framesReady() will include these frames
2126 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2127 // the minimum track buffer size is normally twice the number of frames necessary
2128 // to fill one buffer and the resampler should not leave more than one buffer worth
2129 // of unreleased frames after each pass, but just in case...
2130 LOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002131 }
2132 }
2133 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002134 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002135 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002136 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002137
Eric Laurent65b65452010-06-01 23:49:17 -07002138 mixedTracks++;
2139
2140 // track->mainBuffer() != mMixBuffer means there is an effect chain
2141 // connected to the track
2142 chain.clear();
2143 if (track->mainBuffer() != mMixBuffer) {
2144 chain = getEffectChain_l(track->sessionId());
2145 // Delegate volume control to effect in track effect chain if needed
2146 if (chain != 0) {
2147 tracksWithEffect++;
2148 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002149 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002150 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002151 }
2152 }
2153
2154
2155 int param = AudioMixer::VOLUME;
2156 if (track->mFillingUpStatus == Track::FS_FILLED) {
2157 // no ramp for the first volume setting
2158 track->mFillingUpStatus = Track::FS_ACTIVE;
2159 if (track->mState == TrackBase::RESUMING) {
2160 track->mState = TrackBase::ACTIVE;
2161 param = AudioMixer::RAMP_VOLUME;
2162 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002163 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002164 } else if (cblk->server != 0) {
2165 // If the track is stopped before the first frame was mixed,
2166 // do not apply ramp
2167 param = AudioMixer::RAMP_VOLUME;
2168 }
2169
Eric Laurenta553c252009-07-17 12:17:14 -07002170 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002171 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002172 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002173 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002174 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002175 if (track->isPausing()) {
2176 track->setPaused();
2177 }
2178 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002179
Glenn Kasten871c16c2010-03-05 12:18:01 -08002180 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002181 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002182 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002183 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2184 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002185
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002186 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002187 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002188 // Delegate volume control to effect in track effect chain if needed
2189 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2190 // Do not ramp volume if volume is controlled by effect
2191 param = AudioMixer::VOLUME;
2192 track->mHasVolumeController = true;
2193 } else {
2194 // force no volume ramp when volume controller was just disabled or removed
2195 // from effect chain to avoid volume spike
2196 if (track->mHasVolumeController) {
2197 param = AudioMixer::VOLUME;
2198 }
2199 track->mHasVolumeController = false;
2200 }
2201
2202 // Convert volumes from 8.24 to 4.12 format
2203 int16_t left, right, aux;
2204 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2205 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2206 left = int16_t(v_clamped);
2207 v_clamped = (vr + (1 << 11)) >> 12;
2208 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2209 right = int16_t(v_clamped);
2210
2211 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2212 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002213
Eric Laurent65b65452010-06-01 23:49:17 -07002214 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002215 mAudioMixer->setBufferProvider(name, track);
2216 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002217
Glenn Kasten68deb152011-12-19 15:06:39 -08002218 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2219 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2220 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002221 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002222 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002223 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002224 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002225 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002226 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002227 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002228 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002229 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002230 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002231 AudioMixer::RESAMPLE,
2232 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002233 (void *)(cblk->sampleRate));
2234 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002235 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002236 AudioMixer::TRACK,
2237 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2238 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002239 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002240 AudioMixer::TRACK,
2241 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002242
2243 // reset retry count
2244 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002245 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002246 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002247 //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 -07002248 if (track->isStopped()) {
2249 track->reset();
2250 }
2251 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2252 // We have consumed all the buffers of this track.
2253 // Remove it from the list of active tracks.
2254 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002255 } else {
2256 // No buffers for this track. Give it a few chances to
2257 // fill a buffer, then remove it from active list.
2258 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002259 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002260 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002261 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002262 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002263 } else if (mixerStatus != MIXER_TRACKS_READY) {
2264 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002265 }
Eric Laurenta553c252009-07-17 12:17:14 -07002266 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002267 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002268 }
2269 }
2270
2271 // remove all the tracks that need to be...
2272 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002273 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002274 for (size_t i=0 ; i<count ; i++) {
2275 const sp<Track>& track = tracksToRemove->itemAt(i);
2276 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002277 if (track->mainBuffer() != mMixBuffer) {
2278 chain = getEffectChain_l(track->sessionId());
2279 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002280 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002281 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002282 }
2283 }
Eric Laurenta553c252009-07-17 12:17:14 -07002284 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002285 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002286 }
2287 }
2288 }
2289
Eric Laurent65b65452010-06-01 23:49:17 -07002290 // mix buffer must be cleared if all tracks are connected to an
2291 // effect chain as in this case the mixer will not write to
2292 // mix buffer and track effects will accumulate into it
2293 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2294 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2295 }
2296
Eric Laurent059b4be2009-11-09 23:32:22 -08002297 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002298}
2299
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002300void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002301{
Steve Block71f2cf12011-10-20 11:56:00 +01002302 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002303 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002304 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002305
Eric Laurenta553c252009-07-17 12:17:14 -07002306 size_t size = mTracks.size();
2307 for (size_t i = 0; i < size; i++) {
2308 sp<Track> t = mTracks[i];
2309 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002310 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002311 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002312 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002313 }
2314}
Eric Laurenta553c252009-07-17 12:17:14 -07002315
Eric Laurent05ce0942011-08-30 10:18:54 -07002316void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2317{
Steve Block71f2cf12011-10-20 11:56:00 +01002318 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002319 this, streamType, valid);
2320 Mutex::Autolock _l(mLock);
2321
2322 mStreamTypes[streamType].valid = valid;
2323}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324
Eric Laurenta553c252009-07-17 12:17:14 -07002325// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002326int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327{
2328 return mAudioMixer->getTrackName();
2329}
2330
Eric Laurenta553c252009-07-17 12:17:14 -07002331// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002332void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333{
Steve Block71f2cf12011-10-20 11:56:00 +01002334 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 mAudioMixer->deleteTrackName(name);
2336}
2337
Eric Laurenta553c252009-07-17 12:17:14 -07002338// checkForNewParameters_l() must be called with ThreadBase::mLock held
2339bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340{
Eric Laurenta553c252009-07-17 12:17:14 -07002341 bool reconfig = false;
2342
Eric Laurent8fce46a2009-08-04 09:45:33 -07002343 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002344 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002345 String8 keyValuePair = mNewParameters[0];
2346 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002347 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002348
Eric Laurenta553c252009-07-17 12:17:14 -07002349 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2350 reconfig = true;
2351 }
2352 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002353 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002354 status = BAD_VALUE;
2355 } else {
2356 reconfig = true;
2357 }
2358 }
2359 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002360 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002361 status = BAD_VALUE;
2362 } else {
2363 reconfig = true;
2364 }
2365 }
2366 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2367 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002368 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002369 // if frame count is changed after track creation
2370 if (!mTracks.isEmpty()) {
2371 status = INVALID_OPERATION;
2372 } else {
2373 reconfig = true;
2374 }
2375 }
Eric Laurent65b65452010-06-01 23:49:17 -07002376 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002377 // when changing the audio output device, call addBatteryData to notify
2378 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002379 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002380 uint32_t params = 0;
2381 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002382 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002383 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2384 }
2385
2386 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002387 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002388 // check if any other device (except speaker) is on
2389 if (value & deviceWithoutSpeaker ) {
2390 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2391 }
2392
2393 if (params != 0) {
2394 addBatteryData(params);
2395 }
2396 }
2397
Eric Laurent65b65452010-06-01 23:49:17 -07002398 // forward device change to effects that have requested to be
2399 // aware of attached audio device.
2400 mDevice = (uint32_t)value;
2401 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002402 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002403 }
2404 }
2405
Eric Laurenta553c252009-07-17 12:17:14 -07002406 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002407 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002408 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002409 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002410 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002411 mStandby = true;
2412 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002413 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002414 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002415 }
2416 if (status == NO_ERROR && reconfig) {
2417 delete mAudioMixer;
2418 readOutputParameters();
2419 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2420 for (size_t i = 0; i < mTracks.size() ; i++) {
2421 int name = getTrackName_l();
2422 if (name < 0) break;
2423 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002424 // limit track sample rate to 2 x new output sample rate
2425 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2426 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2427 }
Eric Laurenta553c252009-07-17 12:17:14 -07002428 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002429 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002430 }
2431 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002432
2433 mNewParameters.removeAt(0);
2434
Eric Laurenta553c252009-07-17 12:17:14 -07002435 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002436 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002437 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2438 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002439 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002440 }
2441 return reconfig;
2442}
2443
2444status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2445{
2446 const size_t SIZE = 256;
2447 char buffer[SIZE];
2448 String8 result;
2449
2450 PlaybackThread::dumpInternals(fd, args);
2451
2452 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2453 result.append(buffer);
2454 write(fd, result.string(), result.size());
2455 return NO_ERROR;
2456}
2457
Eric Laurent059b4be2009-11-09 23:32:22 -08002458uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2459{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002460 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002461}
2462
Eric Laurent8448a792010-08-18 18:13:17 -07002463uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2464{
2465 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2466}
2467
Eric Laurenta553c252009-07-17 12:17:14 -07002468// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002469AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002470 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002471{
Eric Laurent464d5b32011-06-17 21:29:58 -07002472 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002473}
2474
2475AudioFlinger::DirectOutputThread::~DirectOutputThread()
2476{
2477}
2478
Eric Laurent65b65452010-06-01 23:49:17 -07002479static inline
2480int32_t mul(int16_t in, int16_t v)
2481{
2482#if defined(__arm__) && !defined(__thumb__)
2483 int32_t out;
2484 asm( "smulbb %[out], %[in], %[v] \n"
2485 : [out]"=r"(out)
2486 : [in]"%r"(in), [v]"r"(v)
2487 : );
2488 return out;
2489#else
2490 return in * int32_t(v);
2491#endif
2492}
2493
2494void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2495{
2496 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002497 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002498 return;
2499 }
2500
2501 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002502 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002503 size_t count = mFrameCount * mChannelCount;
2504 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2505 int16_t *dst = mMixBuffer + count-1;
2506 while(count--) {
2507 *dst-- = (int16_t)(*src--^0x80) << 8;
2508 }
2509 }
2510
2511 size_t frameCount = mFrameCount;
2512 int16_t *out = mMixBuffer;
2513 if (ramp) {
2514 if (mChannelCount == 1) {
2515 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2516 int32_t vlInc = d / (int32_t)frameCount;
2517 int32_t vl = ((int32_t)mLeftVolShort << 16);
2518 do {
2519 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2520 out++;
2521 vl += vlInc;
2522 } while (--frameCount);
2523
2524 } else {
2525 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2526 int32_t vlInc = d / (int32_t)frameCount;
2527 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2528 int32_t vrInc = d / (int32_t)frameCount;
2529 int32_t vl = ((int32_t)mLeftVolShort << 16);
2530 int32_t vr = ((int32_t)mRightVolShort << 16);
2531 do {
2532 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2533 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2534 out += 2;
2535 vl += vlInc;
2536 vr += vrInc;
2537 } while (--frameCount);
2538 }
2539 } else {
2540 if (mChannelCount == 1) {
2541 do {
2542 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2543 out++;
2544 } while (--frameCount);
2545 } else {
2546 do {
2547 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2548 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2549 out += 2;
2550 } while (--frameCount);
2551 }
2552 }
2553
2554 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002555 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002556 size_t count = mFrameCount * mChannelCount;
2557 int16_t *src = mMixBuffer;
2558 uint8_t *dst = (uint8_t *)mMixBuffer;
2559 while(count--) {
2560 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2561 }
2562 }
2563
2564 mLeftVolShort = leftVol;
2565 mRightVolShort = rightVol;
2566}
2567
Eric Laurenta553c252009-07-17 12:17:14 -07002568bool AudioFlinger::DirectOutputThread::threadLoop()
2569{
Eric Laurent059b4be2009-11-09 23:32:22 -08002570 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002571 sp<Track> trackToRemove;
2572 sp<Track> activeTrack;
2573 nsecs_t standbyTime = systemTime();
2574 int8_t *curBuf;
2575 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002576 uint32_t activeSleepTime = activeSleepTimeUs();
2577 uint32_t idleSleepTime = idleSleepTimeUs();
2578 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002579 // use shorter standby delay as on normal output to release
2580 // hardware resources as soon as possible
2581 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002582
Eric Laurent6dbdc402011-07-22 09:04:31 -07002583 acquireWakeLock();
2584
Eric Laurenta553c252009-07-17 12:17:14 -07002585 while (!exitPending())
2586 {
Eric Laurent65b65452010-06-01 23:49:17 -07002587 bool rampVolume;
2588 uint16_t leftVol;
2589 uint16_t rightVol;
2590 Vector< sp<EffectChain> > effectChains;
2591
Eric Laurenta553c252009-07-17 12:17:14 -07002592 processConfigEvents();
2593
Eric Laurent059b4be2009-11-09 23:32:22 -08002594 mixerStatus = MIXER_IDLE;
2595
Eric Laurenta553c252009-07-17 12:17:14 -07002596 { // scope for the mLock
2597
2598 Mutex::Autolock _l(mLock);
2599
2600 if (checkForNewParameters_l()) {
2601 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002602 activeSleepTime = activeSleepTimeUs();
2603 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002604 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002605 }
2606
2607 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002608 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2609 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002610 // wait until we have something to do...
2611 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002612 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002613 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002614 mStandby = true;
2615 mBytesWritten = 0;
2616 }
2617
2618 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2619 // we're about to wait, flush the binder command buffer
2620 IPCThreadState::self()->flushCommands();
2621
2622 if (exitPending()) break;
2623
Eric Laurent6dbdc402011-07-22 09:04:31 -07002624 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002625 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002626 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002627 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002628 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002629
2630 if (mMasterMute == false) {
2631 char value[PROPERTY_VALUE_MAX];
2632 property_get("ro.audio.silent", value, "0");
2633 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002634 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002635 setMasterMute(true);
2636 }
2637 }
2638
Eric Laurentef9500f2010-03-11 14:47:00 -08002639 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002640 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002641 continue;
2642 }
2643 }
2644
Eric Laurent65b65452010-06-01 23:49:17 -07002645 effectChains = mEffectChains;
2646
Eric Laurenta553c252009-07-17 12:17:14 -07002647 // find out which tracks need to be processed
2648 if (mActiveTracks.size() != 0) {
2649 sp<Track> t = mActiveTracks[0].promote();
2650 if (t == 0) continue;
2651
2652 Track* const track = t.get();
2653 audio_track_cblk_t* cblk = track->cblk();
2654
2655 // The first time a track is added we wait
2656 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002657 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002658 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002659 {
Steve Block71f2cf12011-10-20 11:56:00 +01002660 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002661
Eric Laurent65b65452010-06-01 23:49:17 -07002662 if (track->mFillingUpStatus == Track::FS_FILLED) {
2663 track->mFillingUpStatus = Track::FS_ACTIVE;
2664 mLeftVolFloat = mRightVolFloat = 0;
2665 mLeftVolShort = mRightVolShort = 0;
2666 if (track->mState == TrackBase::RESUMING) {
2667 track->mState = TrackBase::ACTIVE;
2668 rampVolume = true;
2669 }
2670 } else if (cblk->server != 0) {
2671 // If the track is stopped before the first frame was mixed,
2672 // do not apply ramp
2673 rampVolume = true;
2674 }
Eric Laurenta553c252009-07-17 12:17:14 -07002675 // compute volume for this track
2676 float left, right;
2677 if (track->isMuted() || mMasterMute || track->isPausing() ||
2678 mStreamTypes[track->type()].mute) {
2679 left = right = 0;
2680 if (track->isPausing()) {
2681 track->setPaused();
2682 }
2683 } else {
2684 float typeVolume = mStreamTypes[track->type()].volume;
2685 float v = mMasterVolume * typeVolume;
2686 float v_clamped = v * cblk->volume[0];
2687 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2688 left = v_clamped/MAX_GAIN;
2689 v_clamped = v * cblk->volume[1];
2690 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2691 right = v_clamped/MAX_GAIN;
2692 }
2693
Eric Laurent65b65452010-06-01 23:49:17 -07002694 if (left != mLeftVolFloat || right != mRightVolFloat) {
2695 mLeftVolFloat = left;
2696 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002697
Eric Laurent65b65452010-06-01 23:49:17 -07002698 // If audio HAL implements volume control,
2699 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002700 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002701 left = 1.0f;
2702 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002703 }
Eric Laurent65b65452010-06-01 23:49:17 -07002704
2705 // Convert volumes from float to 8.24
2706 uint32_t vl = (uint32_t)(left * (1 << 24));
2707 uint32_t vr = (uint32_t)(right * (1 << 24));
2708
2709 // Delegate volume control to effect in track effect chain if needed
2710 // only one effect chain can be present on DirectOutputThread, so if
2711 // there is one, the track is connected to it
2712 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002713 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002714 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002715 rampVolume = false;
2716 }
2717 }
2718
2719 // Convert volumes from 8.24 to 4.12 format
2720 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2721 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2722 leftVol = (uint16_t)v_clamped;
2723 v_clamped = (vr + (1 << 11)) >> 12;
2724 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2725 rightVol = (uint16_t)v_clamped;
2726 } else {
2727 leftVol = mLeftVolShort;
2728 rightVol = mRightVolShort;
2729 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002730 }
2731
2732 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002733 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002734 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002735 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002736 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002737 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002738 if (track->isStopped()) {
2739 track->reset();
2740 }
2741 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2742 // We have consumed all the buffers of this track.
2743 // Remove it from the list of active tracks.
2744 trackToRemove = track;
2745 } else {
2746 // No buffers for this track. Give it a few chances to
2747 // fill a buffer, then remove it from active list.
2748 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002749 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002750 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002751 } else {
2752 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002753 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002754 }
Eric Laurenta553c252009-07-17 12:17:14 -07002755 }
2756 }
2757
2758 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002759 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002760 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002761 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002762 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002763 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002764 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002765 }
Eric Laurenta553c252009-07-17 12:17:14 -07002766 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002767 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002768 }
2769 }
Eric Laurent65b65452010-06-01 23:49:17 -07002770
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002771 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002772 }
2773
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002774 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002775 AudioBufferProvider::Buffer buffer;
2776 size_t frameCount = mFrameCount;
2777 curBuf = (int8_t *)mMixBuffer;
2778 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002779 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002780 buffer.frameCount = frameCount;
2781 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002782 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002783 memset(curBuf, 0, frameCount * mFrameSize);
2784 break;
2785 }
2786 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2787 frameCount -= buffer.frameCount;
2788 curBuf += buffer.frameCount * mFrameSize;
2789 activeTrack->releaseBuffer(&buffer);
2790 }
2791 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002792 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002793 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002794 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002795 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2796 sleepTime = activeSleepTime;
2797 } else {
2798 sleepTime = idleSleepTime;
2799 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002800 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002801 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002802 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002803 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002804 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002805
Eric Laurentf69a3f82009-09-22 00:35:48 -07002806 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002807 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002808 }
2809 // sleepTime == 0 means we must write to audio hardware
2810 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002811 if (mixerStatus == MIXER_TRACKS_READY) {
2812 applyVolume(leftVol, rightVol, rampVolume);
2813 }
2814 for (size_t i = 0; i < effectChains.size(); i ++) {
2815 effectChains[i]->process_l();
2816 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002817 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002818
Eric Laurentf69a3f82009-09-22 00:35:48 -07002819 mLastWriteTime = systemTime();
2820 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002821 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002822 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002823 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002824 mNumWrites++;
2825 mInWrite = false;
2826 mStandby = false;
2827 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002828 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002829 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002830 }
2831
2832 // finally let go of removed track, without the lock held
2833 // since we can't guarantee the destructors won't acquire that
2834 // same lock.
2835 trackToRemove.clear();
2836 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002837
2838 // Effect chains will be actually deleted here if they were removed from
2839 // mEffectChains list during mixing or effects processing
2840 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002841 }
2842
2843 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002844 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002845 }
Eric Laurenta553c252009-07-17 12:17:14 -07002846
Eric Laurent6dbdc402011-07-22 09:04:31 -07002847 releaseWakeLock();
2848
Steve Block71f2cf12011-10-20 11:56:00 +01002849 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002850 return false;
2851}
2852
2853// getTrackName_l() must be called with ThreadBase::mLock held
2854int AudioFlinger::DirectOutputThread::getTrackName_l()
2855{
2856 return 0;
2857}
2858
2859// deleteTrackName_l() must be called with ThreadBase::mLock held
2860void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2861{
2862}
2863
2864// checkForNewParameters_l() must be called with ThreadBase::mLock held
2865bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2866{
2867 bool reconfig = false;
2868
Eric Laurent8fce46a2009-08-04 09:45:33 -07002869 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002870 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002871 String8 keyValuePair = mNewParameters[0];
2872 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002873 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002874
Eric Laurenta553c252009-07-17 12:17:14 -07002875 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2876 // do not accept frame count changes if tracks are open as the track buffer
2877 // size depends on frame count and correct behavior would not be garantied
2878 // if frame count is changed after track creation
2879 if (!mTracks.isEmpty()) {
2880 status = INVALID_OPERATION;
2881 } else {
2882 reconfig = true;
2883 }
2884 }
2885 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002886 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002887 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002888 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002889 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002890 mStandby = true;
2891 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002892 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002893 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002894 }
2895 if (status == NO_ERROR && reconfig) {
2896 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002897 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002898 }
2899 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002900
2901 mNewParameters.removeAt(0);
2902
Eric Laurenta553c252009-07-17 12:17:14 -07002903 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002904 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002905 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2906 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002907 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002908 }
2909 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002910}
2911
Eric Laurent059b4be2009-11-09 23:32:22 -08002912uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002913{
2914 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002915 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002916 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002917 } else {
2918 time = 10000;
2919 }
2920 return time;
2921}
2922
2923uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2924{
2925 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002926 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002927 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002928 } else {
2929 time = 10000;
2930 }
2931 return time;
2932}
2933
Eric Laurent8448a792010-08-18 18:13:17 -07002934uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2935{
2936 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002937 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002938 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2939 } else {
2940 time = 10000;
2941 }
2942 return time;
2943}
2944
2945
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002946// ----------------------------------------------------------------------------
2947
Eric Laurent49f02be2009-11-19 09:00:56 -08002948AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002949 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002950{
Eric Laurent464d5b32011-06-17 21:29:58 -07002951 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002952 addOutputTrack(mainThread);
2953}
2954
2955AudioFlinger::DuplicatingThread::~DuplicatingThread()
2956{
Eric Laurent0a080292009-12-07 10:53:10 -08002957 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2958 mOutputTracks[i]->destroy();
2959 }
Eric Laurenta553c252009-07-17 12:17:14 -07002960 mOutputTracks.clear();
2961}
2962
2963bool AudioFlinger::DuplicatingThread::threadLoop()
2964{
Eric Laurenta553c252009-07-17 12:17:14 -07002965 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002966 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002967 nsecs_t standbyTime = systemTime();
2968 size_t mixBufferSize = mFrameCount*mFrameSize;
2969 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002970 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002971 uint32_t activeSleepTime = activeSleepTimeUs();
2972 uint32_t idleSleepTime = idleSleepTimeUs();
2973 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002974 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002975
Eric Laurent6dbdc402011-07-22 09:04:31 -07002976 acquireWakeLock();
2977
Eric Laurenta553c252009-07-17 12:17:14 -07002978 while (!exitPending())
2979 {
2980 processConfigEvents();
2981
Eric Laurent059b4be2009-11-09 23:32:22 -08002982 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002983 { // scope for the mLock
2984
2985 Mutex::Autolock _l(mLock);
2986
2987 if (checkForNewParameters_l()) {
2988 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002989 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002990 activeSleepTime = activeSleepTimeUs();
2991 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002992 }
2993
2994 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2995
2996 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2997 outputTracks.add(mOutputTracks[i]);
2998 }
2999
3000 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003001 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3002 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003003 if (!mStandby) {
3004 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003005 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003006 }
3007 mStandby = true;
3008 mBytesWritten = 0;
3009 }
3010
3011 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3012 // we're about to wait, flush the binder command buffer
3013 IPCThreadState::self()->flushCommands();
3014 outputTracks.clear();
3015
3016 if (exitPending()) break;
3017
Eric Laurent6dbdc402011-07-22 09:04:31 -07003018 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003019 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003020 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003021 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003022 acquireWakeLock_l();
3023
Eric Laurenta553c252009-07-17 12:17:14 -07003024 if (mMasterMute == false) {
3025 char value[PROPERTY_VALUE_MAX];
3026 property_get("ro.audio.silent", value, "0");
3027 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003028 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003029 setMasterMute(true);
3030 }
3031 }
3032
3033 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003034 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003035 continue;
3036 }
3037 }
3038
Eric Laurent059b4be2009-11-09 23:32:22 -08003039 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003040
3041 // prevent any changes in effect chain list and in each effect chain
3042 // during mixing and effect process as the audio buffers could be deleted
3043 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003044 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003045 }
Eric Laurenta553c252009-07-17 12:17:14 -07003046
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003047 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003048 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003049 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003050 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003051 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003052 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003053 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003054 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003055 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003056 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003057 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003058 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3059 sleepTime = activeSleepTime;
3060 } else {
3061 sleepTime = idleSleepTime;
3062 }
Eric Laurent62443f52009-10-05 20:29:18 -07003063 } else if (mBytesWritten != 0) {
3064 // flush remaining overflow buffers in output tracks
3065 for (size_t i = 0; i < outputTracks.size(); i++) {
3066 if (outputTracks[i]->isActive()) {
3067 sleepTime = 0;
3068 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003069 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003070 break;
3071 }
3072 }
Eric Laurenta553c252009-07-17 12:17:14 -07003073 }
3074 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003075
3076 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003077 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003078 }
3079 // sleepTime == 0 means we must write to audio hardware
3080 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003081 for (size_t i = 0; i < effectChains.size(); i ++) {
3082 effectChains[i]->process_l();
3083 }
3084 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003085 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003086
Eric Laurent62443f52009-10-05 20:29:18 -07003087 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003088 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003089 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003090 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003091 mStandby = false;
3092 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003093 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003094 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003095 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003096 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003097 }
3098
3099 // finally let go of all our tracks, without the lock held
3100 // since we can't guarantee the destructors won't acquire that
3101 // same lock.
3102 tracksToRemove.clear();
3103 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003104
3105 // Effect chains will be actually deleted here if they were removed from
3106 // mEffectChains list during mixing or effects processing
3107 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003108 }
3109
Eric Laurent6dbdc402011-07-22 09:04:31 -07003110 releaseWakeLock();
3111
Eric Laurenta553c252009-07-17 12:17:14 -07003112 return false;
3113}
3114
3115void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3116{
3117 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3118 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003119 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003120 mSampleRate,
3121 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003122 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003123 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003124 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003125 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003126 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003127 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003128 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003129 }
Eric Laurenta553c252009-07-17 12:17:14 -07003130}
3131
3132void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3133{
3134 Mutex::Autolock _l(mLock);
3135 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3136 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003137 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003138 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003139 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003140 return;
3141 }
3142 }
Steve Block71f2cf12011-10-20 11:56:00 +01003143 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003144}
3145
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003146void AudioFlinger::DuplicatingThread::updateWaitTime()
3147{
3148 mWaitTimeMs = UINT_MAX;
3149 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3150 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3151 if (strong != NULL) {
3152 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3153 if (waitTimeMs < mWaitTimeMs) {
3154 mWaitTimeMs = waitTimeMs;
3155 }
3156 }
3157 }
3158}
3159
3160
3161bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3162{
3163 for (size_t i = 0; i < outputTracks.size(); i++) {
3164 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3165 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003166 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003167 return false;
3168 }
3169 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3170 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003171 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003172 return false;
3173 }
3174 }
3175 return true;
3176}
3177
3178uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3179{
3180 return (mWaitTimeMs * 1000) / 2;
3181}
3182
Eric Laurenta553c252009-07-17 12:17:14 -07003183// ----------------------------------------------------------------------------
3184
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003185// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003186AudioFlinger::ThreadBase::TrackBase::TrackBase(
3187 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003188 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003189 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003190 uint32_t format,
3191 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003192 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003194 const sp<IMemory>& sharedBuffer,
3195 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003196 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003197 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003198 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003199 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003200 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003201 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003202 mClientTid(-1),
3203 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003204 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3205 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003206{
Steve Block71f2cf12011-10-20 11:56:00 +01003207 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003208
Steve Block5baa3a62011-12-20 16:23:08 +00003209 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003210 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003211 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003212 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3213 if (sharedBuffer == 0) {
3214 size += bufferSize;
3215 }
3216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 if (client != NULL) {
3218 mCblkMemory = client->heap()->allocate(size);
3219 if (mCblkMemory != 0) {
3220 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3221 if (mCblk) { // construct the shared structure in-place.
3222 new(mCblk) audio_track_cblk_t();
3223 // clear all buffers
3224 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003225 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003226 mChannelCount = channelCount;
3227 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 if (sharedBuffer == 0) {
3229 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3230 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3231 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003232 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003233 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 } else {
3235 mBuffer = sharedBuffer->pointer();
3236 }
3237 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 } else {
Steve Block3762c312012-01-06 19:20:56 +00003240 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 client->heap()->dump("AudioTrack");
3242 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 } else {
3245 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3246 if (mCblk) { // construct the shared structure in-place.
3247 new(mCblk) audio_track_cblk_t();
3248 // clear all buffers
3249 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003250 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003251 mChannelCount = channelCount;
3252 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3254 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3255 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003256 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003257 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3259 }
3260 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003261}
3262
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003263AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003264{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003266 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3267 if (mClient == NULL) {
3268 delete mCblk;
3269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003271 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003272 if (mClient != NULL) {
3273 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3274 mClient.clear();
3275 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003276}
3277
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003278void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003279{
Glenn Kastenc434c902011-12-13 11:53:26 -08003280 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003281 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003282 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003283 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003284}
3285
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003286bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003287 bool result;
3288 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003289
3290 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003291 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003292 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003293 mFlags |= STEPSERVER_FAILED;
3294 }
3295 return result;
3296}
3297
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003298void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003299 audio_track_cblk_t* cblk = this->cblk();
3300
3301 cblk->user = 0;
3302 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003303 cblk->userBase = 0;
3304 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003306 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003307}
3308
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003309sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003310{
3311 return mCblkMemory;
3312}
3313
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003314int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003315 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003316}
3317
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003318int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003319 return (const int)mChannelCount;
3320}
3321
3322uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3323 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003324}
3325
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003326void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003327 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003328 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3329 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003330
3331 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003332 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3333 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003334 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 -07003335 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003336 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003337 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003338 return 0;
3339 }
3340
3341 return bufferStart;
3342}
3343
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003344// ----------------------------------------------------------------------------
3345
Eric Laurenta553c252009-07-17 12:17:14 -07003346// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3347AudioFlinger::PlaybackThread::Track::Track(
3348 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003349 const sp<Client>& client,
3350 int streamType,
3351 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003352 uint32_t format,
3353 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003354 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003355 const sp<IMemory>& sharedBuffer,
3356 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003357 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003358 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3359 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003360{
Eric Laurent8a77a992009-09-09 05:16:08 -07003361 if (mCblk != NULL) {
3362 sp<ThreadBase> baseThread = thread.promote();
3363 if (baseThread != 0) {
3364 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3365 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003366 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003367 }
Steve Block71f2cf12011-10-20 11:56:00 +01003368 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003369 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003370 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003371 }
3372 mVolume[0] = 1.0f;
3373 mVolume[1] = 1.0f;
3374 mStreamType = streamType;
3375 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3376 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003377 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003378 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003379}
3380
Eric Laurenta553c252009-07-17 12:17:14 -07003381AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003382{
Steve Block71f2cf12011-10-20 11:56:00 +01003383 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003384 sp<ThreadBase> thread = mThread.promote();
3385 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003386 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003387 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003388 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003389}
3390
Eric Laurenta553c252009-07-17 12:17:14 -07003391void AudioFlinger::PlaybackThread::Track::destroy()
3392{
3393 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3394 // by removing it from mTracks vector, so there is a risk that this Tracks's
3395 // desctructor is called. As the destructor needs to lock mLock,
3396 // we must acquire a strong reference on this Track before locking mLock
3397 // here so that the destructor is called only when exiting this function.
3398 // On the other hand, as long as Track::destroy() is only called by
3399 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3400 // this Track with its member mTrack.
3401 sp<Track> keep(this);
3402 { // scope for mLock
3403 sp<ThreadBase> thread = mThread.promote();
3404 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003405 if (!isOutputTrack()) {
3406 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003407 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003408 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003409 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003410
3411 // to track the speaker usage
3412 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003413 }
3414 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003415 }
Eric Laurenta553c252009-07-17 12:17:14 -07003416 Mutex::Autolock _l(thread->mLock);
3417 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3418 playbackThread->destroyTrack_l(this);
3419 }
3420 }
3421}
3422
3423void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003424{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003425 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 -07003426 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003428 mStreamType,
3429 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003430 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003431 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003432 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003433 mState,
3434 mMute,
3435 mFillingUpStatus,
3436 mCblk->sampleRate,
3437 mCblk->volume[0],
3438 mCblk->volume[1],
3439 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003440 mCblk->user,
3441 (int)mMainBuffer,
3442 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003443}
3444
Eric Laurenta553c252009-07-17 12:17:14 -07003445status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003446{
3447 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003448 uint32_t framesReady;
3449 uint32_t framesReq = buffer->frameCount;
3450
3451 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003452 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3453 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003454 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003455 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3456 }
3457
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003458 framesReady = cblk->framesReady();
3459
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003460 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003461 uint32_t s = cblk->server;
3462 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3463
3464 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3465 if (framesReq > framesReady) {
3466 framesReq = framesReady;
3467 }
3468 if (s + framesReq > bufferEnd) {
3469 framesReq = bufferEnd - s;
3470 }
3471
3472 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003473 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003474
3475 buffer->frameCount = framesReq;
3476 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003477 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003478
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003479getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003480 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003481 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003482 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 -07003483 return NOT_ENOUGH_DATA;
3484}
3485
Eric Laurenta553c252009-07-17 12:17:14 -07003486bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003487 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003488
3489 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003490 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003491 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003492 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003493 return true;
3494 }
3495 return false;
3496}
3497
Eric Laurenta553c252009-07-17 12:17:14 -07003498status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003499{
Eric Laurent49f02be2009-11-19 09:00:56 -08003500 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003501 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003502 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003503 sp<ThreadBase> thread = mThread.promote();
3504 if (thread != 0) {
3505 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003506 int state = mState;
3507 // here the track could be either new, or restarted
3508 // in both cases "unstop" the track
3509 if (mState == PAUSED) {
3510 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003511 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003512 } else {
3513 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003514 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003515 }
3516
3517 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3518 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003519 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003520 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003521 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003522 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003523
3524 // to track the speaker usage
3525 if (status == NO_ERROR) {
3526 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3527 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003528 }
3529 if (status == NO_ERROR) {
3530 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3531 playbackThread->addTrack_l(this);
3532 } else {
3533 mState = state;
3534 }
3535 } else {
3536 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003537 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003538 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003539}
3540
Eric Laurenta553c252009-07-17 12:17:14 -07003541void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003542{
Steve Block71f2cf12011-10-20 11:56:00 +01003543 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003544 sp<ThreadBase> thread = mThread.promote();
3545 if (thread != 0) {
3546 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003547 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003548 if (mState > STOPPED) {
3549 mState = STOPPED;
3550 // If the track is not active (PAUSED and buffers full), flush buffers
3551 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3552 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3553 reset();
3554 }
Steve Block71f2cf12011-10-20 11:56:00 +01003555 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003556 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003557 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3558 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003559 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003560 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003561 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003562 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003563
3564 // to track the speaker usage
3565 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003566 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003567 }
3568}
3569
Eric Laurenta553c252009-07-17 12:17:14 -07003570void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003571{
Steve Block71f2cf12011-10-20 11:56:00 +01003572 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003573 sp<ThreadBase> thread = mThread.promote();
3574 if (thread != 0) {
3575 Mutex::Autolock _l(thread->mLock);
3576 if (mState == ACTIVE || mState == RESUMING) {
3577 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003578 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003579 if (!isOutputTrack()) {
3580 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003581 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003582 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003583 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003584 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003585
3586 // to track the speaker usage
3587 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003588 }
Eric Laurenta553c252009-07-17 12:17:14 -07003589 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003590 }
3591}
3592
Eric Laurenta553c252009-07-17 12:17:14 -07003593void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003594{
Steve Block71f2cf12011-10-20 11:56:00 +01003595 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003596 sp<ThreadBase> thread = mThread.promote();
3597 if (thread != 0) {
3598 Mutex::Autolock _l(thread->mLock);
3599 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3600 return;
3601 }
3602 // No point remaining in PAUSED state after a flush => go to
3603 // STOPPED state
3604 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003605
Eric Laurentae29b762011-03-28 18:37:07 -07003606 // do not reset the track if it is still in the process of being stopped or paused.
3607 // this will be done by prepareTracks_l() when the track is stopped.
3608 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3609 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3610 reset();
3611 }
Eric Laurenta553c252009-07-17 12:17:14 -07003612 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003613}
3614
Eric Laurenta553c252009-07-17 12:17:14 -07003615void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003616{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003617 // Do not reset twice to avoid discarding data written just after a flush and before
3618 // the audioflinger thread detects the track is stopped.
3619 if (!mResetDone) {
3620 TrackBase::reset();
3621 // Force underrun condition to avoid false underrun callback until first data is
3622 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003623 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3624 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003625 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003626 mResetDone = true;
3627 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003628}
3629
Eric Laurenta553c252009-07-17 12:17:14 -07003630void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003631{
3632 mMute = muted;
3633}
3634
Eric Laurenta553c252009-07-17 12:17:14 -07003635void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003636{
3637 mVolume[0] = left;
3638 mVolume[1] = right;
3639}
3640
Eric Laurent65b65452010-06-01 23:49:17 -07003641status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3642{
3643 status_t status = DEAD_OBJECT;
3644 sp<ThreadBase> thread = mThread.promote();
3645 if (thread != 0) {
3646 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3647 status = playbackThread->attachAuxEffect(this, EffectId);
3648 }
3649 return status;
3650}
3651
3652void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3653{
3654 mAuxEffectId = EffectId;
3655 mAuxBuffer = buffer;
3656}
3657
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003658// ----------------------------------------------------------------------------
3659
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003660// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003661AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3662 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003665 uint32_t format,
3666 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003668 uint32_t flags,
3669 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003670 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003671 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003672 mOverflow(false)
3673{
Eric Laurent8a77a992009-09-09 05:16:08 -07003674 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003675 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003676 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003677 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003678 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003679 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003680 } else {
3681 mCblk->frameSize = sizeof(int8_t);
3682 }
3683 }
Eric Laurenta553c252009-07-17 12:17:14 -07003684}
3685
3686AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687{
Eric Laurent49f02be2009-11-19 09:00:56 -08003688 sp<ThreadBase> thread = mThread.promote();
3689 if (thread != 0) {
3690 AudioSystem::releaseInput(thread->id());
3691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692}
3693
Eric Laurenta553c252009-07-17 12:17:14 -07003694status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695{
3696 audio_track_cblk_t* cblk = this->cblk();
3697 uint32_t framesAvail;
3698 uint32_t framesReq = buffer->frameCount;
3699
3700 // Check if last stepServer failed, try to step now
3701 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3702 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003703 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3705 }
3706
3707 framesAvail = cblk->framesAvailable_l();
3708
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003709 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 uint32_t s = cblk->server;
3711 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3712
3713 if (framesReq > framesAvail) {
3714 framesReq = framesAvail;
3715 }
3716 if (s + framesReq > bufferEnd) {
3717 framesReq = bufferEnd - s;
3718 }
3719
3720 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003721 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722
3723 buffer->frameCount = framesReq;
3724 return NO_ERROR;
3725 }
3726
3727getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003728 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 buffer->frameCount = 0;
3730 return NOT_ENOUGH_DATA;
3731}
3732
Eric Laurenta553c252009-07-17 12:17:14 -07003733status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734{
Eric Laurenta553c252009-07-17 12:17:14 -07003735 sp<ThreadBase> thread = mThread.promote();
3736 if (thread != 0) {
3737 RecordThread *recordThread = (RecordThread *)thread.get();
3738 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003739 } else {
3740 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742}
3743
Eric Laurenta553c252009-07-17 12:17:14 -07003744void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745{
Eric Laurenta553c252009-07-17 12:17:14 -07003746 sp<ThreadBase> thread = mThread.promote();
3747 if (thread != 0) {
3748 RecordThread *recordThread = (RecordThread *)thread.get();
3749 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003750 TrackBase::reset();
3751 // Force overerrun condition to avoid false overrun callback until first data is
3752 // read from buffer
3753 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755}
3756
Eric Laurent3fdb1262009-11-07 00:01:32 -08003757void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3758{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003759 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003760 (mClient == NULL) ? getpid() : mClient->pid(),
3761 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003762 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003763 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003764 mFrameCount,
3765 mState,
3766 mCblk->sampleRate,
3767 mCblk->server,
3768 mCblk->user);
3769}
3770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771
3772// ----------------------------------------------------------------------------
3773
Eric Laurenta553c252009-07-17 12:17:14 -07003774AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3775 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003776 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003778 uint32_t format,
3779 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003781 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003782 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783{
Eric Laurenta553c252009-07-17 12:17:14 -07003784
3785 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003786 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003787 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003788 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3789 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3790 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003791 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003792 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003793 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3794 mCblk, mBuffer, mCblk->buffers,
3795 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003796 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003797 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07003798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799}
3800
Eric Laurenta553c252009-07-17 12:17:14 -07003801AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802{
Eric Laurent6c30a712009-08-10 23:22:32 -07003803 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804}
3805
Eric Laurenta553c252009-07-17 12:17:14 -07003806status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807{
3808 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003809 if (status != NO_ERROR) {
3810 return status;
3811 }
3812
3813 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 mRetryCount = 127;
3815 return status;
3816}
3817
Eric Laurenta553c252009-07-17 12:17:14 -07003818void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819{
3820 Track::stop();
3821 clearBufferQueue();
3822 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003823 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824}
3825
Eric Laurenta553c252009-07-17 12:17:14 -07003826bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827{
3828 Buffer *pInBuffer;
3829 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003830 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003831 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 inBuffer.frameCount = frames;
3833 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003834
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003835 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003836
Eric Laurent62443f52009-10-05 20:29:18 -07003837 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003838 start();
3839 sp<ThreadBase> thread = mThread.promote();
3840 if (thread != 0) {
3841 MixerThread *mixerThread = (MixerThread *)thread.get();
3842 if (mCblk->frameCount > frames){
3843 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3844 uint32_t startFrames = (mCblk->frameCount - frames);
3845 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003846 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003847 pInBuffer->frameCount = startFrames;
3848 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003849 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003850 mBufferQueue.add(pInBuffer);
3851 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003852 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07003853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 }
Eric Laurenta553c252009-07-17 12:17:14 -07003855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 }
3857
Eric Laurenta553c252009-07-17 12:17:14 -07003858 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 // First write pending buffers, then new data
3860 if (mBufferQueue.size()) {
3861 pInBuffer = mBufferQueue.itemAt(0);
3862 } else {
3863 pInBuffer = &inBuffer;
3864 }
Eric Laurenta553c252009-07-17 12:17:14 -07003865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 if (pInBuffer->frameCount == 0) {
3867 break;
3868 }
Eric Laurenta553c252009-07-17 12:17:14 -07003869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 if (mOutBuffer.frameCount == 0) {
3871 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003872 nsecs_t startTime = systemTime();
3873 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003874 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003875 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 break;
3877 }
Eric Laurenta553c252009-07-17 12:17:14 -07003878 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003879 if (waitTimeLeftMs >= waitTimeMs) {
3880 waitTimeLeftMs -= waitTimeMs;
3881 } else {
3882 waitTimeLeftMs = 0;
3883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 }
Eric Laurenta553c252009-07-17 12:17:14 -07003885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003887 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 mCblk->stepUser(outFrames);
3889 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003890 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003892 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 if (pInBuffer->frameCount == 0) {
3895 if (mBufferQueue.size()) {
3896 mBufferQueue.removeAt(0);
3897 delete [] pInBuffer->mBuffer;
3898 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003899 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 -08003900 } else {
3901 break;
3902 }
3903 }
3904 }
Eric Laurenta553c252009-07-17 12:17:14 -07003905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 // If we could not write all frames, allocate a buffer and queue it for next time.
3907 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003908 sp<ThreadBase> thread = mThread.promote();
3909 if (thread != 0 && !thread->standby()) {
3910 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3911 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003912 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003913 pInBuffer->frameCount = inBuffer.frameCount;
3914 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003915 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003916 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003917 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003918 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003919 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 }
3922 }
Eric Laurenta553c252009-07-17 12:17:14 -07003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003925 // 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 -08003926 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003927 if (frames == 0 && mBufferQueue.size() == 0) {
3928 if (mCblk->user < mCblk->frameCount) {
3929 frames = mCblk->frameCount - mCblk->user;
3930 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003931 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003932 pInBuffer->frameCount = frames;
3933 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003934 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003935 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003936 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003937 stop();
3938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
3940
Eric Laurenta553c252009-07-17 12:17:14 -07003941 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942}
3943
Eric Laurenta553c252009-07-17 12:17:14 -07003944status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945{
3946 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 status_t result;
3948 audio_track_cblk_t* cblk = mCblk;
3949 uint32_t framesReq = buffer->frameCount;
3950
Steve Block71f2cf12011-10-20 11:56:00 +01003951// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 uint32_t framesAvail = cblk->framesAvailable();
3955
Eric Laurenta553c252009-07-17 12:17:14 -07003956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003958 Mutex::Autolock _l(cblk->lock);
3959 goto start_loop_here;
3960 while (framesAvail == 0) {
3961 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003962 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003963 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurenta553c252009-07-17 12:17:14 -07003964 return AudioTrack::NO_MORE_BUFFERS;
3965 }
3966 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3967 if (result != NO_ERROR) {
3968 return AudioTrack::NO_MORE_BUFFERS;
3969 }
3970 // read the server count again
3971 start_loop_here:
3972 framesAvail = cblk->framesAvailable_l();
3973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 }
3975
Eric Laurenta553c252009-07-17 12:17:14 -07003976// if (framesAvail < framesReq) {
3977// return AudioTrack::NO_MORE_BUFFERS;
3978// }
3979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 if (framesReq > framesAvail) {
3981 framesReq = framesAvail;
3982 }
3983
3984 uint32_t u = cblk->user;
3985 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3986
3987 if (u + framesReq > bufferEnd) {
3988 framesReq = bufferEnd - u;
3989 }
3990
3991 buffer->frameCount = framesReq;
3992 buffer->raw = (void *)cblk->buffer(u);
3993 return NO_ERROR;
3994}
3995
3996
Eric Laurenta553c252009-07-17 12:17:14 -07003997void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998{
3999 size_t size = mBufferQueue.size();
4000 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 for (size_t i = 0; i < size; i++) {
4003 pBuffer = mBufferQueue.itemAt(i);
4004 delete [] pBuffer->mBuffer;
4005 delete pBuffer;
4006 }
4007 mBufferQueue.clear();
4008}
4009
4010// ----------------------------------------------------------------------------
4011
4012AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4013 : RefBase(),
4014 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004015 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 mPid(pid)
4017{
4018 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4019}
4020
Eric Laurentb9481d82009-09-17 05:12:56 -07004021// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022AudioFlinger::Client::~Client()
4023{
Eric Laurentb9481d82009-09-17 05:12:56 -07004024 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025}
4026
4027const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4028{
4029 return mMemoryDealer;
4030}
4031
4032// ----------------------------------------------------------------------------
4033
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004034AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4035 const sp<IAudioFlingerClient>& client,
4036 pid_t pid)
4037 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4038{
4039}
4040
4041AudioFlinger::NotificationClient::~NotificationClient()
4042{
4043 mClient.clear();
4044}
4045
4046void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4047{
4048 sp<NotificationClient> keep(this);
4049 {
4050 mAudioFlinger->removeNotificationClient(mPid);
4051 }
4052}
4053
4054// ----------------------------------------------------------------------------
4055
Eric Laurenta553c252009-07-17 12:17:14 -07004056AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004057 : BnAudioTrack(),
4058 mTrack(track)
4059{
4060}
4061
4062AudioFlinger::TrackHandle::~TrackHandle() {
4063 // just stop the track on deletion, associated resources
4064 // will be freed from the main thread once all pending buffers have
4065 // been played. Unless it's not in the active track list, in which
4066 // case we free everything now...
4067 mTrack->destroy();
4068}
4069
4070status_t AudioFlinger::TrackHandle::start() {
4071 return mTrack->start();
4072}
4073
4074void AudioFlinger::TrackHandle::stop() {
4075 mTrack->stop();
4076}
4077
4078void AudioFlinger::TrackHandle::flush() {
4079 mTrack->flush();
4080}
4081
4082void AudioFlinger::TrackHandle::mute(bool e) {
4083 mTrack->mute(e);
4084}
4085
4086void AudioFlinger::TrackHandle::pause() {
4087 mTrack->pause();
4088}
4089
4090void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4091 mTrack->setVolume(left, right);
4092}
4093
4094sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4095 return mTrack->getCblk();
4096}
4097
Eric Laurent65b65452010-06-01 23:49:17 -07004098status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4099{
4100 return mTrack->attachAuxEffect(EffectId);
4101}
4102
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004103status_t AudioFlinger::TrackHandle::onTransact(
4104 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4105{
4106 return BnAudioTrack::onTransact(code, data, reply, flags);
4107}
4108
4109// ----------------------------------------------------------------------------
4110
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004111sp<IAudioRecord> AudioFlinger::openRecord(
4112 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004113 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004114 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004115 uint32_t format,
4116 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004117 int frameCount,
4118 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004119 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004120 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004121{
Eric Laurenta553c252009-07-17 12:17:14 -07004122 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004123 sp<RecordHandle> recordHandle;
4124 sp<Client> client;
4125 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004126 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004127 RecordThread *thread;
4128 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004129 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004130
4131 // check calling permissions
4132 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004133 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004134 goto Exit;
4135 }
4136
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004137 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004138 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004139 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004140 thread = checkRecordThread_l(input);
4141 if (thread == NULL) {
4142 lStatus = BAD_VALUE;
4143 goto Exit;
4144 }
4145
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004146 wclient = mClients.valueFor(pid);
4147 if (wclient != NULL) {
4148 client = wclient.promote();
4149 } else {
4150 client = new Client(this, pid);
4151 mClients.add(pid, client);
4152 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004153
Eric Laurent65b65452010-06-01 23:49:17 -07004154 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004155 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004156 lSessionId = *sessionId;
4157 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004158 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004159 if (sessionId != NULL) {
4160 *sessionId = lSessionId;
4161 }
4162 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004163 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004164 recordTrack = thread->createRecordTrack_l(client,
4165 sampleRate,
4166 format,
4167 channelMask,
4168 frameCount,
4169 flags,
4170 lSessionId,
4171 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004172 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004173 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004174 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4175 // destructor is called by the TrackBase destructor with mLock held
4176 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 goto Exit;
4179 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004180
4181 // return to handle to client
4182 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004183 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004184
4185Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004186 if (status) {
4187 *status = lStatus;
4188 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004189 return recordHandle;
4190}
4191
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004192// ----------------------------------------------------------------------------
4193
Eric Laurenta553c252009-07-17 12:17:14 -07004194AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004195 : BnAudioRecord(),
4196 mRecordTrack(recordTrack)
4197{
4198}
4199
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004200AudioFlinger::RecordHandle::~RecordHandle() {
4201 stop();
4202}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004203
4204status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004205 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004206 return mRecordTrack->start();
4207}
4208
4209void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004210 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004211 mRecordTrack->stop();
4212}
4213
4214sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4215 return mRecordTrack->getCblk();
4216}
4217
4218status_t AudioFlinger::RecordHandle::onTransact(
4219 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4220{
4221 return BnAudioRecord::onTransact(code, data, reply, flags);
4222}
4223
4224// ----------------------------------------------------------------------------
4225
Eric Laurent464d5b32011-06-17 21:29:58 -07004226AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4227 AudioStreamIn *input,
4228 uint32_t sampleRate,
4229 uint32_t channels,
4230 int id,
4231 uint32_t device) :
4232 ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08004233 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004234{
Eric Laurent464d5b32011-06-17 21:29:58 -07004235 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004236
4237 snprintf(mName, kNameLength, "AudioIn_%d", id);
4238
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004239 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004240 mReqSampleRate = sampleRate;
4241 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004242}
4243
Eric Laurenta553c252009-07-17 12:17:14 -07004244
4245AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004246{
Eric Laurenta553c252009-07-17 12:17:14 -07004247 delete[] mRsmpInBuffer;
Glenn Kastenc434c902011-12-13 11:53:26 -08004248 if (mResampler != NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004249 delete mResampler;
4250 delete[] mRsmpOutBuffer;
4251 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004252}
4253
Eric Laurenta553c252009-07-17 12:17:14 -07004254void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004255{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004256 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004257}
Eric Laurent49f02be2009-11-19 09:00:56 -08004258
Eric Laurent828b9772011-08-07 16:32:26 -07004259status_t AudioFlinger::RecordThread::readyToRun()
4260{
4261 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004262 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004263 return status;
4264}
4265
Eric Laurenta553c252009-07-17 12:17:14 -07004266bool AudioFlinger::RecordThread::threadLoop()
4267{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004268 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004269 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004270 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004271
Eric Laurent4712baa2010-09-30 16:12:31 -07004272 nsecs_t lastWarning = 0;
4273
Eric Laurent6dbdc402011-07-22 09:04:31 -07004274 acquireWakeLock();
4275
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004276 // start recording
4277 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004278
Eric Laurenta553c252009-07-17 12:17:14 -07004279 processConfigEvents();
4280
4281 { // scope for mLock
4282 Mutex::Autolock _l(mLock);
4283 checkForNewParameters_l();
4284 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4285 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004286 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004287 mStandby = true;
4288 }
4289
4290 if (exitPending()) break;
4291
Eric Laurent6dbdc402011-07-22 09:04:31 -07004292 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004293 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004294 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004295 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004296 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004297 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004298 continue;
4299 }
4300 if (mActiveTrack != 0) {
4301 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004302 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004303 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004304 mStandby = true;
4305 }
Eric Laurenta553c252009-07-17 12:17:14 -07004306 mActiveTrack.clear();
4307 mStartStopCond.broadcast();
4308 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004309 if (mReqChannelCount != mActiveTrack->channelCount()) {
4310 mActiveTrack.clear();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004311 mStartStopCond.broadcast();
4312 } else if (mBytesRead != 0) {
4313 // record start succeeds only if first read from audio input
4314 // succeeds
4315 if (mBytesRead > 0) {
4316 mActiveTrack->mState = TrackBase::ACTIVE;
4317 } else {
4318 mActiveTrack.clear();
4319 }
4320 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004321 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004322 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004323 }
Eric Laurenta553c252009-07-17 12:17:14 -07004324 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004325 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004326 }
4327
4328 if (mActiveTrack != 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004329 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4330 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004331 unlockEffectChains(effectChains);
4332 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004333 continue;
4334 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004335 for (size_t i = 0; i < effectChains.size(); i ++) {
4336 effectChains[i]->process_l();
4337 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004338
Eric Laurenta553c252009-07-17 12:17:14 -07004339 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004340 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004341 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004342 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004343 // no resampling
4344 while (framesOut) {
4345 size_t framesIn = mFrameCount - mRsmpInIndex;
4346 if (framesIn) {
4347 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4348 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4349 if (framesIn > framesOut)
4350 framesIn = framesOut;
4351 mRsmpInIndex += framesIn;
4352 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004353 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004354 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004355 memcpy(dst, src, framesIn * mFrameSize);
4356 } else {
4357 int16_t *src16 = (int16_t *)src;
4358 int16_t *dst16 = (int16_t *)dst;
4359 if (mChannelCount == 1) {
4360 while (framesIn--) {
4361 *dst16++ = *src16;
4362 *dst16++ = *src16++;
4363 }
4364 } else {
4365 while (framesIn--) {
4366 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4367 src16 += 2;
4368 }
4369 }
4370 }
4371 }
4372 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004373 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004374 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004375 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004376 framesOut = 0;
4377 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004378 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004379 mRsmpInIndex = 0;
4380 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004381 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004382 ALOGE("Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004383 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004384 // Force input into standby so that it tries to
4385 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004386 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004387 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004388 }
Eric Laurenta553c252009-07-17 12:17:14 -07004389 mRsmpInIndex = mFrameCount;
4390 framesOut = 0;
4391 buffer.frameCount = 0;
4392 }
4393 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004394 }
4395 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004396 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004397
Eric Laurenta553c252009-07-17 12:17:14 -07004398 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4399 // alter output frame count as if we were expecting stereo samples
4400 if (mChannelCount == 1 && mReqChannelCount == 1) {
4401 framesOut >>= 1;
4402 }
4403 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4404 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4405 // are 32 bit aligned which should be always true.
4406 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004407 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004408 // the resampler always outputs stereo samples: do post stereo to mono conversion
4409 int16_t *src = (int16_t *)mRsmpOutBuffer;
4410 int16_t *dst = buffer.i16;
4411 while (framesOut--) {
4412 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4413 src += 2;
4414 }
4415 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004416 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004417 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004418
Eric Laurenta553c252009-07-17 12:17:14 -07004419 }
4420 mActiveTrack->releaseBuffer(&buffer);
4421 mActiveTrack->overflow();
4422 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004423 // client isn't retrieving buffers fast enough
4424 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004425 if (!mActiveTrack->setOverflow()) {
4426 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004427 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004428 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004429 lastWarning = now;
4430 }
4431 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004432 // Release the processor for a while before asking for a new buffer.
4433 // This will give the application more chance to read from the buffer and
4434 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004435 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004436 }
4437 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004438 // enable changes in effect chain
4439 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004440 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004441 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004442
Eric Laurenta553c252009-07-17 12:17:14 -07004443 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004444 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004445 }
Eric Laurenta553c252009-07-17 12:17:14 -07004446 mActiveTrack.clear();
4447
Eric Laurent49f02be2009-11-19 09:00:56 -08004448 mStartStopCond.broadcast();
4449
Eric Laurent6dbdc402011-07-22 09:04:31 -07004450 releaseWakeLock();
4451
Steve Block71f2cf12011-10-20 11:56:00 +01004452 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004453 return false;
4454}
4455
Eric Laurent464d5b32011-06-17 21:29:58 -07004456
4457sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4458 const sp<AudioFlinger::Client>& client,
4459 uint32_t sampleRate,
4460 int format,
4461 int channelMask,
4462 int frameCount,
4463 uint32_t flags,
4464 int sessionId,
4465 status_t *status)
4466{
4467 sp<RecordTrack> track;
4468 status_t lStatus;
4469
4470 lStatus = initCheck();
4471 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004472 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004473 goto Exit;
4474 }
4475
4476 { // scope for mLock
4477 Mutex::Autolock _l(mLock);
4478
4479 track = new RecordTrack(this, client, sampleRate,
4480 format, channelMask, frameCount, flags, sessionId);
4481
4482 if (track->getCblk() == NULL) {
4483 lStatus = NO_MEMORY;
4484 goto Exit;
4485 }
4486
4487 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004488 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4489 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004490 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004491 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4492 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004493 }
4494 lStatus = NO_ERROR;
4495
4496Exit:
4497 if (status) {
4498 *status = lStatus;
4499 }
4500 return track;
4501}
4502
Eric Laurenta553c252009-07-17 12:17:14 -07004503status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004504{
Steve Block71f2cf12011-10-20 11:56:00 +01004505 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004506 sp <ThreadBase> strongMe = this;
4507 status_t status = NO_ERROR;
4508 {
4509 AutoMutex lock(&mLock);
4510 if (mActiveTrack != 0) {
4511 if (recordTrack != mActiveTrack.get()) {
4512 status = -EBUSY;
4513 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004514 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004515 }
4516 return status;
4517 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004518
Eric Laurent49f02be2009-11-19 09:00:56 -08004519 recordTrack->mState = TrackBase::IDLE;
4520 mActiveTrack = recordTrack;
4521 mLock.unlock();
4522 status_t status = AudioSystem::startInput(mId);
4523 mLock.lock();
4524 if (status != NO_ERROR) {
4525 mActiveTrack.clear();
4526 return status;
4527 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004528 mRsmpInIndex = mFrameCount;
4529 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004530 if (mResampler != NULL) {
4531 mResampler->reset();
4532 }
4533 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004534 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004535 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004536 mWaitWorkCV.signal();
4537 // do not wait for mStartStopCond if exiting
4538 if (mExiting) {
4539 mActiveTrack.clear();
4540 status = INVALID_OPERATION;
4541 goto startError;
4542 }
4543 mStartStopCond.wait(mLock);
4544 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004545 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004546 status = BAD_VALUE;
4547 goto startError;
4548 }
Steve Block71f2cf12011-10-20 11:56:00 +01004549 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004550 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004551 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004552startError:
4553 AudioSystem::stopInput(mId);
4554 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004555}
4556
Eric Laurenta553c252009-07-17 12:17:14 -07004557void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004558 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004559 sp <ThreadBase> strongMe = this;
4560 {
4561 AutoMutex lock(&mLock);
4562 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4563 mActiveTrack->mState = TrackBase::PAUSING;
4564 // do not wait for mStartStopCond if exiting
4565 if (mExiting) {
4566 return;
4567 }
4568 mStartStopCond.wait(mLock);
4569 // if we have been restarted, recordTrack == mActiveTrack.get() here
4570 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4571 mLock.unlock();
4572 AudioSystem::stopInput(mId);
4573 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004574 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004575 }
4576 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004577 }
4578}
4579
Eric Laurenta553c252009-07-17 12:17:14 -07004580status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581{
4582 const size_t SIZE = 256;
4583 char buffer[SIZE];
4584 String8 result;
4585 pid_t pid = 0;
4586
Eric Laurent3fdb1262009-11-07 00:01:32 -08004587 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4588 result.append(buffer);
4589
4590 if (mActiveTrack != 0) {
4591 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004592 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004593 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004595
4596 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4597 result.append(buffer);
4598 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4599 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004600 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004601 result.append(buffer);
4602 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4603 result.append(buffer);
4604 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4605 result.append(buffer);
4606
4607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 } else {
4609 result.append("No record client\n");
4610 }
4611 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004612
4613 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004614 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 return NO_ERROR;
4617}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004618
Eric Laurenta553c252009-07-17 12:17:14 -07004619status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4620{
4621 size_t framesReq = buffer->frameCount;
4622 size_t framesReady = mFrameCount - mRsmpInIndex;
4623 int channelCount;
4624
4625 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004626 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004627 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004628 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004629 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004630 // Force input into standby so that it tries to
4631 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004632 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004633 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004634 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004635 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004636 buffer->frameCount = 0;
4637 return NOT_ENOUGH_DATA;
4638 }
4639 mRsmpInIndex = 0;
4640 framesReady = mFrameCount;
4641 }
4642
4643 if (framesReq > framesReady) {
4644 framesReq = framesReady;
4645 }
4646
4647 if (mChannelCount == 1 && mReqChannelCount == 2) {
4648 channelCount = 1;
4649 } else {
4650 channelCount = 2;
4651 }
4652 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4653 buffer->frameCount = framesReq;
4654 return NO_ERROR;
4655}
4656
4657void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4658{
4659 mRsmpInIndex += buffer->frameCount;
4660 buffer->frameCount = 0;
4661}
4662
4663bool AudioFlinger::RecordThread::checkForNewParameters_l()
4664{
4665 bool reconfig = false;
4666
Eric Laurent8fce46a2009-08-04 09:45:33 -07004667 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004668 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004669 String8 keyValuePair = mNewParameters[0];
4670 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004671 int value;
4672 int reqFormat = mFormat;
4673 int reqSamplingRate = mReqSampleRate;
4674 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004675
Eric Laurenta553c252009-07-17 12:17:14 -07004676 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4677 reqSamplingRate = value;
4678 reconfig = true;
4679 }
4680 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4681 reqFormat = value;
4682 reconfig = true;
4683 }
4684 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004685 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004686 reconfig = true;
4687 }
4688 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4689 // do not accept frame count changes if tracks are open as the track buffer
4690 // size depends on frame count and correct behavior would not be garantied
4691 // if frame count is changed after track creation
4692 if (mActiveTrack != 0) {
4693 status = INVALID_OPERATION;
4694 } else {
4695 reconfig = true;
4696 }
4697 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004698 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4699 // forward device change to effects that have requested to be
4700 // aware of attached audio device.
4701 for (size_t i = 0; i < mEffectChains.size(); i++) {
4702 mEffectChains[i]->setDevice_l(value);
4703 }
4704 // store input device and output device but do not forward output device to audio HAL.
4705 // Note that status is ignored by the caller for output device
4706 // (see AudioFlinger::setParameters()
4707 if (value & AUDIO_DEVICE_OUT_ALL) {
4708 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4709 status = BAD_VALUE;
4710 } else {
4711 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004712 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4713 if (mTrack != NULL) {
4714 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004715 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004716 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4717 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4718 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004719 }
4720 mDevice |= (uint32_t)value;
4721 }
Eric Laurenta553c252009-07-17 12:17:14 -07004722 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004723 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004724 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004725 mInput->stream->common.standby(&mInput->stream->common);
4726 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004727 }
4728 if (reconfig) {
4729 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004730 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004731 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004732 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4733 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004734 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004735 status = NO_ERROR;
4736 }
4737 if (status == NO_ERROR) {
4738 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004739 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004740 }
4741 }
4742 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004743
4744 mNewParameters.removeAt(0);
4745
Eric Laurenta553c252009-07-17 12:17:14 -07004746 mParamStatus = status;
4747 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004748 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4749 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004750 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004751 }
4752 return reconfig;
4753}
4754
4755String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4756{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004757 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004758 String8 out_s8 = String8();
4759
4760 Mutex::Autolock _l(mLock);
4761 if (initCheck() != NO_ERROR) {
4762 return out_s8;
4763 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004764
Dima Zavin31f188892011-04-18 16:57:27 -07004765 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004766 out_s8 = String8(s);
4767 free(s);
4768 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004769}
4770
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004771void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004772 AudioSystem::OutputDescriptor desc;
4773 void *param2 = 0;
4774
4775 switch (event) {
4776 case AudioSystem::INPUT_OPENED:
4777 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004778 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004779 desc.samplingRate = mSampleRate;
4780 desc.format = mFormat;
4781 desc.frameCount = mFrameCount;
4782 desc.latency = 0;
4783 param2 = &desc;
4784 break;
4785
4786 case AudioSystem::INPUT_CLOSED:
4787 default:
4788 break;
4789 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004790 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004791}
4792
4793void AudioFlinger::RecordThread::readInputParameters()
4794{
4795 if (mRsmpInBuffer) delete mRsmpInBuffer;
4796 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4797 if (mResampler) delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004798 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004799
Dima Zavin31f188892011-04-18 16:57:27 -07004800 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004801 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4802 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004803 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4804 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4805 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004806 mFrameCount = mInputBytes / mFrameSize;
4807 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4808
4809 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4810 {
4811 int channelCount;
4812 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4813 // stereo to mono post process as the resampler always outputs stereo.
4814 if (mChannelCount == 1 && mReqChannelCount == 2) {
4815 channelCount = 1;
4816 } else {
4817 channelCount = 2;
4818 }
4819 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4820 mResampler->setSampleRate(mSampleRate);
4821 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4822 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4823
4824 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4825 if (mChannelCount == 1 && mReqChannelCount == 1) {
4826 mFrameCount >>= 1;
4827 }
4828
4829 }
4830 mRsmpInIndex = mFrameCount;
4831}
4832
Eric Laurent47d0a922010-02-26 02:47:27 -08004833unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4834{
Eric Laurent828b9772011-08-07 16:32:26 -07004835 Mutex::Autolock _l(mLock);
4836 if (initCheck() != NO_ERROR) {
4837 return 0;
4838 }
4839
Dima Zavin31f188892011-04-18 16:57:27 -07004840 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004841}
4842
Eric Laurent464d5b32011-06-17 21:29:58 -07004843uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4844{
4845 Mutex::Autolock _l(mLock);
4846 uint32_t result = 0;
4847 if (getEffectChain_l(sessionId) != 0) {
4848 result = EFFECT_SESSION;
4849 }
4850
4851 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4852 result |= TRACK_SESSION;
4853 }
4854
4855 return result;
4856}
4857
Eric Laurent6639b552011-08-01 09:52:20 -07004858AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4859{
4860 Mutex::Autolock _l(mLock);
4861 return mTrack;
4862}
4863
Eric Laurent828b9772011-08-07 16:32:26 -07004864AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4865{
4866 Mutex::Autolock _l(mLock);
4867 return mInput;
4868}
4869
4870AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4871{
4872 Mutex::Autolock _l(mLock);
4873 AudioStreamIn *input = mInput;
4874 mInput = NULL;
4875 return input;
4876}
4877
4878// this method must always be called either with ThreadBase mLock held or inside the thread loop
4879audio_stream_t* AudioFlinger::RecordThread::stream()
4880{
4881 if (mInput == NULL) {
4882 return NULL;
4883 }
4884 return &mInput->stream->common;
4885}
4886
4887
Eric Laurenta553c252009-07-17 12:17:14 -07004888// ----------------------------------------------------------------------------
4889
Eric Laurentddb78e72009-07-28 08:44:33 -07004890int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004891 uint32_t *pSamplingRate,
4892 uint32_t *pFormat,
4893 uint32_t *pChannels,
4894 uint32_t *pLatencyMs,
4895 uint32_t flags)
4896{
4897 status_t status;
4898 PlaybackThread *thread = NULL;
4899 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4900 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4901 uint32_t format = pFormat ? *pFormat : 0;
4902 uint32_t channels = pChannels ? *pChannels : 0;
4903 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004904 audio_stream_out_t *outStream;
4905 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004906
Steve Block71f2cf12011-10-20 11:56:00 +01004907 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004908 pDevices ? *pDevices : 0,
4909 samplingRate,
4910 format,
4911 channels,
4912 flags);
4913
4914 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004915 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004916 }
Dima Zavin31f188892011-04-18 16:57:27 -07004917
Eric Laurenta553c252009-07-17 12:17:14 -07004918 Mutex::Autolock _l(mLock);
4919
Dima Zavin31f188892011-04-18 16:57:27 -07004920 outHwDev = findSuitableHwDev_l(*pDevices);
4921 if (outHwDev == NULL)
4922 return 0;
4923
4924 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4925 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004926 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004927 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004928 samplingRate,
4929 format,
4930 channels,
4931 status);
4932
4933 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004934 if (outStream != NULL) {
4935 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004936 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004937
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004938 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4939 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4940 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004941 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004942 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004943 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004944 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004945 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004946 }
Eric Laurent65b65452010-06-01 23:49:17 -07004947 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004948
4949 if (pSamplingRate) *pSamplingRate = samplingRate;
4950 if (pFormat) *pFormat = format;
4951 if (pChannels) *pChannels = channels;
4952 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004953
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004954 // notify client processes of the new output creation
4955 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004956 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004957 }
4958
Eric Laurent9cc489a2009-12-05 05:20:01 -08004959 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004960}
4961
Eric Laurentddb78e72009-07-28 08:44:33 -07004962int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004963{
4964 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004965 MixerThread *thread1 = checkMixerThread_l(output1);
4966 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004967
Eric Laurentddb78e72009-07-28 08:44:33 -07004968 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004969 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004970 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004971 }
4972
Eric Laurent464d5b32011-06-17 21:29:58 -07004973 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004974 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004975 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004976 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004977 // notify client processes of the new output creation
4978 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004979 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004980}
4981
Eric Laurentddb78e72009-07-28 08:44:33 -07004982status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004983{
Eric Laurent49018a52009-08-04 08:37:05 -07004984 // keep strong reference on the playback thread so that
4985 // it is not destroyed while exit() is executed
4986 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004987 {
4988 Mutex::Autolock _l(mLock);
4989 thread = checkPlaybackThread_l(output);
4990 if (thread == NULL) {
4991 return BAD_VALUE;
4992 }
4993
Steve Block71f2cf12011-10-20 11:56:00 +01004994 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004995
Eric Laurent464d5b32011-06-17 21:29:58 -07004996 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004997 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004998 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004999 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005000 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005001 }
5002 }
5003 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07005004 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005005 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005006 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005007 }
5008 thread->exit();
5009
Eric Laurent464d5b32011-06-17 21:29:58 -07005010 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005011 AudioStreamOut *out = thread->clearOutput();
5012 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005013 out->hwDev->close_output_stream(out->hwDev, out->stream);
5014 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005015 }
Eric Laurenta553c252009-07-17 12:17:14 -07005016 return NO_ERROR;
5017}
5018
Eric Laurentddb78e72009-07-28 08:44:33 -07005019status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005020{
5021 Mutex::Autolock _l(mLock);
5022 PlaybackThread *thread = checkPlaybackThread_l(output);
5023
5024 if (thread == NULL) {
5025 return BAD_VALUE;
5026 }
5027
Steve Block71f2cf12011-10-20 11:56:00 +01005028 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005029 thread->suspend();
5030
5031 return NO_ERROR;
5032}
5033
Eric Laurentddb78e72009-07-28 08:44:33 -07005034status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005035{
5036 Mutex::Autolock _l(mLock);
5037 PlaybackThread *thread = checkPlaybackThread_l(output);
5038
5039 if (thread == NULL) {
5040 return BAD_VALUE;
5041 }
5042
Steve Block71f2cf12011-10-20 11:56:00 +01005043 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005044
5045 thread->restore();
5046
5047 return NO_ERROR;
5048}
5049
Eric Laurentddb78e72009-07-28 08:44:33 -07005050int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005051 uint32_t *pSamplingRate,
5052 uint32_t *pFormat,
5053 uint32_t *pChannels,
5054 uint32_t acoustics)
5055{
5056 status_t status;
5057 RecordThread *thread = NULL;
5058 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5059 uint32_t format = pFormat ? *pFormat : 0;
5060 uint32_t channels = pChannels ? *pChannels : 0;
5061 uint32_t reqSamplingRate = samplingRate;
5062 uint32_t reqFormat = format;
5063 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005064 audio_stream_in_t *inStream;
5065 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005066
5067 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005068 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005069 }
Dima Zavin31f188892011-04-18 16:57:27 -07005070
Eric Laurenta553c252009-07-17 12:17:14 -07005071 Mutex::Autolock _l(mLock);
5072
Dima Zavin31f188892011-04-18 16:57:27 -07005073 inHwDev = findSuitableHwDev_l(*pDevices);
5074 if (inHwDev == NULL)
5075 return 0;
5076
5077 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5078 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005079 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005080 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005081 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005082 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005083 samplingRate,
5084 format,
5085 channels,
5086 acoustics,
5087 status);
5088
5089 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5090 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5091 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005092 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005093 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005094 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005095 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005096 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005097 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5098 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005099 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005100 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005101 }
5102
Dima Zavin31f188892011-04-18 16:57:27 -07005103 if (inStream != NULL) {
5104 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5105
Eric Laurent464d5b32011-06-17 21:29:58 -07005106 int id = nextUniqueId();
5107 // Start record thread
5108 // RecorThread require both input and output device indication to forward to audio
5109 // pre processing modules
5110 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5111 thread = new RecordThread(this,
5112 input,
5113 reqSamplingRate,
5114 reqChannels,
5115 id,
5116 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005117 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005118 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005119 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5120 if (pFormat) *pFormat = format;
5121 if (pChannels) *pChannels = reqChannels;
5122
Dima Zavin31f188892011-04-18 16:57:27 -07005123 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08005124
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005125 // notify client processes of the new input creation
5126 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005127 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005128 }
5129
Eric Laurent9cc489a2009-12-05 05:20:01 -08005130 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005131}
5132
Eric Laurentddb78e72009-07-28 08:44:33 -07005133status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005134{
Eric Laurent49018a52009-08-04 08:37:05 -07005135 // keep strong reference on the record thread so that
5136 // it is not destroyed while exit() is executed
5137 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005138 {
5139 Mutex::Autolock _l(mLock);
5140 thread = checkRecordThread_l(input);
5141 if (thread == NULL) {
5142 return BAD_VALUE;
5143 }
5144
Steve Block71f2cf12011-10-20 11:56:00 +01005145 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005146 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005147 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005148 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005149 }
5150 thread->exit();
5151
Eric Laurent828b9772011-08-07 16:32:26 -07005152 AudioStreamIn *in = thread->clearInput();
5153 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005154 in->hwDev->close_input_stream(in->hwDev, in->stream);
5155 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005156
Eric Laurenta553c252009-07-17 12:17:14 -07005157 return NO_ERROR;
5158}
5159
Eric Laurentddb78e72009-07-28 08:44:33 -07005160status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005161{
5162 Mutex::Autolock _l(mLock);
5163 MixerThread *dstThread = checkMixerThread_l(output);
5164 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005165 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005166 return BAD_VALUE;
5167 }
5168
Steve Block71f2cf12011-10-20 11:56:00 +01005169 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005170 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005171
Eric Laurent05ce0942011-08-30 10:18:54 -07005172 dstThread->setStreamValid(stream, true);
5173
Eric Laurenta553c252009-07-17 12:17:14 -07005174 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005175 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005176 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005177 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005178 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005179 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005180 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005181 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005182 }
Eric Laurentd069f322009-09-01 05:56:26 -07005183
Eric Laurenta553c252009-07-17 12:17:14 -07005184 return NO_ERROR;
5185}
5186
Eric Laurent65b65452010-06-01 23:49:17 -07005187
5188int AudioFlinger::newAudioSessionId()
5189{
Eric Laurent464d5b32011-06-17 21:29:58 -07005190 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005191}
5192
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005193void AudioFlinger::acquireAudioSessionId(int audioSession)
5194{
5195 Mutex::Autolock _l(mLock);
5196 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005197 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005198 int num = mAudioSessionRefs.size();
5199 for (int i = 0; i< num; i++) {
5200 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5201 if (ref->sessionid == audioSession && ref->pid == caller) {
5202 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005203 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005204 return;
5205 }
5206 }
5207 AudioSessionRef *ref = new AudioSessionRef();
5208 ref->sessionid = audioSession;
5209 ref->pid = caller;
5210 ref->cnt = 1;
5211 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005212 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005213}
5214
5215void AudioFlinger::releaseAudioSessionId(int audioSession)
5216{
5217 Mutex::Autolock _l(mLock);
5218 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005219 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005220 int num = mAudioSessionRefs.size();
5221 for (int i = 0; i< num; i++) {
5222 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5223 if (ref->sessionid == audioSession && ref->pid == caller) {
5224 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005225 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005226 if (ref->cnt == 0) {
5227 mAudioSessionRefs.removeAt(i);
5228 delete ref;
5229 purgeStaleEffects_l();
5230 }
5231 return;
5232 }
5233 }
Steve Block8564c8d2012-01-05 23:22:43 +00005234 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005235}
5236
5237void AudioFlinger::purgeStaleEffects_l() {
5238
Steve Block71f2cf12011-10-20 11:56:00 +01005239 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005240
5241 Vector< sp<EffectChain> > chains;
5242
5243 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5244 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5245 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5246 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005247 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5248 chains.push(ec);
5249 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005250 }
5251 }
5252 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5253 sp<RecordThread> t = mRecordThreads.valueAt(i);
5254 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5255 sp<EffectChain> ec = t->mEffectChains[j];
5256 chains.push(ec);
5257 }
5258 }
5259
5260 for (size_t i = 0; i < chains.size(); i++) {
5261 sp<EffectChain> ec = chains[i];
5262 int sessionid = ec->sessionId();
5263 sp<ThreadBase> t = ec->mThread.promote();
5264 if (t == 0) {
5265 continue;
5266 }
5267 size_t numsessionrefs = mAudioSessionRefs.size();
5268 bool found = false;
5269 for (size_t k = 0; k < numsessionrefs; k++) {
5270 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5271 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005272 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005273 sessionid, ref->pid, ref->cnt);
5274 found = true;
5275 break;
5276 }
5277 }
5278 if (!found) {
5279 // remove all effects from the chain
5280 while (ec->mEffects.size()) {
5281 sp<EffectModule> effect = ec->mEffects[0];
5282 effect->unPin();
5283 Mutex::Autolock _l (t->mLock);
5284 t->removeEffect_l(effect);
5285 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5286 sp<EffectHandle> handle = effect->mHandles[j].promote();
5287 if (handle != 0) {
5288 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005289 if (handle->mHasControl && handle->mEnabled) {
5290 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5291 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005292 }
5293 }
5294 AudioSystem::unregisterEffect(effect->id());
5295 }
5296 }
5297 }
5298 return;
5299}
5300
Eric Laurenta553c252009-07-17 12:17:14 -07005301// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005302AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005303{
5304 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005305 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5306 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005307 }
Eric Laurenta553c252009-07-17 12:17:14 -07005308 return thread;
5309}
5310
5311// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005312AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005313{
5314 PlaybackThread *thread = checkPlaybackThread_l(output);
5315 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005316 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005317 thread = NULL;
5318 }
5319 }
5320 return (MixerThread *)thread;
5321}
5322
5323// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005324AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005325{
5326 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005327 if (mRecordThreads.indexOfKey(input) >= 0) {
5328 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005329 }
Eric Laurenta553c252009-07-17 12:17:14 -07005330 return thread;
5331}
5332
Eric Laurent464d5b32011-06-17 21:29:58 -07005333uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005334{
Eric Laurent464d5b32011-06-17 21:29:58 -07005335 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005336}
5337
Eric Laurent464d5b32011-06-17 21:29:58 -07005338AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5339{
5340 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5341 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005342 AudioStreamOut *output = thread->getOutput();
5343 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005344 return thread;
5345 }
5346 }
5347 return NULL;
5348}
5349
5350uint32_t AudioFlinger::primaryOutputDevice_l()
5351{
5352 PlaybackThread *thread = primaryPlaybackThread_l();
5353
5354 if (thread == NULL) {
5355 return 0;
5356 }
5357
5358 return thread->device();
5359}
5360
5361
Eric Laurent65b65452010-06-01 23:49:17 -07005362// ----------------------------------------------------------------------------
5363// Effect management
5364// ----------------------------------------------------------------------------
5365
5366
Eric Laurent65b65452010-06-01 23:49:17 -07005367status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5368{
5369 Mutex::Autolock _l(mLock);
5370 return EffectQueryNumberEffects(numEffects);
5371}
5372
Eric Laurent53334cd2010-06-23 17:38:20 -07005373status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005374{
5375 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005376 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005377}
5378
5379status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5380{
5381 Mutex::Autolock _l(mLock);
5382 return EffectGetDescriptor(pUuid, descriptor);
5383}
5384
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005385
Eric Laurent65b65452010-06-01 23:49:17 -07005386sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5387 effect_descriptor_t *pDesc,
5388 const sp<IEffectClient>& effectClient,
5389 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005390 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005391 int sessionId,
5392 status_t *status,
5393 int *id,
5394 int *enabled)
5395{
5396 status_t lStatus = NO_ERROR;
5397 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005398 effect_descriptor_t desc;
5399 sp<Client> client;
5400 wp<Client> wclient;
5401
Steve Block71f2cf12011-10-20 11:56:00 +01005402 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005403 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005404
5405 if (pDesc == NULL) {
5406 lStatus = BAD_VALUE;
5407 goto Exit;
5408 }
5409
Eric Laurent98c92592010-09-23 16:10:16 -07005410 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005411 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005412 lStatus = PERMISSION_DENIED;
5413 goto Exit;
5414 }
5415
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005416 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005417 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005418 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005419 lStatus = PERMISSION_DENIED;
5420 goto Exit;
5421 }
5422
Eric Laurent464d5b32011-06-17 21:29:58 -07005423 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005424 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005425 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005426 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005427 lStatus = BAD_VALUE;
5428 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005429 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005430 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005431 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005432 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005433 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005434 }
5435 }
5436
Eric Laurent65b65452010-06-01 23:49:17 -07005437 {
5438 Mutex::Autolock _l(mLock);
5439
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005440
Eric Laurent65b65452010-06-01 23:49:17 -07005441 if (!EffectIsNullUuid(&pDesc->uuid)) {
5442 // if uuid is specified, request effect descriptor
5443 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5444 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005445 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005446 goto Exit;
5447 }
5448 } else {
5449 // if uuid is not specified, look for an available implementation
5450 // of the required type in effect factory
5451 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005452 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005453 lStatus = BAD_VALUE;
5454 goto Exit;
5455 }
5456 uint32_t numEffects = 0;
5457 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005458 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005459 bool found = false;
5460
5461 lStatus = EffectQueryNumberEffects(&numEffects);
5462 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005463 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005464 goto Exit;
5465 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005466 for (uint32_t i = 0; i < numEffects; i++) {
5467 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005468 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005469 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005470 continue;
5471 }
5472 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5473 // If matching type found save effect descriptor. If the session is
5474 // 0 and the effect is not auxiliary, continue enumeration in case
5475 // an auxiliary version of this effect type is available
5476 found = true;
5477 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005478 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005479 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5480 break;
5481 }
5482 }
5483 }
5484 if (!found) {
5485 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005486 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005487 goto Exit;
5488 }
5489 // For same effect type, chose auxiliary version over insert version if
5490 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005491 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005492 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5493 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5494 }
5495 }
5496
5497 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005498 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005499 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5500 lStatus = INVALID_OPERATION;
5501 goto Exit;
5502 }
5503
Eric Laurentf82fccd2011-07-27 19:49:51 -07005504 // check recording permission for visualizer
5505 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5506 !recordingAllowed()) {
5507 lStatus = PERMISSION_DENIED;
5508 goto Exit;
5509 }
5510
Eric Laurent65b65452010-06-01 23:49:17 -07005511 // return effect descriptor
5512 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5513
5514 // If output is not specified try to find a matching audio session ID in one of the
5515 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005516 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5517 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005518 // Note: io is never 0 when creating an effect on an input
5519 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005520 // look for the thread where the specified audio session is present
5521 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5522 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005523 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005524 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005525 }
Eric Laurent65b65452010-06-01 23:49:17 -07005526 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005527 if (io == 0) {
5528 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5529 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5530 io = mRecordThreads.keyAt(i);
5531 break;
5532 }
5533 }
5534 }
Eric Laurent98c92592010-09-23 16:10:16 -07005535 // If no output thread contains the requested session ID, default to
5536 // first output. The effect chain will be moved to the correct output
5537 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005538 if (io == 0 && mPlaybackThreads.size()) {
5539 io = mPlaybackThreads.keyAt(0);
5540 }
Steve Block71f2cf12011-10-20 11:56:00 +01005541 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005542 }
5543 ThreadBase *thread = checkRecordThread_l(io);
5544 if (thread == NULL) {
5545 thread = checkPlaybackThread_l(io);
5546 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005547 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005548 lStatus = BAD_VALUE;
5549 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005550 }
Eric Laurent65b65452010-06-01 23:49:17 -07005551 }
Eric Laurent98c92592010-09-23 16:10:16 -07005552
Eric Laurent65b65452010-06-01 23:49:17 -07005553 wclient = mClients.valueFor(pid);
5554
5555 if (wclient != NULL) {
5556 client = wclient.promote();
5557 } else {
5558 client = new Client(this, pid);
5559 mClients.add(pid, client);
5560 }
5561
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005562 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005563 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5564 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005565 if (handle != 0 && id != NULL) {
5566 *id = handle->id();
5567 }
5568 }
5569
5570Exit:
5571 if(status) {
5572 *status = lStatus;
5573 }
5574 return handle;
5575}
5576
Eric Laurentf82fccd2011-07-27 19:49:51 -07005577status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005578{
Steve Block71f2cf12011-10-20 11:56:00 +01005579 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005580 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005581 Mutex::Autolock _l(mLock);
5582 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00005583 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005584 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005585 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005586 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5587 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005588 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005589 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005590 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005591 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5592 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005593 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005594 return BAD_VALUE;
5595 }
5596
5597 Mutex::Autolock _dl(dstThread->mLock);
5598 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005599 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005600
Eric Laurent53334cd2010-06-23 17:38:20 -07005601 return NO_ERROR;
5602}
5603
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005604// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005605status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005606 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005607 AudioFlinger::PlaybackThread *dstThread,
5608 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005609{
Steve Block71f2cf12011-10-20 11:56:00 +01005610 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005611 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612
Eric Laurentf82fccd2011-07-27 19:49:51 -07005613 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005614 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005615 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005616 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005617 return INVALID_OPERATION;
5618 }
5619
Eric Laurent493941b2010-07-28 01:32:47 -07005620 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005621 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005622 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005623 // removed.
5624 srcThread->removeEffectChain_l(chain);
5625
5626 // transfer all effects one by one so that new effect chain is created on new thread with
5627 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005628 int dstOutput = dstThread->id();
5629 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005630 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005631 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5632 while (effect != 0) {
5633 srcThread->removeEffect_l(effect);
5634 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005635 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5636 if (effect->state() == EffectModule::ACTIVE ||
5637 effect->state() == EffectModule::STOPPING) {
5638 effect->start();
5639 }
Eric Laurent493941b2010-07-28 01:32:47 -07005640 // if the move request is not received from audio policy manager, the effect must be
5641 // re-registered with the new strategy and output
5642 if (dstChain == 0) {
5643 dstChain = effect->chain().promote();
5644 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005645 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07005646 srcThread->addEffect_l(effect);
5647 return NO_INIT;
5648 }
5649 strategy = dstChain->strategy();
5650 }
5651 if (reRegister) {
5652 AudioSystem::unregisterEffect(effect->id());
5653 AudioSystem::registerEffect(&effect->desc(),
5654 dstOutput,
5655 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005656 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005657 effect->id());
5658 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005659 effect = chain->getEffectFromId_l(0);
5660 }
5661
5662 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005663}
5664
Eric Laurent464d5b32011-06-17 21:29:58 -07005665
Eric Laurent65b65452010-06-01 23:49:17 -07005666// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005667sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005668 const sp<AudioFlinger::Client>& client,
5669 const sp<IEffectClient>& effectClient,
5670 int32_t priority,
5671 int sessionId,
5672 effect_descriptor_t *desc,
5673 int *enabled,
5674 status_t *status
5675 )
5676{
5677 sp<EffectModule> effect;
5678 sp<EffectHandle> handle;
5679 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005680 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005681 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005682 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005683 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005684
Eric Laurent464d5b32011-06-17 21:29:58 -07005685 lStatus = initCheck();
5686 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00005687 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005688 goto Exit;
5689 }
5690
5691 // Do not allow effects with session ID 0 on direct output or duplicating threads
5692 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005693 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00005694 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005695 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005696 lStatus = BAD_VALUE;
5697 goto Exit;
5698 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005699 // Only Pre processor effects are allowed on input threads and only on input threads
5700 if ((mType == RECORD &&
5701 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5702 (mType != RECORD &&
5703 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005704 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005705 desc->name, desc->flags, mType);
5706 lStatus = BAD_VALUE;
5707 goto Exit;
5708 }
Eric Laurent65b65452010-06-01 23:49:17 -07005709
Steve Block71f2cf12011-10-20 11:56:00 +01005710 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005711
5712 { // scope for mLock
5713 Mutex::Autolock _l(mLock);
5714
5715 // check for existing effect chain with the requested audio session
5716 chain = getEffectChain_l(sessionId);
5717 if (chain == 0) {
5718 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005719 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005720 chain = new EffectChain(this, sessionId);
5721 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005722 chain->setStrategy(getStrategyForSession_l(sessionId));
5723 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005724 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005725 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005726 }
5727
Steve Block71f2cf12011-10-20 11:56:00 +01005728 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005729
5730 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005731 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005732 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005733 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005734 if (lStatus != NO_ERROR) {
5735 goto Exit;
5736 }
5737 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005738 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005739 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005740 lStatus = effect->status();
5741 if (lStatus != NO_ERROR) {
5742 goto Exit;
5743 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005744 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005745 if (lStatus != NO_ERROR) {
5746 goto Exit;
5747 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005748 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005749
5750 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005751 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005752 }
5753 // create effect handle and connect it to effect module
5754 handle = new EffectHandle(effect, client, effectClient, priority);
5755 lStatus = effect->addHandle(handle);
5756 if (enabled) {
5757 *enabled = (int)effect->isEnabled();
5758 }
5759 }
5760
5761Exit:
5762 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005763 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005764 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005765 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005766 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005767 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005768 AudioSystem::unregisterEffect(effect->id());
5769 }
5770 if (chainCreated) {
5771 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005772 }
Eric Laurent65b65452010-06-01 23:49:17 -07005773 handle.clear();
5774 }
5775
5776 if(status) {
5777 *status = lStatus;
5778 }
5779 return handle;
5780}
5781
Eric Laurent464d5b32011-06-17 21:29:58 -07005782sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5783{
5784 sp<EffectModule> effect;
5785
5786 sp<EffectChain> chain = getEffectChain_l(sessionId);
5787 if (chain != 0) {
5788 effect = chain->getEffectFromId_l(effectId);
5789 }
5790 return effect;
5791}
5792
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005793// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5794// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005795status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005796{
5797 // check for existing effect chain with the requested audio session
5798 int sessionId = effect->sessionId();
5799 sp<EffectChain> chain = getEffectChain_l(sessionId);
5800 bool chainCreated = false;
5801
5802 if (chain == 0) {
5803 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005804 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005805 chain = new EffectChain(this, sessionId);
5806 addEffectChain_l(chain);
5807 chain->setStrategy(getStrategyForSession_l(sessionId));
5808 chainCreated = true;
5809 }
Steve Block71f2cf12011-10-20 11:56:00 +01005810 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005811
5812 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005813 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005814 this, effect->desc().name, chain.get());
5815 return BAD_VALUE;
5816 }
5817
5818 status_t status = chain->addEffect_l(effect);
5819 if (status != NO_ERROR) {
5820 if (chainCreated) {
5821 removeEffectChain_l(chain);
5822 }
5823 return status;
5824 }
5825
5826 effect->setDevice(mDevice);
5827 effect->setMode(mAudioFlinger->getMode());
5828 return NO_ERROR;
5829}
5830
Eric Laurent464d5b32011-06-17 21:29:58 -07005831void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005832
Steve Block71f2cf12011-10-20 11:56:00 +01005833 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005834 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005835 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5836 detachAuxEffect_l(effect->id());
5837 }
5838
5839 sp<EffectChain> chain = effect->chain().promote();
5840 if (chain != 0) {
5841 // remove effect chain if removing last effect
5842 if (chain->removeEffect_l(effect) == 0) {
5843 removeEffectChain_l(chain);
5844 }
5845 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00005846 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005847 }
5848}
5849
Eric Laurent464d5b32011-06-17 21:29:58 -07005850void AudioFlinger::ThreadBase::lockEffectChains_l(
5851 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5852{
5853 effectChains = mEffectChains;
5854 for (size_t i = 0; i < mEffectChains.size(); i++) {
5855 mEffectChains[i]->lock();
5856 }
5857}
5858
5859void AudioFlinger::ThreadBase::unlockEffectChains(
5860 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5861{
5862 for (size_t i = 0; i < effectChains.size(); i++) {
5863 effectChains[i]->unlock();
5864 }
5865}
5866
5867sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5868{
5869 Mutex::Autolock _l(mLock);
5870 return getEffectChain_l(sessionId);
5871}
5872
5873sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5874{
5875 sp<EffectChain> chain;
5876
5877 size_t size = mEffectChains.size();
5878 for (size_t i = 0; i < size; i++) {
5879 if (mEffectChains[i]->sessionId() == sessionId) {
5880 chain = mEffectChains[i];
5881 break;
5882 }
5883 }
5884 return chain;
5885}
5886
5887void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5888{
5889 Mutex::Autolock _l(mLock);
5890 size_t size = mEffectChains.size();
5891 for (size_t i = 0; i < size; i++) {
5892 mEffectChains[i]->setMode_l(mode);
5893 }
5894}
5895
5896void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005897 const wp<EffectHandle>& handle,
5898 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005899
Eric Laurent53334cd2010-06-23 17:38:20 -07005900 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005901 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005902 // delete the effect module if removing last handle on it
5903 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005904 if (!effect->isPinned() || unpiniflast) {
5905 removeEffect_l(effect);
5906 AudioSystem::unregisterEffect(effect->id());
5907 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005908 }
5909}
5910
Eric Laurent65b65452010-06-01 23:49:17 -07005911status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5912{
5913 int session = chain->sessionId();
5914 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005915 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005916
Steve Block71f2cf12011-10-20 11:56:00 +01005917 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005918 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005919 // Only one effect chain can be present in direct output thread and it uses
5920 // the mix buffer as input
5921 if (mType != DIRECT) {
5922 size_t numSamples = mFrameCount * mChannelCount;
5923 buffer = new int16_t[numSamples];
5924 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005925 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005926 ownsBuffer = true;
5927 }
Eric Laurent65b65452010-06-01 23:49:17 -07005928
Eric Laurent53334cd2010-06-23 17:38:20 -07005929 // Attach all tracks with same session ID to this chain.
5930 for (size_t i = 0; i < mTracks.size(); ++i) {
5931 sp<Track> track = mTracks[i];
5932 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005933 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005934 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005935 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005936 }
5937 }
5938
5939 // indicate all active tracks in the chain
5940 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5941 sp<Track> track = mActiveTracks[i].promote();
5942 if (track == 0) continue;
5943 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005944 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005945 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005946 }
Eric Laurent65b65452010-06-01 23:49:17 -07005947 }
5948 }
5949
Eric Laurent53334cd2010-06-23 17:38:20 -07005950 chain->setInBuffer(buffer, ownsBuffer);
5951 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005952 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005953 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005954 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5955 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005956 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005957 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5958 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005959 // Effect chain for other sessions are inserted at beginning of effect
5960 // chains list to be processed before output mix effects. Relative order between other
5961 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005962 size_t size = mEffectChains.size();
5963 size_t i = 0;
5964 for (i = 0; i < size; i++) {
5965 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005966 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005967 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005968 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005969
5970 return NO_ERROR;
5971}
5972
5973size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5974{
5975 int session = chain->sessionId();
5976
Steve Block71f2cf12011-10-20 11:56:00 +01005977 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005978
5979 for (size_t i = 0; i < mEffectChains.size(); i++) {
5980 if (chain == mEffectChains[i]) {
5981 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005982 // detach all active tracks from the chain
5983 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5984 sp<Track> track = mActiveTracks[i].promote();
5985 if (track == 0) continue;
5986 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005987 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005988 chain.get(), session);
5989 chain->decActiveTrackCnt();
5990 }
5991 }
5992
Eric Laurent65b65452010-06-01 23:49:17 -07005993 // detach all tracks with same session ID from this chain
5994 for (size_t i = 0; i < mTracks.size(); ++i) {
5995 sp<Track> track = mTracks[i];
5996 if (session == track->sessionId()) {
5997 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005998 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005999 }
6000 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006001 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006002 }
6003 }
6004 return mEffectChains.size();
6005}
6006
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006007status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6008 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006009{
6010 Mutex::Autolock _l(mLock);
6011 return attachAuxEffect_l(track, EffectId);
6012}
6013
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006014status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6015 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006016{
6017 status_t status = NO_ERROR;
6018
6019 if (EffectId == 0) {
6020 track->setAuxBuffer(0, NULL);
6021 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006022 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6023 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006024 if (effect != 0) {
6025 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6026 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6027 } else {
6028 status = INVALID_OPERATION;
6029 }
6030 } else {
6031 status = BAD_VALUE;
6032 }
6033 }
6034 return status;
6035}
6036
6037void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6038{
6039 for (size_t i = 0; i < mTracks.size(); ++i) {
6040 sp<Track> track = mTracks[i];
6041 if (track->auxEffectId() == effectId) {
6042 attachAuxEffect_l(track, 0);
6043 }
6044 }
6045}
6046
Eric Laurent464d5b32011-06-17 21:29:58 -07006047status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6048{
6049 // only one chain per input thread
6050 if (mEffectChains.size() != 0) {
6051 return INVALID_OPERATION;
6052 }
Steve Block71f2cf12011-10-20 11:56:00 +01006053 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006054
6055 chain->setInBuffer(NULL);
6056 chain->setOutBuffer(NULL);
6057
Eric Laurentf82fccd2011-07-27 19:49:51 -07006058 checkSuspendOnAddEffectChain_l(chain);
6059
Eric Laurent464d5b32011-06-17 21:29:58 -07006060 mEffectChains.add(chain);
6061
6062 return NO_ERROR;
6063}
6064
6065size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6066{
Steve Block71f2cf12011-10-20 11:56:00 +01006067 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006068 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006069 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6070 chain.get(), mEffectChains.size(), this);
6071 if (mEffectChains.size() == 1) {
6072 mEffectChains.removeAt(0);
6073 }
6074 return 0;
6075}
6076
Eric Laurent65b65452010-06-01 23:49:17 -07006077// ----------------------------------------------------------------------------
6078// EffectModule implementation
6079// ----------------------------------------------------------------------------
6080
6081#undef LOG_TAG
6082#define LOG_TAG "AudioFlinger::EffectModule"
6083
6084AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6085 const wp<AudioFlinger::EffectChain>& chain,
6086 effect_descriptor_t *desc,
6087 int id,
6088 int sessionId)
6089 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006090 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006091{
Steve Block71f2cf12011-10-20 11:56:00 +01006092 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006093 int lStatus;
6094 sp<ThreadBase> thread = mThread.promote();
6095 if (thread == 0) {
6096 return;
6097 }
Eric Laurent65b65452010-06-01 23:49:17 -07006098
6099 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6100
6101 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006102 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006103
Eric Laurent65b65452010-06-01 23:49:17 -07006104 if (mStatus != NO_ERROR) {
6105 return;
6106 }
6107 lStatus = init();
6108 if (lStatus < 0) {
6109 mStatus = lStatus;
6110 goto Error;
6111 }
6112
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006113 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6114 mPinned = true;
6115 }
Steve Block71f2cf12011-10-20 11:56:00 +01006116 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006117 return;
6118Error:
6119 EffectRelease(mEffectInterface);
6120 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006121 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006122}
6123
6124AudioFlinger::EffectModule::~EffectModule()
6125{
Steve Block71f2cf12011-10-20 11:56:00 +01006126 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006127 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006128 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6129 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6130 sp<ThreadBase> thread = mThread.promote();
6131 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006132 audio_stream_t *stream = thread->stream();
6133 if (stream != NULL) {
6134 stream->remove_audio_effect(stream, mEffectInterface);
6135 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006136 }
6137 }
Eric Laurent65b65452010-06-01 23:49:17 -07006138 // release effect engine
6139 EffectRelease(mEffectInterface);
6140 }
6141}
6142
6143status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6144{
6145 status_t status;
6146
6147 Mutex::Autolock _l(mLock);
6148 // First handle in mHandles has highest priority and controls the effect module
6149 int priority = handle->priority();
6150 size_t size = mHandles.size();
6151 sp<EffectHandle> h;
6152 size_t i;
6153 for (i = 0; i < size; i++) {
6154 h = mHandles[i].promote();
6155 if (h == 0) continue;
6156 if (h->priority() <= priority) break;
6157 }
6158 // if inserted in first place, move effect control from previous owner to this handle
6159 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006160 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006161 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006162 enabled = h->enabled();
6163 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006164 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006165 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006166 status = NO_ERROR;
6167 } else {
6168 status = ALREADY_EXISTS;
6169 }
Steve Block71f2cf12011-10-20 11:56:00 +01006170 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006171 mHandles.insertAt(handle, i);
6172 return status;
6173}
6174
6175size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6176{
6177 Mutex::Autolock _l(mLock);
6178 size_t size = mHandles.size();
6179 size_t i;
6180 for (i = 0; i < size; i++) {
6181 if (mHandles[i] == handle) break;
6182 }
6183 if (i == size) {
6184 return size;
6185 }
Steve Block71f2cf12011-10-20 11:56:00 +01006186 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006187
6188 bool enabled = false;
6189 EffectHandle *hdl = handle.unsafe_get();
6190 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006191 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006192 enabled = hdl->enabled();
6193 }
Eric Laurent65b65452010-06-01 23:49:17 -07006194 mHandles.removeAt(i);
6195 size = mHandles.size();
6196 // if removed from first place, move effect control from this handle to next in line
6197 if (i == 0 && size != 0) {
6198 sp<EffectHandle> h = mHandles[0].promote();
6199 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006200 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006201 }
6202 }
6203
Eric Laurent21b5c472011-07-26 20:54:46 -07006204 // Prevent calls to process() and other functions on effect interface from now on.
6205 // The effect engine will be released by the destructor when the last strong reference on
6206 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006207 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006208 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006209 }
6210
Eric Laurent65b65452010-06-01 23:49:17 -07006211 return size;
6212}
6213
Eric Laurentf82fccd2011-07-27 19:49:51 -07006214sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6215{
6216 Mutex::Autolock _l(mLock);
6217 sp<EffectHandle> handle;
6218 if (mHandles.size() != 0) {
6219 handle = mHandles[0].promote();
6220 }
6221 return handle;
6222}
6223
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006224void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006225{
Steve Block71f2cf12011-10-20 11:56:00 +01006226 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006227 // keep a strong reference on this EffectModule to avoid calling the
6228 // destructor before we exit
6229 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006230 {
6231 sp<ThreadBase> thread = mThread.promote();
6232 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006233 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006234 }
6235 }
6236}
6237
Eric Laurent7d850f22010-07-09 13:34:17 -07006238void AudioFlinger::EffectModule::updateState() {
6239 Mutex::Autolock _l(mLock);
6240
6241 switch (mState) {
6242 case RESTART:
6243 reset_l();
6244 // FALL THROUGH
6245
6246 case STARTING:
6247 // clear auxiliary effect input buffer for next accumulation
6248 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6249 memset(mConfig.inputCfg.buffer.raw,
6250 0,
6251 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6252 }
6253 start_l();
6254 mState = ACTIVE;
6255 break;
6256 case STOPPING:
6257 stop_l();
6258 mDisableWaitCnt = mMaxDisableWaitCnt;
6259 mState = STOPPED;
6260 break;
6261 case STOPPED:
6262 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6263 // turn off sequence.
6264 if (--mDisableWaitCnt == 0) {
6265 reset_l();
6266 mState = IDLE;
6267 }
6268 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006269 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006270 break;
6271 }
6272}
6273
Eric Laurent65b65452010-06-01 23:49:17 -07006274void AudioFlinger::EffectModule::process()
6275{
6276 Mutex::Autolock _l(mLock);
6277
Eric Laurent21b5c472011-07-26 20:54:46 -07006278 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006279 mConfig.inputCfg.buffer.raw == NULL ||
6280 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006281 return;
6282 }
6283
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006284 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006285 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6286 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006287 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006288 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006289 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006290 }
6291
Eric Laurent65b65452010-06-01 23:49:17 -07006292 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006293 int ret = (*mEffectInterface)->process(mEffectInterface,
6294 &mConfig.inputCfg.buffer,
6295 &mConfig.outputCfg.buffer);
6296
6297 // force transition to IDLE state when engine is ready
6298 if (mState == STOPPED && ret == -ENODATA) {
6299 mDisableWaitCnt = 1;
6300 }
Eric Laurent65b65452010-06-01 23:49:17 -07006301
6302 // clear auxiliary effect input buffer for next accumulation
6303 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006304 memset(mConfig.inputCfg.buffer.raw, 0,
6305 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006306 }
6307 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006308 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6309 // If an insert effect is idle and input buffer is different from output buffer,
6310 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006311 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006312 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006313 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6314 int16_t *in = mConfig.inputCfg.buffer.s16;
6315 int16_t *out = mConfig.outputCfg.buffer.s16;
6316 for (size_t i = 0; i < frameCnt; i++) {
6317 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006318 }
Eric Laurent65b65452010-06-01 23:49:17 -07006319 }
6320 }
6321}
6322
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006323void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006324{
6325 if (mEffectInterface == NULL) {
6326 return;
6327 }
6328 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6329}
6330
6331status_t AudioFlinger::EffectModule::configure()
6332{
6333 uint32_t channels;
6334 if (mEffectInterface == NULL) {
6335 return NO_INIT;
6336 }
6337
6338 sp<ThreadBase> thread = mThread.promote();
6339 if (thread == 0) {
6340 return DEAD_OBJECT;
6341 }
6342
6343 // TODO: handle configuration of effects replacing track process
6344 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006345 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006346 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006347 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006348 }
6349
6350 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006351 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006352 } else {
6353 mConfig.inputCfg.channels = channels;
6354 }
6355 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006356 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6357 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006358 mConfig.inputCfg.samplingRate = thread->sampleRate();
6359 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6360 mConfig.inputCfg.bufferProvider.cookie = NULL;
6361 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6362 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6363 mConfig.outputCfg.bufferProvider.cookie = NULL;
6364 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6365 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6366 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6367 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006368 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006369 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006370 // - in other sessions:
6371 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6372 // other effect: overwrites output buffer: input buffer == output buffer
6373 // Auxiliary effect:
6374 // accumulates in output buffer: input buffer != output buffer
6375 // Therefore: accumulate <=> input buffer != output buffer
6376 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6377 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6378 } else {
6379 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6380 }
6381 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6382 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6383 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6384 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6385
Steve Block71f2cf12011-10-20 11:56:00 +01006386 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006387 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6388
Eric Laurent65b65452010-06-01 23:49:17 -07006389 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006390 uint32_t size = sizeof(int);
6391 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006392 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006393 sizeof(effect_config_t),
6394 &mConfig,
6395 &size,
6396 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006397 if (status == 0) {
6398 status = cmdStatus;
6399 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006400
6401 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6402 (1000 * mConfig.outputCfg.buffer.frameCount);
6403
Eric Laurent65b65452010-06-01 23:49:17 -07006404 return status;
6405}
6406
6407status_t AudioFlinger::EffectModule::init()
6408{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006409 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006410 if (mEffectInterface == NULL) {
6411 return NO_INIT;
6412 }
6413 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006414 uint32_t size = sizeof(status_t);
6415 status_t status = (*mEffectInterface)->command(mEffectInterface,
6416 EFFECT_CMD_INIT,
6417 0,
6418 NULL,
6419 &size,
6420 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006421 if (status == 0) {
6422 status = cmdStatus;
6423 }
6424 return status;
6425}
6426
Eric Laurent6fccbd02011-10-05 17:42:25 -07006427status_t AudioFlinger::EffectModule::start()
6428{
6429 Mutex::Autolock _l(mLock);
6430 return start_l();
6431}
6432
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006433status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006434{
6435 if (mEffectInterface == NULL) {
6436 return NO_INIT;
6437 }
6438 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006439 uint32_t size = sizeof(status_t);
6440 status_t status = (*mEffectInterface)->command(mEffectInterface,
6441 EFFECT_CMD_ENABLE,
6442 0,
6443 NULL,
6444 &size,
6445 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006446 if (status == 0) {
6447 status = cmdStatus;
6448 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006449 if (status == 0 &&
6450 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6451 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6452 sp<ThreadBase> thread = mThread.promote();
6453 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006454 audio_stream_t *stream = thread->stream();
6455 if (stream != NULL) {
6456 stream->add_audio_effect(stream, mEffectInterface);
6457 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006458 }
6459 }
Eric Laurent65b65452010-06-01 23:49:17 -07006460 return status;
6461}
6462
Eric Laurent21b5c472011-07-26 20:54:46 -07006463status_t AudioFlinger::EffectModule::stop()
6464{
6465 Mutex::Autolock _l(mLock);
6466 return stop_l();
6467}
6468
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006469status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006470{
6471 if (mEffectInterface == NULL) {
6472 return NO_INIT;
6473 }
6474 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006475 uint32_t size = sizeof(status_t);
6476 status_t status = (*mEffectInterface)->command(mEffectInterface,
6477 EFFECT_CMD_DISABLE,
6478 0,
6479 NULL,
6480 &size,
6481 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006482 if (status == 0) {
6483 status = cmdStatus;
6484 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006485 if (status == 0 &&
6486 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6487 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6488 sp<ThreadBase> thread = mThread.promote();
6489 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006490 audio_stream_t *stream = thread->stream();
6491 if (stream != NULL) {
6492 stream->remove_audio_effect(stream, mEffectInterface);
6493 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006494 }
6495 }
Eric Laurent65b65452010-06-01 23:49:17 -07006496 return status;
6497}
6498
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006499status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6500 uint32_t cmdSize,
6501 void *pCmdData,
6502 uint32_t *replySize,
6503 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006504{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006505 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006506// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006507
Eric Laurent21b5c472011-07-26 20:54:46 -07006508 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006509 return NO_INIT;
6510 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006511 status_t status = (*mEffectInterface)->command(mEffectInterface,
6512 cmdCode,
6513 cmdSize,
6514 pCmdData,
6515 replySize,
6516 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006517 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006518 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006519 for (size_t i = 1; i < mHandles.size(); i++) {
6520 sp<EffectHandle> h = mHandles[i].promote();
6521 if (h != 0) {
6522 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6523 }
6524 }
6525 }
6526 return status;
6527}
6528
6529status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6530{
Eric Laurent6752ec82011-08-10 10:37:50 -07006531
Eric Laurent65b65452010-06-01 23:49:17 -07006532 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006533 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006534
6535 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006536 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6537 if (enabled && status != NO_ERROR) {
6538 return status;
6539 }
6540
Eric Laurent65b65452010-06-01 23:49:17 -07006541 switch (mState) {
6542 // going from disabled to enabled
6543 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006544 mState = STARTING;
6545 break;
6546 case STOPPED:
6547 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006548 break;
6549 case STOPPING:
6550 mState = ACTIVE;
6551 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006552
6553 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006554 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006555 mState = STOPPED;
6556 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006557 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006558 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006559 break;
6560 case ACTIVE:
6561 mState = STOPPING;
6562 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006563 case DESTROYED:
6564 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006565 }
6566 for (size_t i = 1; i < mHandles.size(); i++) {
6567 sp<EffectHandle> h = mHandles[i].promote();
6568 if (h != 0) {
6569 h->setEnabled(enabled);
6570 }
6571 }
6572 }
6573 return NO_ERROR;
6574}
6575
6576bool AudioFlinger::EffectModule::isEnabled()
6577{
6578 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006579 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006580 case STARTING:
6581 case ACTIVE:
6582 return true;
6583 case IDLE:
6584 case STOPPING:
6585 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006586 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006587 default:
6588 return false;
6589 }
6590}
6591
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006592bool AudioFlinger::EffectModule::isProcessEnabled()
6593{
6594 switch (mState) {
6595 case RESTART:
6596 case ACTIVE:
6597 case STOPPING:
6598 case STOPPED:
6599 return true;
6600 case IDLE:
6601 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006602 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006603 default:
6604 return false;
6605 }
6606}
6607
Eric Laurent65b65452010-06-01 23:49:17 -07006608status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6609{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006610 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006611 status_t status = NO_ERROR;
6612
6613 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6614 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006615 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006616 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6617 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006618 status_t cmdStatus;
6619 uint32_t volume[2];
6620 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006621 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006622 volume[0] = *left;
6623 volume[1] = *right;
6624 if (controller) {
6625 pVolume = volume;
6626 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006627 status = (*mEffectInterface)->command(mEffectInterface,
6628 EFFECT_CMD_SET_VOLUME,
6629 size,
6630 volume,
6631 &size,
6632 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006633 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6634 *left = volume[0];
6635 *right = volume[1];
6636 }
6637 }
6638 return status;
6639}
6640
6641status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
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;
Eric Laurent464d5b32011-06-17 21:29:58 -07006645 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6646 // audio pre processing modules on RecordThread can receive both output and
6647 // input device indication in the same call
6648 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6649 if (dev) {
6650 status_t cmdStatus;
6651 uint32_t size = sizeof(status_t);
6652
6653 status = (*mEffectInterface)->command(mEffectInterface,
6654 EFFECT_CMD_SET_DEVICE,
6655 sizeof(uint32_t),
6656 &dev,
6657 &size,
6658 &cmdStatus);
6659 if (status == NO_ERROR) {
6660 status = cmdStatus;
6661 }
6662 }
6663 dev = device & AUDIO_DEVICE_IN_ALL;
6664 if (dev) {
6665 status_t cmdStatus;
6666 uint32_t size = sizeof(status_t);
6667
6668 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6669 EFFECT_CMD_SET_INPUT_DEVICE,
6670 sizeof(uint32_t),
6671 &dev,
6672 &size,
6673 &cmdStatus);
6674 if (status2 == NO_ERROR) {
6675 status2 = cmdStatus;
6676 }
6677 if (status == NO_ERROR) {
6678 status = status2;
6679 }
Eric Laurent65b65452010-06-01 23:49:17 -07006680 }
6681 }
6682 return status;
6683}
6684
Eric Laurent53334cd2010-06-23 17:38:20 -07006685status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6686{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006687 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006688 status_t status = NO_ERROR;
6689 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006690 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006691 uint32_t size = sizeof(status_t);
6692 status = (*mEffectInterface)->command(mEffectInterface,
6693 EFFECT_CMD_SET_AUDIO_MODE,
6694 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006695 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006696 &size,
6697 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006698 if (status == NO_ERROR) {
6699 status = cmdStatus;
6700 }
6701 }
6702 return status;
6703}
6704
Eric Laurentf82fccd2011-07-27 19:49:51 -07006705void AudioFlinger::EffectModule::setSuspended(bool suspended)
6706{
6707 Mutex::Autolock _l(mLock);
6708 mSuspended = suspended;
6709}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006710
6711bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006712{
6713 Mutex::Autolock _l(mLock);
6714 return mSuspended;
6715}
6716
Eric Laurent65b65452010-06-01 23:49:17 -07006717status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6718{
6719 const size_t SIZE = 256;
6720 char buffer[SIZE];
6721 String8 result;
6722
6723 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6724 result.append(buffer);
6725
6726 bool locked = tryLock(mLock);
6727 // failed to lock - AudioFlinger is probably deadlocked
6728 if (!locked) {
6729 result.append("\t\tCould not lock Fx mutex:\n");
6730 }
6731
6732 result.append("\t\tSession Status State Engine:\n");
6733 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6734 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6735 result.append(buffer);
6736
6737 result.append("\t\tDescriptor:\n");
6738 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6739 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6740 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6741 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6742 result.append(buffer);
6743 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6744 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6745 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6746 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6747 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006748 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006749 mDescriptor.apiVersion,
6750 mDescriptor.flags);
6751 result.append(buffer);
6752 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6753 mDescriptor.name);
6754 result.append(buffer);
6755 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6756 mDescriptor.implementor);
6757 result.append(buffer);
6758
6759 result.append("\t\t- Input configuration:\n");
6760 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6761 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6762 (uint32_t)mConfig.inputCfg.buffer.raw,
6763 mConfig.inputCfg.buffer.frameCount,
6764 mConfig.inputCfg.samplingRate,
6765 mConfig.inputCfg.channels,
6766 mConfig.inputCfg.format);
6767 result.append(buffer);
6768
6769 result.append("\t\t- Output configuration:\n");
6770 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6771 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6772 (uint32_t)mConfig.outputCfg.buffer.raw,
6773 mConfig.outputCfg.buffer.frameCount,
6774 mConfig.outputCfg.samplingRate,
6775 mConfig.outputCfg.channels,
6776 mConfig.outputCfg.format);
6777 result.append(buffer);
6778
6779 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6780 result.append(buffer);
6781 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6782 for (size_t i = 0; i < mHandles.size(); ++i) {
6783 sp<EffectHandle> handle = mHandles[i].promote();
6784 if (handle != 0) {
6785 handle->dump(buffer, SIZE);
6786 result.append(buffer);
6787 }
6788 }
6789
6790 result.append("\n");
6791
6792 write(fd, result.string(), result.length());
6793
6794 if (locked) {
6795 mLock.unlock();
6796 }
6797
6798 return NO_ERROR;
6799}
6800
6801// ----------------------------------------------------------------------------
6802// EffectHandle implementation
6803// ----------------------------------------------------------------------------
6804
6805#undef LOG_TAG
6806#define LOG_TAG "AudioFlinger::EffectHandle"
6807
6808AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6809 const sp<AudioFlinger::Client>& client,
6810 const sp<IEffectClient>& effectClient,
6811 int32_t priority)
6812 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006813 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006814 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006815{
Steve Block71f2cf12011-10-20 11:56:00 +01006816 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006817
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006818 if (client == 0) {
6819 return;
6820 }
Eric Laurent65b65452010-06-01 23:49:17 -07006821 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6822 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6823 if (mCblkMemory != 0) {
6824 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6825
6826 if (mCblk) {
6827 new(mCblk) effect_param_cblk_t();
6828 mBuffer = (uint8_t *)mCblk + bufOffset;
6829 }
6830 } else {
Steve Block3762c312012-01-06 19:20:56 +00006831 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006832 return;
6833 }
6834}
6835
6836AudioFlinger::EffectHandle::~EffectHandle()
6837{
Steve Block71f2cf12011-10-20 11:56:00 +01006838 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006839 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006840 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006841}
6842
6843status_t AudioFlinger::EffectHandle::enable()
6844{
Steve Block71f2cf12011-10-20 11:56:00 +01006845 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006846 if (!mHasControl) return INVALID_OPERATION;
6847 if (mEffect == 0) return DEAD_OBJECT;
6848
Eric Laurent6752ec82011-08-10 10:37:50 -07006849 if (mEnabled) {
6850 return NO_ERROR;
6851 }
6852
Eric Laurentf82fccd2011-07-27 19:49:51 -07006853 mEnabled = true;
6854
6855 sp<ThreadBase> thread = mEffect->thread().promote();
6856 if (thread != 0) {
6857 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6858 }
6859
6860 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6861 if (mEffect->suspended()) {
6862 return NO_ERROR;
6863 }
6864
Eric Laurent6752ec82011-08-10 10:37:50 -07006865 status_t status = mEffect->setEnabled(true);
6866 if (status != NO_ERROR) {
6867 if (thread != 0) {
6868 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6869 }
6870 mEnabled = false;
6871 }
6872 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006873}
6874
6875status_t AudioFlinger::EffectHandle::disable()
6876{
Steve Block71f2cf12011-10-20 11:56:00 +01006877 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006878 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006879 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006880
Eric Laurent6752ec82011-08-10 10:37:50 -07006881 if (!mEnabled) {
6882 return NO_ERROR;
6883 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006884 mEnabled = false;
6885
6886 if (mEffect->suspended()) {
6887 return NO_ERROR;
6888 }
6889
6890 status_t status = mEffect->setEnabled(false);
6891
6892 sp<ThreadBase> thread = mEffect->thread().promote();
6893 if (thread != 0) {
6894 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6895 }
6896
6897 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006898}
6899
6900void AudioFlinger::EffectHandle::disconnect()
6901{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006902 disconnect(true);
6903}
6904
6905void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6906{
Steve Block71f2cf12011-10-20 11:56:00 +01006907 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006908 if (mEffect == 0) {
6909 return;
6910 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006911 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006912
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006913 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006914 sp<ThreadBase> thread = mEffect->thread().promote();
6915 if (thread != 0) {
6916 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6917 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006918 }
6919
Eric Laurent65b65452010-06-01 23:49:17 -07006920 // release sp on module => module destructor can be called now
6921 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006922 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006923 if (mCblk) {
6924 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6925 }
6926 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006927 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6928 mClient.clear();
6929 }
6930}
6931
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006932status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6933 uint32_t cmdSize,
6934 void *pCmdData,
6935 uint32_t *replySize,
6936 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006937{
Steve Block71f2cf12011-10-20 11:56:00 +01006938// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006939// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006940
6941 // only get parameter command is permitted for applications not controlling the effect
6942 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6943 return INVALID_OPERATION;
6944 }
6945 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006946 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006947
6948 // handle commands that are not forwarded transparently to effect engine
6949 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6950 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6951 // no risk to block the whole media server process or mixer threads is we are stuck here
6952 Mutex::Autolock _l(mCblk->lock);
6953 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6954 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6955 mCblk->serverIndex = 0;
6956 mCblk->clientIndex = 0;
6957 return BAD_VALUE;
6958 }
6959 status_t status = NO_ERROR;
6960 while (mCblk->serverIndex < mCblk->clientIndex) {
6961 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006962 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006963 int *p = (int *)(mBuffer + mCblk->serverIndex);
6964 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006965 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00006966 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006967 break;
6968 }
Eric Laurent65b65452010-06-01 23:49:17 -07006969 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006970 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006971 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006972 mCblk->serverIndex += size;
6973 continue;
6974 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006975 uint32_t psize = sizeof(effect_param_t) +
6976 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6977 param->vsize;
6978 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6979 psize,
6980 p,
6981 &rsize,
6982 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006983 // stop at first error encountered
6984 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006985 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006986 *(int *)pReplyData = reply;
6987 break;
6988 } else if (reply != NO_ERROR) {
6989 *(int *)pReplyData = reply;
6990 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006991 }
6992 mCblk->serverIndex += size;
6993 }
6994 mCblk->serverIndex = 0;
6995 mCblk->clientIndex = 0;
6996 return status;
6997 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006998 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006999 return enable();
7000 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007001 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007002 return disable();
7003 }
7004
7005 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7006}
7007
7008sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7009 return mCblkMemory;
7010}
7011
Eric Laurentf82fccd2011-07-27 19:49:51 -07007012void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007013{
Steve Block71f2cf12011-10-20 11:56:00 +01007014 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007015
7016 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007017 mEnabled = enabled;
7018
Eric Laurent65b65452010-06-01 23:49:17 -07007019 if (signal && mEffectClient != 0) {
7020 mEffectClient->controlStatusChanged(hasControl);
7021 }
7022}
7023
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007024void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7025 uint32_t cmdSize,
7026 void *pCmdData,
7027 uint32_t replySize,
7028 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007029{
7030 if (mEffectClient != 0) {
7031 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7032 }
7033}
7034
7035
7036
7037void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7038{
7039 if (mEffectClient != 0) {
7040 mEffectClient->enableStatusChanged(enabled);
7041 }
7042}
7043
7044status_t AudioFlinger::EffectHandle::onTransact(
7045 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7046{
7047 return BnEffect::onTransact(code, data, reply, flags);
7048}
7049
7050
7051void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7052{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007053 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007054
7055 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7056 (mClient == NULL) ? getpid() : mClient->pid(),
7057 mPriority,
7058 mHasControl,
7059 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007060 mCblk ? mCblk->clientIndex : 0,
7061 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007062 );
7063
7064 if (locked) {
7065 mCblk->lock.unlock();
7066 }
7067}
7068
7069#undef LOG_TAG
7070#define LOG_TAG "AudioFlinger::EffectChain"
7071
7072AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7073 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007074 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007075 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7076 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007077{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007078 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007079 sp<ThreadBase> thread = mThread.promote();
7080 if (thread == 0) {
7081 return;
7082 }
7083 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7084 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007085}
7086
7087AudioFlinger::EffectChain::~EffectChain()
7088{
7089 if (mOwnInBuffer) {
7090 delete mInBuffer;
7091 }
7092
7093}
7094
Eric Laurentf82fccd2011-07-27 19:49:51 -07007095// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007096sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007097{
7098 sp<EffectModule> effect;
7099 size_t size = mEffects.size();
7100
7101 for (size_t i = 0; i < size; i++) {
7102 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7103 effect = mEffects[i];
7104 break;
7105 }
7106 }
7107 return effect;
7108}
7109
Eric Laurentf82fccd2011-07-27 19:49:51 -07007110// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007111sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007112{
7113 sp<EffectModule> effect;
7114 size_t size = mEffects.size();
7115
7116 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007117 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7118 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007119 effect = mEffects[i];
7120 break;
7121 }
7122 }
7123 return effect;
7124}
7125
Eric Laurentf82fccd2011-07-27 19:49:51 -07007126// getEffectFromType_l() must be called with ThreadBase::mLock held
7127sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7128 const effect_uuid_t *type)
7129{
7130 sp<EffectModule> effect;
7131 size_t size = mEffects.size();
7132
7133 for (size_t i = 0; i < size; i++) {
7134 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7135 effect = mEffects[i];
7136 break;
7137 }
7138 }
7139 return effect;
7140}
7141
Eric Laurent65b65452010-06-01 23:49:17 -07007142// Must be called with EffectChain::mLock locked
7143void AudioFlinger::EffectChain::process_l()
7144{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007145 sp<ThreadBase> thread = mThread.promote();
7146 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007147 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007148 return;
7149 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007150 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7151 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007152 // always process effects unless no more tracks are on the session and the effect tail
7153 // has been rendered
7154 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007155 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007156 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007157
Eric Laurentf9c361d2011-11-11 15:42:52 -08007158 if (!tracksOnSession && mTailBufferCount == 0) {
7159 doProcess = false;
7160 }
7161
7162 if (activeTrackCnt() == 0) {
7163 // if no track is active and the effect tail has not been rendered,
7164 // the input buffer must be cleared here as the mixer process will not do it
7165 if (tracksOnSession || mTailBufferCount > 0) {
7166 size_t numSamples = thread->frameCount() * thread->channelCount();
7167 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7168 if (mTailBufferCount > 0) {
7169 mTailBufferCount--;
7170 }
7171 }
7172 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007173 }
7174
Eric Laurent65b65452010-06-01 23:49:17 -07007175 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007176 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007177 for (size_t i = 0; i < size; i++) {
7178 mEffects[i]->process();
7179 }
Eric Laurent65b65452010-06-01 23:49:17 -07007180 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007181 for (size_t i = 0; i < size; i++) {
7182 mEffects[i]->updateState();
7183 }
Eric Laurent65b65452010-06-01 23:49:17 -07007184}
7185
Eric Laurent76c40f72010-07-15 12:50:15 -07007186// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007187status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007188{
7189 effect_descriptor_t desc = effect->desc();
7190 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7191
7192 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007193 effect->setChain(this);
7194 sp<ThreadBase> thread = mThread.promote();
7195 if (thread == 0) {
7196 return NO_INIT;
7197 }
7198 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007199
7200 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7201 // Auxiliary effects are inserted at the beginning of mEffects vector as
7202 // they are processed first and accumulated in chain input buffer
7203 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007204
Eric Laurent65b65452010-06-01 23:49:17 -07007205 // the input buffer for auxiliary effect contains mono samples in
7206 // 32 bit format. This is to avoid saturation in AudoMixer
7207 // accumulation stage. Saturation is done in EffectModule::process() before
7208 // calling the process in effect engine
7209 size_t numSamples = thread->frameCount();
7210 int32_t *buffer = new int32_t[numSamples];
7211 memset(buffer, 0, numSamples * sizeof(int32_t));
7212 effect->setInBuffer((int16_t *)buffer);
7213 // auxiliary effects output samples to chain input buffer for further processing
7214 // by insert effects
7215 effect->setOutBuffer(mInBuffer);
7216 } else {
7217 // Insert effects are inserted at the end of mEffects vector as they are processed
7218 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007219 // Insert effect order as a function of indicated preference:
7220 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7221 // another effect is present
7222 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7223 // last effect claiming first position
7224 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7225 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007226 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007227 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7228 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007229
7230 int size = (int)mEffects.size();
7231 int idx_insert = size;
7232 int idx_insert_first = -1;
7233 int idx_insert_last = -1;
7234
7235 for (int i = 0; i < size; i++) {
7236 effect_descriptor_t d = mEffects[i]->desc();
7237 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7238 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7239 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7240 // check invalid effect chaining combinations
7241 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007242 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007243 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007244 return INVALID_OPERATION;
7245 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007246 // remember position of first insert effect and by default
7247 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007248 if (idx_insert == size) {
7249 idx_insert = i;
7250 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007251 // remember position of last insert effect claiming
7252 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007253 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7254 idx_insert_first = i;
7255 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007256 // remember position of first insert effect claiming
7257 // last position
7258 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7259 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007260 idx_insert_last = i;
7261 }
7262 }
7263 }
7264
Eric Laurent53334cd2010-06-23 17:38:20 -07007265 // modify idx_insert from first position if needed
7266 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7267 if (idx_insert_last != -1) {
7268 idx_insert = idx_insert_last;
7269 } else {
7270 idx_insert = size;
7271 }
7272 } else {
7273 if (idx_insert_first != -1) {
7274 idx_insert = idx_insert_first + 1;
7275 }
Eric Laurent65b65452010-06-01 23:49:17 -07007276 }
7277
7278 // always read samples from chain input buffer
7279 effect->setInBuffer(mInBuffer);
7280
7281 // if last effect in the chain, output samples to chain
7282 // output buffer, otherwise to chain input buffer
7283 if (idx_insert == size) {
7284 if (idx_insert != 0) {
7285 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7286 mEffects[idx_insert-1]->configure();
7287 }
7288 effect->setOutBuffer(mOutBuffer);
7289 } else {
7290 effect->setOutBuffer(mInBuffer);
7291 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007292 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007293
Steve Block71f2cf12011-10-20 11:56:00 +01007294 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007295 }
7296 effect->configure();
7297 return NO_ERROR;
7298}
7299
Eric Laurent76c40f72010-07-15 12:50:15 -07007300// removeEffect_l() must be called with PlaybackThread::mLock held
7301size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007302{
7303 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007304 int size = (int)mEffects.size();
7305 int i;
7306 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7307
7308 for (i = 0; i < size; i++) {
7309 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007310 // calling stop here will remove pre-processing effect from the audio HAL.
7311 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7312 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007313 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7314 mEffects[i]->state() == EffectModule::STOPPING) {
7315 mEffects[i]->stop();
7316 }
Eric Laurent65b65452010-06-01 23:49:17 -07007317 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7318 delete[] effect->inBuffer();
7319 } else {
7320 if (i == size - 1 && i != 0) {
7321 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7322 mEffects[i - 1]->configure();
7323 }
7324 }
7325 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007326 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007327 break;
7328 }
7329 }
Eric Laurent65b65452010-06-01 23:49:17 -07007330
7331 return mEffects.size();
7332}
7333
Eric Laurent76c40f72010-07-15 12:50:15 -07007334// setDevice_l() must be called with PlaybackThread::mLock held
7335void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007336{
7337 size_t size = mEffects.size();
7338 for (size_t i = 0; i < size; i++) {
7339 mEffects[i]->setDevice(device);
7340 }
7341}
7342
Eric Laurent76c40f72010-07-15 12:50:15 -07007343// setMode_l() must be called with PlaybackThread::mLock held
7344void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007345{
7346 size_t size = mEffects.size();
7347 for (size_t i = 0; i < size; i++) {
7348 mEffects[i]->setMode(mode);
7349 }
7350}
7351
Eric Laurent76c40f72010-07-15 12:50:15 -07007352// setVolume_l() must be called with PlaybackThread::mLock held
7353bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007354{
7355 uint32_t newLeft = *left;
7356 uint32_t newRight = *right;
7357 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007358 int ctrlIdx = -1;
7359 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007360
Eric Laurent76c40f72010-07-15 12:50:15 -07007361 // first update volume controller
7362 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007363 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007364 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7365 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007366 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007367 break;
7368 }
7369 }
7370
7371 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007372 if (hasControl) {
7373 *left = mNewLeftVolume;
7374 *right = mNewRightVolume;
7375 }
7376 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007377 }
7378
7379 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007380 mLeftVolume = newLeft;
7381 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007382
7383 // second get volume update from volume controller
7384 if (ctrlIdx >= 0) {
7385 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007386 mNewLeftVolume = newLeft;
7387 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007388 }
7389 // then indicate volume to all other effects in chain.
7390 // Pass altered volume to effects before volume controller
7391 // and requested volume to effects after controller
7392 uint32_t lVol = newLeft;
7393 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007394
Eric Laurent65b65452010-06-01 23:49:17 -07007395 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007396 if ((int)i == ctrlIdx) continue;
7397 // this also works for ctrlIdx == -1 when there is no volume controller
7398 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007399 lVol = *left;
7400 rVol = *right;
7401 }
7402 mEffects[i]->setVolume(&lVol, &rVol, false);
7403 }
7404 *left = newLeft;
7405 *right = newRight;
7406
7407 return hasControl;
7408}
7409
Eric Laurent65b65452010-06-01 23:49:17 -07007410status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7411{
7412 const size_t SIZE = 256;
7413 char buffer[SIZE];
7414 String8 result;
7415
7416 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7417 result.append(buffer);
7418
7419 bool locked = tryLock(mLock);
7420 // failed to lock - AudioFlinger is probably deadlocked
7421 if (!locked) {
7422 result.append("\tCould not lock mutex:\n");
7423 }
7424
Eric Laurent76c40f72010-07-15 12:50:15 -07007425 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7426 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007427 mEffects.size(),
7428 (uint32_t)mInBuffer,
7429 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007430 mActiveTrackCnt);
7431 result.append(buffer);
7432 write(fd, result.string(), result.size());
7433
7434 for (size_t i = 0; i < mEffects.size(); ++i) {
7435 sp<EffectModule> effect = mEffects[i];
7436 if (effect != 0) {
7437 effect->dump(fd, args);
7438 }
7439 }
7440
7441 if (locked) {
7442 mLock.unlock();
7443 }
7444
7445 return NO_ERROR;
7446}
7447
Eric Laurentf82fccd2011-07-27 19:49:51 -07007448// must be called with ThreadBase::mLock held
7449void AudioFlinger::EffectChain::setEffectSuspended_l(
7450 const effect_uuid_t *type, bool suspend)
7451{
7452 sp<SuspendedEffectDesc> desc;
7453 // use effect type UUID timelow as key as there is no real risk of identical
7454 // timeLow fields among effect type UUIDs.
7455 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7456 if (suspend) {
7457 if (index >= 0) {
7458 desc = mSuspendedEffects.valueAt(index);
7459 } else {
7460 desc = new SuspendedEffectDesc();
7461 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7462 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007463 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007464 }
7465 if (desc->mRefCount++ == 0) {
7466 sp<EffectModule> effect = getEffectIfEnabled(type);
7467 if (effect != 0) {
7468 desc->mEffect = effect;
7469 effect->setSuspended(true);
7470 effect->setEnabled(false);
7471 }
7472 }
7473 } else {
7474 if (index < 0) {
7475 return;
7476 }
7477 desc = mSuspendedEffects.valueAt(index);
7478 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007479 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007480 desc->mRefCount = 1;
7481 }
7482 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007483 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007484 if (desc->mEffect != 0) {
7485 sp<EffectModule> effect = desc->mEffect.promote();
7486 if (effect != 0) {
7487 effect->setSuspended(false);
7488 sp<EffectHandle> handle = effect->controlHandle();
7489 if (handle != 0) {
7490 effect->setEnabled(handle->enabled());
7491 }
7492 }
7493 desc->mEffect.clear();
7494 }
7495 mSuspendedEffects.removeItemsAt(index);
7496 }
7497 }
7498}
7499
7500// must be called with ThreadBase::mLock held
7501void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7502{
7503 sp<SuspendedEffectDesc> desc;
7504
7505 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7506 if (suspend) {
7507 if (index >= 0) {
7508 desc = mSuspendedEffects.valueAt(index);
7509 } else {
7510 desc = new SuspendedEffectDesc();
7511 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007512 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007513 }
7514 if (desc->mRefCount++ == 0) {
7515 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7516 for (size_t i = 0; i < effects.size(); i++) {
7517 setEffectSuspended_l(&effects[i]->desc().type, true);
7518 }
7519 }
7520 } else {
7521 if (index < 0) {
7522 return;
7523 }
7524 desc = mSuspendedEffects.valueAt(index);
7525 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007526 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007527 desc->mRefCount = 1;
7528 }
7529 if (--desc->mRefCount == 0) {
7530 Vector<const effect_uuid_t *> types;
7531 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7532 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7533 continue;
7534 }
7535 types.add(&mSuspendedEffects.valueAt(i)->mType);
7536 }
7537 for (size_t i = 0; i < types.size(); i++) {
7538 setEffectSuspended_l(types[i], false);
7539 }
Steve Block71f2cf12011-10-20 11:56:00 +01007540 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007541 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7542 }
7543 }
7544}
7545
Eric Laurent5e7acae2011-09-23 08:40:41 -07007546
7547// The volume effect is used for automated tests only
7548#ifndef OPENSL_ES_H_
7549static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7550 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7551const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7552#endif //OPENSL_ES_H_
7553
Eric Laurent6752ec82011-08-10 10:37:50 -07007554bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7555{
7556 // auxiliary effects and visualizer are never suspended on output mix
7557 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7558 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007559 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7560 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007561 return false;
7562 }
7563 return true;
7564}
7565
Eric Laurentf82fccd2011-07-27 19:49:51 -07007566Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7567{
7568 Vector< sp<EffectModule> > effects;
7569 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007570 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007571 continue;
7572 }
7573 effects.add(mEffects[i]);
7574 }
7575 return effects;
7576}
7577
7578sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7579 const effect_uuid_t *type)
7580{
7581 sp<EffectModule> effect;
7582 effect = getEffectFromType_l(type);
7583 if (effect != 0 && !effect->isEnabled()) {
7584 effect.clear();
7585 }
7586 return effect;
7587}
7588
7589void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7590 bool enabled)
7591{
7592 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7593 if (enabled) {
7594 if (index < 0) {
7595 // if the effect is not suspend check if all effects are suspended
7596 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7597 if (index < 0) {
7598 return;
7599 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007600 if (!isEffectEligibleForSuspend(effect->desc())) {
7601 return;
7602 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007603 setEffectSuspended_l(&effect->desc().type, enabled);
7604 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007605 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007606 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07007607 return;
7608 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007609 }
Steve Block71f2cf12011-10-20 11:56:00 +01007610 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007611 effect->desc().type.timeLow);
7612 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7613 // if effect is requested to suspended but was not yet enabled, supend it now.
7614 if (desc->mEffect == 0) {
7615 desc->mEffect = effect;
7616 effect->setEnabled(false);
7617 effect->setSuspended(true);
7618 }
7619 } else {
7620 if (index < 0) {
7621 return;
7622 }
Steve Block71f2cf12011-10-20 11:56:00 +01007623 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007624 effect->desc().type.timeLow);
7625 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7626 desc->mEffect.clear();
7627 effect->setSuspended(false);
7628 }
7629}
7630
Eric Laurent65b65452010-06-01 23:49:17 -07007631#undef LOG_TAG
7632#define LOG_TAG "AudioFlinger"
7633
Eric Laurenta553c252009-07-17 12:17:14 -07007634// ----------------------------------------------------------------------------
7635
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007636status_t AudioFlinger::onTransact(
7637 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7638{
7639 return BnAudioFlinger::onTransact(code, data, reply, flags);
7640}
7641
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007642}; // namespace android