blob: 433af4abde1e95d10ec08909b2d4f551749a2615 [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>
38
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070044#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
Dima Zavin34bb4192011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070047#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Eric Laurent53334cd2010-06-23 17:38:20 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
Glenn Kastenda494f92011-07-08 15:26:12 -070057#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070059// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
60
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
Eric Laurent8ed6ed02010-07-13 04:45:46 -070063
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070064namespace android {
65
The Android Open Source Project10592532009-03-18 17:39:46 -070066static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
67static const char* kHardwareLockedString = "Hardware lock is taken\n";
68
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080069//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070071static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072
73// retry counts for buffer fill timeout
74// 50 * ~20msecs = 1 second
75static const int8_t kMaxTrackRetries = 50;
76static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080077// allow less retry attempts on direct output thread.
78// direct outputs can be a scarce resource in audio hardware and should
79// be released as quickly as possible.
80static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070081
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070082static const int kDumpLockRetries = 50;
83static const int kDumpLockSleep = 20000;
84
Dave Sparksd0ac8c02009-09-30 03:09:03 -070085static const nsecs_t kWarningThrottle = seconds(5);
86
Eric Laurent464d5b32011-06-17 21:29:58 -070087// RecordThread loop sleep time upon application overrun or audio HAL read error
88static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Eric Laurent5f37be32011-09-13 11:40:21 -070090static const nsecs_t kSetParametersTimeout = seconds(2);
91
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070092// ----------------------------------------------------------------------------
93
94static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070095 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
96 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
97 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
98 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070099}
100
101static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
103 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
104 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
105 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106}
107
Gloria Wang9b3f1522011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
110 sp<IBinder> binder =
111 defaultServiceManager()->getService(String16("media.player"));
112 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
113 if (service.get() == NULL) {
114 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
115 return;
116 }
117
118 service->addBatteryData(params);
119}
120
Dima Zavin31f188892011-04-18 16:57:27 -0700121static int load_audio_interface(const char *if_name, const hw_module_t **mod,
122 audio_hw_device_t **dev)
123{
124 int rc;
125
126 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
127 if (rc)
128 goto out;
129
130 rc = audio_hw_device_open(*mod, dev);
131 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
132 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
133 if (rc)
134 goto out;
135
136 return 0;
137
138out:
139 *mod = NULL;
140 *dev = NULL;
141 return rc;
142}
143
144static const char *audio_interfaces[] = {
145 "primary",
146 "a2dp",
147 "usb",
148};
149#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
150
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700151// ----------------------------------------------------------------------------
152
153AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 : BnAudioFlinger(),
Eric Laurent6639b552011-08-01 09:52:20 -0700155 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700156 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700157{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700158}
159
160void AudioFlinger::onFirstRef()
161{
Dima Zavin31f188892011-04-18 16:57:27 -0700162 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700163
Eric Laurent01635942011-01-18 18:39:02 -0800164 Mutex::Autolock _l(mLock);
165
Dima Zavin31f188892011-04-18 16:57:27 -0700166 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700168
Dima Zavin31f188892011-04-18 16:57:27 -0700169 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
170 const hw_module_t *mod;
171 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700172
Dima Zavin31f188892011-04-18 16:57:27 -0700173 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
174 if (rc)
175 continue;
176
177 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
178 mod->name, mod->id);
179 mAudioHwDevs.push(dev);
180
181 if (!mPrimaryHardwareDev) {
182 mPrimaryHardwareDev = dev;
183 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700184 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700185 }
186 }
Eric Laurenta553c252009-07-17 12:17:14 -0700187
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700188 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700189
Dima Zavin31f188892011-04-18 16:57:27 -0700190 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
191 LOGE("Primary audio interface not found");
192 return;
193 }
194
195 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
196 audio_hw_device_t *dev = mAudioHwDevs[i];
197
198 mHardwareStatus = AUDIO_HW_INIT;
199 rc = dev->init_check(dev);
200 if (rc == 0) {
201 AutoMutex lock(mHardwareLock);
202
203 mMode = AUDIO_MODE_NORMAL;
204 mHardwareStatus = AUDIO_HW_SET_MODE;
205 dev->set_mode(dev, mMode);
206 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
207 dev->set_master_volume(dev, 1.0f);
208 mHardwareStatus = AUDIO_HW_IDLE;
209 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700210 }
211}
212
Dima Zavin2986f5b2011-04-19 19:04:32 -0700213status_t AudioFlinger::initCheck() const
214{
215 Mutex::Autolock _l(mLock);
216 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
217 return NO_INIT;
218 return NO_ERROR;
219}
220
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700221AudioFlinger::~AudioFlinger()
222{
Dima Zavin31f188892011-04-18 16:57:27 -0700223 int num_devs = mAudioHwDevs.size();
224
Eric Laurent7954c462009-08-28 10:39:03 -0700225 while (!mRecordThreads.isEmpty()) {
226 // closeInput() will remove first entry from mRecordThreads
227 closeInput(mRecordThreads.keyAt(0));
228 }
229 while (!mPlaybackThreads.isEmpty()) {
230 // closeOutput() will remove first entry from mPlaybackThreads
231 closeOutput(mPlaybackThreads.keyAt(0));
232 }
Dima Zavin31f188892011-04-18 16:57:27 -0700233
234 for (int i = 0; i < num_devs; i++) {
235 audio_hw_device_t *dev = mAudioHwDevs[i];
236 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700237 }
Dima Zavin31f188892011-04-18 16:57:27 -0700238 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800239}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800240
Dima Zavin31f188892011-04-18 16:57:27 -0700241audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
242{
243 /* first matching HW device is returned */
244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 if ((dev->get_supported_devices(dev) & devices) == devices)
247 return dev;
248 }
249 return NULL;
250}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700251
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700252status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
253{
254 const size_t SIZE = 256;
255 char buffer[SIZE];
256 String8 result;
257
258 result.append("Clients:\n");
259 for (size_t i = 0; i < mClients.size(); ++i) {
260 wp<Client> wClient = mClients.valueAt(i);
261 if (wClient != 0) {
262 sp<Client> client = wClient.promote();
263 if (client != 0) {
264 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
265 result.append(buffer);
266 }
267 }
268 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700269
270 result.append("Global session refs:\n");
271 result.append(" session pid cnt\n");
272 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
273 AudioSessionRef *r = mAudioSessionRefs[i];
274 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
275 result.append(buffer);
276 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700277 write(fd, result.string(), result.size());
278 return NO_ERROR;
279}
280
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281
282status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700287 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700288
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700289 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700290 result.append(buffer);
291 write(fd, result.string(), result.size());
292 return NO_ERROR;
293}
294
295status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
296{
297 const size_t SIZE = 256;
298 char buffer[SIZE];
299 String8 result;
300 snprintf(buffer, SIZE, "Permission Denial: "
301 "can't dump AudioFlinger from pid=%d, uid=%d\n",
302 IPCThreadState::self()->getCallingPid(),
303 IPCThreadState::self()->getCallingUid());
304 result.append(buffer);
305 write(fd, result.string(), result.size());
306 return NO_ERROR;
307}
308
The Android Open Source Project10592532009-03-18 17:39:46 -0700309static bool tryLock(Mutex& mutex)
310{
311 bool locked = false;
312 for (int i = 0; i < kDumpLockRetries; ++i) {
313 if (mutex.tryLock() == NO_ERROR) {
314 locked = true;
315 break;
316 }
317 usleep(kDumpLockSleep);
318 }
319 return locked;
320}
321
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700322status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
323{
324 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
325 dumpPermissionDenial(fd, args);
326 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700327 // get state of hardware lock
328 bool hardwareLocked = tryLock(mHardwareLock);
329 if (!hardwareLocked) {
330 String8 result(kHardwareLockedString);
331 write(fd, result.string(), result.size());
332 } else {
333 mHardwareLock.unlock();
334 }
335
336 bool locked = tryLock(mLock);
337
338 // failed to lock - AudioFlinger is probably deadlocked
339 if (!locked) {
340 String8 result(kDeadlockedString);
341 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700342 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700343
344 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700345 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346
Eric Laurenta553c252009-07-17 12:17:14 -0700347 // dump playback threads
348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700349 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700350 }
351
352 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700353 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700354 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
Dima Zavin31f188892011-04-18 16:57:27 -0700357 // dump all hardware devs
358 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
359 audio_hw_device_t *dev = mAudioHwDevs[i];
360 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700361 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700362 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700363 }
364 return NO_ERROR;
365}
366
Eric Laurenta553c252009-07-17 12:17:14 -0700367
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369
370
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371sp<IAudioTrack> AudioFlinger::createTrack(
372 pid_t pid,
373 int streamType,
374 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700375 uint32_t format,
376 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800377 int frameCount,
378 uint32_t flags,
379 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700380 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700381 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800382 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700383{
Eric Laurenta553c252009-07-17 12:17:14 -0700384 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700385 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700386 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800387 wp<Client> wclient;
388 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700389 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700390
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700391 if (streamType >= AUDIO_STREAM_CNT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800392 LOGE("invalid stream type");
393 lStatus = BAD_VALUE;
394 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 }
396
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800397 {
398 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700399 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700400 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700401 if (thread == NULL) {
402 LOGE("unknown output thread");
403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800406
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800407 wclient = mClients.valueFor(pid);
408
409 if (wclient != NULL) {
410 client = wclient.promote();
411 } else {
412 client = new Client(this, pid);
413 mClients.add(pid, client);
414 }
Eric Laurent65b65452010-06-01 23:49:17 -0700415
Steve Block71f2cf12011-10-20 11:56:00 +0100416 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700417 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700418 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700419 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
420 if (mPlaybackThreads.keyAt(i) != output) {
421 // prevent same audio session on different output threads
422 uint32_t sessions = t->hasAudioSession(*sessionId);
423 if (sessions & PlaybackThread::TRACK_SESSION) {
424 lStatus = BAD_VALUE;
425 goto Exit;
426 }
427 // check if an effect with same session ID is waiting for a track to be created
428 if (sessions & PlaybackThread::EFFECT_SESSION) {
429 effectThread = t.get();
430 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700431 }
432 }
Eric Laurent65b65452010-06-01 23:49:17 -0700433 lSessionId = *sessionId;
434 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700435 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700436 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700437 if (sessionId != NULL) {
438 *sessionId = lSessionId;
439 }
440 }
Steve Block71f2cf12011-10-20 11:56:00 +0100441 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700442
Eric Laurenta553c252009-07-17 12:17:14 -0700443 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700444 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700445
446 // move effect chain to this output thread if an effect on same session was waiting
447 // for a track to be created
448 if (lStatus == NO_ERROR && effectThread != NULL) {
449 Mutex::Autolock _dl(thread->mLock);
450 Mutex::Autolock _sl(effectThread->mLock);
451 moveEffectChain_l(lSessionId, effectThread, thread, true);
452 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700453 }
454 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800455 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700456 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700457 // remove local strong reference to Client before deleting the Track so that the Client
458 // destructor is called by the TrackBase destructor with mLock held
459 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700460 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800461 }
462
463Exit:
464 if(status) {
465 *status = lStatus;
466 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700467 return trackHandle;
468}
469
Eric Laurentddb78e72009-07-28 08:44:33 -0700470uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700471{
Eric Laurenta553c252009-07-17 12:17:14 -0700472 Mutex::Autolock _l(mLock);
473 PlaybackThread *thread = checkPlaybackThread_l(output);
474 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700475 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700476 return 0;
477 }
478 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479}
480
Eric Laurentddb78e72009-07-28 08:44:33 -0700481int AudioFlinger::channelCount(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) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700486 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700487 return 0;
488 }
489 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490}
491
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700492uint32_t AudioFlinger::format(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) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700497 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700498 return 0;
499 }
500 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501}
502
Eric Laurentddb78e72009-07-28 08:44:33 -0700503size_t AudioFlinger::frameCount(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) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700508 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700509 return 0;
510 }
511 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512}
513
Eric Laurentddb78e72009-07-28 08:44:33 -0700514uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800515{
Eric Laurenta553c252009-07-17 12:17:14 -0700516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700519 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700520 return 0;
521 }
522 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800523}
524
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700525status_t AudioFlinger::setMasterVolume(float value)
526{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700527 status_t ret = initCheck();
528 if (ret != NO_ERROR) {
529 return ret;
530 }
531
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700532 // check calling permissions
533 if (!settingsAllowed()) {
534 return PERMISSION_DENIED;
535 }
536
537 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800538 { // scope for the lock
539 AutoMutex lock(mHardwareLock);
540 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700541 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800542 value = 1.0f;
543 }
544 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700545 }
Eric Laurenta553c252009-07-17 12:17:14 -0700546
Eric Laurent01635942011-01-18 18:39:02 -0800547 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700548 mMasterVolume = value;
549 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700550 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700551
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552 return NO_ERROR;
553}
554
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555status_t AudioFlinger::setMode(int mode)
556{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700557 status_t ret = initCheck();
558 if (ret != NO_ERROR) {
559 return ret;
560 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700561
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700562 // check calling permissions
563 if (!settingsAllowed()) {
564 return PERMISSION_DENIED;
565 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700566 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700567 LOGW("Illegal value: setMode(%d)", mode);
568 return BAD_VALUE;
569 }
570
Eric Laurent53334cd2010-06-23 17:38:20 -0700571 { // scope for the lock
572 AutoMutex lock(mHardwareLock);
573 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700574 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700575 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800576 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700577
578 if (NO_ERROR == ret) {
579 Mutex::Autolock _l(mLock);
580 mMode = mode;
581 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
582 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700583 }
584
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700585 return ret;
586}
587
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700588status_t AudioFlinger::setMicMute(bool state)
589{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700590 status_t ret = initCheck();
591 if (ret != NO_ERROR) {
592 return ret;
593 }
594
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700595 // check calling permissions
596 if (!settingsAllowed()) {
597 return PERMISSION_DENIED;
598 }
599
600 AutoMutex lock(mHardwareLock);
601 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700602 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700603 mHardwareStatus = AUDIO_HW_IDLE;
604 return ret;
605}
606
607bool AudioFlinger::getMicMute() const
608{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700609 status_t ret = initCheck();
610 if (ret != NO_ERROR) {
611 return false;
612 }
613
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700614 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700615 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700616 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700617 mHardwareStatus = AUDIO_HW_IDLE;
618 return state;
619}
620
621status_t AudioFlinger::setMasterMute(bool muted)
622{
623 // check calling permissions
624 if (!settingsAllowed()) {
625 return PERMISSION_DENIED;
626 }
Eric Laurenta553c252009-07-17 12:17:14 -0700627
Eric Laurent01635942011-01-18 18:39:02 -0800628 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700629 mMasterMute = muted;
630 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700631 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700632
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700633 return NO_ERROR;
634}
635
636float AudioFlinger::masterVolume() const
637{
Eric Laurenta553c252009-07-17 12:17:14 -0700638 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700639}
640
641bool AudioFlinger::masterMute() const
642{
Eric Laurenta553c252009-07-17 12:17:14 -0700643 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700644}
645
Eric Laurentddb78e72009-07-28 08:44:33 -0700646status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700647{
648 // check calling permissions
649 if (!settingsAllowed()) {
650 return PERMISSION_DENIED;
651 }
652
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700653 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700654 return BAD_VALUE;
655 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800656
Eric Laurenta553c252009-07-17 12:17:14 -0700657 AutoMutex lock(mLock);
658 PlaybackThread *thread = NULL;
659 if (output) {
660 thread = checkPlaybackThread_l(output);
661 if (thread == NULL) {
662 return BAD_VALUE;
663 }
664 }
665
Eric Laurenta553c252009-07-17 12:17:14 -0700666 mStreamTypes[stream].volume = value;
667
668 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700669 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700670 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700671 }
Eric Laurenta553c252009-07-17 12:17:14 -0700672 } else {
673 thread->setStreamVolume(stream, value);
674 }
Eric Laurentef028272009-04-21 07:56:33 -0700675
Eric Laurent415f3e22009-10-21 08:14:22 -0700676 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700677}
678
679status_t AudioFlinger::setStreamMute(int stream, bool muted)
680{
681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700686 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
687 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700688 return BAD_VALUE;
689 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700690
Eric Laurent01635942011-01-18 18:39:02 -0800691 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700692 mStreamTypes[stream].mute = muted;
693 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700694 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700696 return NO_ERROR;
697}
698
Eric Laurentddb78e72009-07-28 08:44:33 -0700699float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700700{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700701 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700702 return 0.0f;
703 }
Eric Laurenta553c252009-07-17 12:17:14 -0700704
705 AutoMutex lock(mLock);
706 float volume;
707 if (output) {
708 PlaybackThread *thread = checkPlaybackThread_l(output);
709 if (thread == NULL) {
710 return 0.0f;
711 }
712 volume = thread->streamVolume(stream);
713 } else {
714 volume = mStreamTypes[stream].volume;
715 }
716
Eric Laurentef028272009-04-21 07:56:33 -0700717 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700718}
719
720bool AudioFlinger::streamMute(int stream) const
721{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700722 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700723 return true;
724 }
Eric Laurenta553c252009-07-17 12:17:14 -0700725
726 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700727}
728
Eric Laurentddb78e72009-07-28 08:44:33 -0700729status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700730{
Eric Laurenta553c252009-07-17 12:17:14 -0700731 status_t result;
732
Steve Block71f2cf12011-10-20 11:56:00 +0100733 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700734 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
735 // check calling permissions
736 if (!settingsAllowed()) {
737 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800738 }
Eric Laurenta553c252009-07-17 12:17:14 -0700739
740 // ioHandle == 0 means the parameters are global to the audio hardware interface
741 if (ioHandle == 0) {
742 AutoMutex lock(mHardwareLock);
743 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700744 status_t final_result = NO_ERROR;
745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
746 audio_hw_device_t *dev = mAudioHwDevs[i];
747 result = dev->set_parameters(dev, keyValuePairs.string());
748 final_result = result ?: final_result;
749 }
Eric Laurenta553c252009-07-17 12:17:14 -0700750 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700751 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
752 AudioParameter param = AudioParameter(keyValuePairs);
753 String8 value;
754 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
755 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700756 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
757 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700758 for (size_t i = 0; i < mRecordThreads.size(); i++) {
759 sp<RecordThread> thread = mRecordThreads.valueAt(i);
760 RecordThread::RecordTrack *track = thread->track();
761 if (track != NULL) {
762 audio_devices_t device = (audio_devices_t)(
763 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700764 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700765 thread->setEffectSuspended(FX_IID_AEC,
766 suspend,
767 track->sessionId());
768 thread->setEffectSuspended(FX_IID_NS,
769 suspend,
770 track->sessionId());
771 }
772 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700773 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700774 }
775 }
Dima Zavin31f188892011-04-18 16:57:27 -0700776 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700777 }
778
Eric Laurentb7d94602009-09-29 11:12:57 -0700779 // hold a strong ref on thread in case closeOutput() or closeInput() is called
780 // and the thread is exited once the lock is released
781 sp<ThreadBase> thread;
782 {
783 Mutex::Autolock _l(mLock);
784 thread = checkPlaybackThread_l(ioHandle);
785 if (thread == NULL) {
786 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700787 } else if (thread.get() == primaryPlaybackThread_l()) {
788 // indicate output device change to all input threads for pre processing
789 AudioParameter param = AudioParameter(keyValuePairs);
790 int value;
791 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
792 for (size_t i = 0; i < mRecordThreads.size(); i++) {
793 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
794 }
795 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700796 }
Eric Laurenta553c252009-07-17 12:17:14 -0700797 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700798 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800799 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800800 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700801 }
Eric Laurenta553c252009-07-17 12:17:14 -0700802 return BAD_VALUE;
803}
804
Eric Laurentddb78e72009-07-28 08:44:33 -0700805String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700806{
Steve Block71f2cf12011-10-20 11:56:00 +0100807// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700808// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
809
810 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700811 String8 out_s8;
812
Dima Zavin31f188892011-04-18 16:57:27 -0700813 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
814 audio_hw_device_t *dev = mAudioHwDevs[i];
815 char *s = dev->get_parameters(dev, keys.string());
816 out_s8 += String8(s);
817 free(s);
818 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700819 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700820 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700821
822 Mutex::Autolock _l(mLock);
823
Eric Laurenta553c252009-07-17 12:17:14 -0700824 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
825 if (playbackThread != NULL) {
826 return playbackThread->getParameters(keys);
827 }
828 RecordThread *recordThread = checkRecordThread_l(ioHandle);
829 if (recordThread != NULL) {
830 return recordThread->getParameters(keys);
831 }
832 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700833}
834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
836{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700837 status_t ret = initCheck();
838 if (ret != NO_ERROR) {
839 return 0;
840 }
841
Dima Zavin31f188892011-04-18 16:57:27 -0700842 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843}
844
Eric Laurent47d0a922010-02-26 02:47:27 -0800845unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
846{
847 if (ioHandle == 0) {
848 return 0;
849 }
850
851 Mutex::Autolock _l(mLock);
852
853 RecordThread *recordThread = checkRecordThread_l(ioHandle);
854 if (recordThread != NULL) {
855 return recordThread->getInputFramesLost();
856 }
857 return 0;
858}
859
Eric Laurent415f3e22009-10-21 08:14:22 -0700860status_t AudioFlinger::setVoiceVolume(float value)
861{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700862 status_t ret = initCheck();
863 if (ret != NO_ERROR) {
864 return ret;
865 }
866
Eric Laurent415f3e22009-10-21 08:14:22 -0700867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
872 AutoMutex lock(mHardwareLock);
873 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700874 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700875 mHardwareStatus = AUDIO_HW_IDLE;
876
877 return ret;
878}
879
Eric Laurent0986e792010-01-19 17:37:09 -0800880status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
881{
882 status_t status;
883
884 Mutex::Autolock _l(mLock);
885
886 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
887 if (playbackThread != NULL) {
888 return playbackThread->getRenderPosition(halFrames, dspFrames);
889 }
890
891 return BAD_VALUE;
892}
893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
895{
Eric Laurenta553c252009-07-17 12:17:14 -0700896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 Mutex::Autolock _l(mLock);
898
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700899 int pid = IPCThreadState::self()->getCallingPid();
900 if (mNotificationClients.indexOfKey(pid) < 0) {
901 sp<NotificationClient> notificationClient = new NotificationClient(this,
902 client,
903 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100904 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700905
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700906 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700907
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700908 sp<IBinder> binder = client->asBinder();
909 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700911 // the config change is always sent from playback or record threads to avoid deadlock
912 // with AudioSystem::gLock
913 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
914 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
915 }
Eric Laurenta553c252009-07-17 12:17:14 -0700916
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700917 for (size_t i = 0; i < mRecordThreads.size(); i++) {
918 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
920 }
921}
922
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700923void AudioFlinger::removeNotificationClient(pid_t pid)
924{
925 Mutex::Autolock _l(mLock);
926
927 int index = mNotificationClients.indexOfKey(pid);
928 if (index >= 0) {
929 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100930 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700931 mNotificationClients.removeItem(pid);
932 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700933
Steve Block71f2cf12011-10-20 11:56:00 +0100934 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700935 int num = mAudioSessionRefs.size();
936 bool removed = false;
937 for (int i = 0; i< num; i++) {
938 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100939 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700940 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100941 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700942 mAudioSessionRefs.removeAt(i);
943 delete ref;
944 removed = true;
945 i--;
946 num--;
947 }
948 }
949 if (removed) {
950 purgeStaleEffects_l();
951 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700952}
953
Eric Laurent296a0ec2009-09-15 07:10:12 -0700954// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700955void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
956{
Eric Laurent49f02be2009-11-19 09:00:56 -0800957 size_t size = mNotificationClients.size();
958 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700959 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700960 }
961}
962
Eric Laurentb9481d82009-09-17 05:12:56 -0700963// removeClient_l() must be called with AudioFlinger::mLock held
964void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965{
Steve Block71f2cf12011-10-20 11:56:00 +0100966 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 -0700967 mClients.removeItem(pid);
968}
969
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700970
Eric Laurenta553c252009-07-17 12:17:14 -0700971// ----------------------------------------------------------------------------
972
Eric Laurent464d5b32011-06-17 21:29:58 -0700973AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700974 : Thread(false),
975 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700976 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
977 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700978{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700979 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980}
981
Eric Laurenta553c252009-07-17 12:17:14 -0700982AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700984 mParamCond.broadcast();
985 mNewParameters.clear();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700986 // do not lock the mutex in destructor
987 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -0700988 if (mPowerManager != 0) {
989 sp<IBinder> binder = mPowerManager->asBinder();
990 binder->unlinkToDeath(mDeathRecipient);
991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992}
993
Eric Laurenta553c252009-07-17 12:17:14 -0700994void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700995{
Eric Laurentb7d94602009-09-29 11:12:57 -0700996 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700997 // destroyed in the middle of requestExitAndWait()
998 sp <ThreadBase> strongMe = this;
999
Steve Block71f2cf12011-10-20 11:56:00 +01001000 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001001 {
1002 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001003 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001004 requestExit();
1005 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001006 }
Eric Laurenta553c252009-07-17 12:17:14 -07001007 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001008}
Eric Laurenta553c252009-07-17 12:17:14 -07001009
1010uint32_t AudioFlinger::ThreadBase::sampleRate() const
1011{
1012 return mSampleRate;
1013}
1014
1015int AudioFlinger::ThreadBase::channelCount() const
1016{
Eric Laurentb0a01472010-05-14 05:45:46 -07001017 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001018}
1019
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001020uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001021{
1022 return mFormat;
1023}
1024
1025size_t AudioFlinger::ThreadBase::frameCount() const
1026{
1027 return mFrameCount;
1028}
1029
1030status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1031{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001032 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001033
Steve Block71f2cf12011-10-20 11:56:00 +01001034 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001035 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001036
Eric Laurent8fce46a2009-08-04 09:45:33 -07001037 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001038 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001039 // wait condition with timeout in case the thread loop has exited
1040 // before the request could be processed
Eric Laurent5f37be32011-09-13 11:40:21 -07001041 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001042 status = mParamStatus;
1043 mWaitWorkCV.signal();
1044 } else {
1045 status = TIMED_OUT;
1046 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001047 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001048}
1049
1050void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1051{
1052 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001053 sendConfigEvent_l(event, param);
1054}
1055
1056// sendConfigEvent_l() must be called with ThreadBase::mLock held
1057void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1058{
Eric Laurenta553c252009-07-17 12:17:14 -07001059 ConfigEvent *configEvent = new ConfigEvent();
1060 configEvent->mEvent = event;
1061 configEvent->mParam = param;
1062 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001063 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001064 mWaitWorkCV.signal();
1065}
1066
1067void AudioFlinger::ThreadBase::processConfigEvents()
1068{
1069 mLock.lock();
1070 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001071 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001072 ConfigEvent *configEvent = mConfigEvents[0];
1073 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001074 // release mLock before locking AudioFlinger mLock: lock order is always
1075 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001076 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001077 mAudioFlinger->mLock.lock();
1078 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1079 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001080 delete configEvent;
1081 mLock.lock();
1082 }
1083 mLock.unlock();
1084}
1085
Eric Laurent3fdb1262009-11-07 00:01:32 -08001086status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1087{
1088 const size_t SIZE = 256;
1089 char buffer[SIZE];
1090 String8 result;
1091
1092 bool locked = tryLock(mLock);
1093 if (!locked) {
1094 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1095 write(fd, buffer, strlen(buffer));
1096 }
1097
1098 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1103 result.append(buffer);
1104 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1105 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001106 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1107 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001108 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1111 result.append(buffer);
1112
1113 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1114 result.append(buffer);
1115 result.append(" Index Command");
1116 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1117 snprintf(buffer, SIZE, "\n %02d ", i);
1118 result.append(buffer);
1119 result.append(mNewParameters[i]);
1120 }
1121
1122 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1123 result.append(buffer);
1124 snprintf(buffer, SIZE, " Index event param\n");
1125 result.append(buffer);
1126 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1127 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1128 result.append(buffer);
1129 }
1130 result.append("\n");
1131
1132 write(fd, result.string(), result.size());
1133
1134 if (locked) {
1135 mLock.unlock();
1136 }
1137 return NO_ERROR;
1138}
1139
Eric Laurent1345d332011-07-24 17:49:51 -07001140status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1141{
1142 const size_t SIZE = 256;
1143 char buffer[SIZE];
1144 String8 result;
1145
1146 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1147 write(fd, buffer, strlen(buffer));
1148
1149 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1150 sp<EffectChain> chain = mEffectChains[i];
1151 if (chain != 0) {
1152 chain->dump(fd, args);
1153 }
1154 }
1155 return NO_ERROR;
1156}
1157
Eric Laurent6dbdc402011-07-22 09:04:31 -07001158void AudioFlinger::ThreadBase::acquireWakeLock()
1159{
1160 Mutex::Autolock _l(mLock);
1161 acquireWakeLock_l();
1162}
1163
1164void AudioFlinger::ThreadBase::acquireWakeLock_l()
1165{
1166 if (mPowerManager == 0) {
1167 // use checkService() to avoid blocking if power service is not up yet
1168 sp<IBinder> binder =
1169 defaultServiceManager()->checkService(String16("power"));
1170 if (binder == 0) {
1171 LOGW("Thread %s cannot connect to the power manager service", mName);
1172 } else {
1173 mPowerManager = interface_cast<IPowerManager>(binder);
1174 binder->linkToDeath(mDeathRecipient);
1175 }
1176 }
1177 if (mPowerManager != 0) {
1178 sp<IBinder> binder = new BBinder();
1179 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1180 binder,
1181 String16(mName));
1182 if (status == NO_ERROR) {
1183 mWakeLockToken = binder;
1184 }
Steve Block71f2cf12011-10-20 11:56:00 +01001185 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001186 }
1187}
1188
1189void AudioFlinger::ThreadBase::releaseWakeLock()
1190{
1191 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001192 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001193}
1194
1195void AudioFlinger::ThreadBase::releaseWakeLock_l()
1196{
1197 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001198 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001199 if (mPowerManager != 0) {
1200 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1201 }
1202 mWakeLockToken.clear();
1203 }
1204}
1205
1206void AudioFlinger::ThreadBase::clearPowerManager()
1207{
1208 Mutex::Autolock _l(mLock);
1209 releaseWakeLock_l();
1210 mPowerManager.clear();
1211}
1212
1213void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1214{
1215 sp<ThreadBase> thread = mThread.promote();
1216 if (thread != 0) {
1217 thread->clearPowerManager();
1218 }
1219 LOGW("power manager service died !!!");
1220}
Eric Laurent1345d332011-07-24 17:49:51 -07001221
Eric Laurentf82fccd2011-07-27 19:49:51 -07001222void AudioFlinger::ThreadBase::setEffectSuspended(
1223 const effect_uuid_t *type, bool suspend, int sessionId)
1224{
1225 Mutex::Autolock _l(mLock);
1226 setEffectSuspended_l(type, suspend, sessionId);
1227}
1228
1229void AudioFlinger::ThreadBase::setEffectSuspended_l(
1230 const effect_uuid_t *type, bool suspend, int sessionId)
1231{
1232 sp<EffectChain> chain;
1233 chain = getEffectChain_l(sessionId);
1234 if (chain != 0) {
1235 if (type != NULL) {
1236 chain->setEffectSuspended_l(type, suspend);
1237 } else {
1238 chain->setEffectSuspendedAll_l(suspend);
1239 }
1240 }
1241
1242 updateSuspendedSessions_l(type, suspend, sessionId);
1243}
1244
1245void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1246{
1247 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1248 if (index < 0) {
1249 return;
1250 }
1251
1252 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1253 mSuspendedSessions.editValueAt(index);
1254
1255 for (size_t i = 0; i < sessionEffects.size(); i++) {
1256 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1257 for (int j = 0; j < desc->mRefCount; j++) {
1258 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1259 chain->setEffectSuspendedAll_l(true);
1260 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001261 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001262 desc->mType.timeLow);
1263 chain->setEffectSuspended_l(&desc->mType, true);
1264 }
1265 }
1266 }
1267}
1268
Eric Laurentf82fccd2011-07-27 19:49:51 -07001269void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1270 bool suspend,
1271 int sessionId)
1272{
1273 int index = mSuspendedSessions.indexOfKey(sessionId);
1274
1275 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1276
1277 if (suspend) {
1278 if (index >= 0) {
1279 sessionEffects = mSuspendedSessions.editValueAt(index);
1280 } else {
1281 mSuspendedSessions.add(sessionId, sessionEffects);
1282 }
1283 } else {
1284 if (index < 0) {
1285 return;
1286 }
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 }
1289
1290
1291 int key = EffectChain::kKeyForSuspendAll;
1292 if (type != NULL) {
1293 key = type->timeLow;
1294 }
1295 index = sessionEffects.indexOfKey(key);
1296
1297 sp <SuspendedSessionDesc> desc;
1298 if (suspend) {
1299 if (index >= 0) {
1300 desc = sessionEffects.valueAt(index);
1301 } else {
1302 desc = new SuspendedSessionDesc();
1303 if (type != NULL) {
1304 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1305 }
1306 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001307 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001308 }
1309 desc->mRefCount++;
1310 } else {
1311 if (index < 0) {
1312 return;
1313 }
1314 desc = sessionEffects.valueAt(index);
1315 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001316 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001317 sessionEffects.removeItemsAt(index);
1318 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001319 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001320 sessionId);
1321 mSuspendedSessions.removeItem(sessionId);
1322 }
1323 }
1324 }
1325 if (!sessionEffects.isEmpty()) {
1326 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1327 }
1328}
1329
1330void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1331 bool enabled,
1332 int sessionId)
1333{
1334 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001335 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1336}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001337
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001338void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1339 bool enabled,
1340 int sessionId)
1341{
Eric Laurent6752ec82011-08-10 10:37:50 -07001342 if (mType != RECORD) {
1343 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1344 // another session. This gives the priority to well behaved effect control panels
1345 // and applications not using global effects.
1346 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1347 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1348 }
1349 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001350
1351 sp<EffectChain> chain = getEffectChain_l(sessionId);
1352 if (chain != 0) {
1353 chain->checkSuspendOnEffectEnabled(effect, enabled);
1354 }
1355}
1356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357// ----------------------------------------------------------------------------
1358
Eric Laurent464d5b32011-06-17 21:29:58 -07001359AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1360 AudioStreamOut* output,
1361 int id,
1362 uint32_t device)
1363 : ThreadBase(audioFlinger, id, device),
Eric Laurentd5603c12009-08-06 08:49:39 -07001364 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001365 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001367 snprintf(mName, kNameLength, "AudioOut_%d", id);
1368
Eric Laurenta553c252009-07-17 12:17:14 -07001369 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370
Eric Laurenta553c252009-07-17 12:17:14 -07001371 mMasterVolume = mAudioFlinger->masterVolume();
1372 mMasterMute = mAudioFlinger->masterMute();
1373
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001374 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001375 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1376 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001377 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379}
1380
Eric Laurenta553c252009-07-17 12:17:14 -07001381AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382{
1383 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384}
1385
Eric Laurenta553c252009-07-17 12:17:14 -07001386status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387{
1388 dumpInternals(fd, args);
1389 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001390 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 return NO_ERROR;
1392}
1393
Eric Laurenta553c252009-07-17 12:17:14 -07001394status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395{
1396 const size_t SIZE = 256;
1397 char buffer[SIZE];
1398 String8 result;
1399
Eric Laurenta553c252009-07-17 12:17:14 -07001400 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001402 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 -08001403 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001404 sp<Track> track = mTracks[i];
1405 if (track != 0) {
1406 track->dump(buffer, SIZE);
1407 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409 }
1410
Eric Laurenta553c252009-07-17 12:17:14 -07001411 snprintf(buffer, SIZE, "Output thread %p active 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 < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001415 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 if (wTrack != 0) {
1417 sp<Track> track = wTrack.promote();
1418 if (track != 0) {
1419 track->dump(buffer, SIZE);
1420 result.append(buffer);
1421 }
1422 }
1423 }
1424 write(fd, result.string(), result.size());
1425 return NO_ERROR;
1426}
1427
Eric Laurenta553c252009-07-17 12:17:14 -07001428status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429{
1430 const size_t SIZE = 256;
1431 char buffer[SIZE];
1432 String8 result;
1433
Eric Laurent3fdb1262009-11-07 00:01:32 -08001434 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 result.append(buffer);
1436 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1437 result.append(buffer);
1438 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1439 result.append(buffer);
1440 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1441 result.append(buffer);
1442 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1443 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001444 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1445 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001446 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1447 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001449
1450 dumpBase(fd, args);
1451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 return NO_ERROR;
1453}
1454
1455// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001456status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457{
Eric Laurent828b9772011-08-07 16:32:26 -07001458 status_t status = initCheck();
1459 if (status == NO_ERROR) {
1460 LOGI("AudioFlinger's thread %p ready to run", this);
1461 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 LOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
Eric Laurent828b9772011-08-07 16:32:26 -07001464 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465}
1466
Eric Laurenta553c252009-07-17 12:17:14 -07001467void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001469 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470}
1471
Eric Laurenta553c252009-07-17 12:17:14 -07001472// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1473sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 const sp<AudioFlinger::Client>& client,
1475 int streamType,
1476 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001477 uint32_t format,
1478 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 int frameCount,
1480 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001481 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 status_t *status)
1483{
1484 sp<Track> track;
1485 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001486
1487 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001488 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1489 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1490 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1491 "for output %p with format %d",
1492 sampleRate, format, channelMask, mOutput, mFormat);
1493 lStatus = BAD_VALUE;
1494 goto Exit;
1495 }
Eric Laurenta553c252009-07-17 12:17:14 -07001496 }
1497 } else {
1498 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1499 if (sampleRate > mSampleRate*2) {
1500 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1501 lStatus = BAD_VALUE;
1502 goto Exit;
1503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505
Eric Laurent464d5b32011-06-17 21:29:58 -07001506 lStatus = initCheck();
1507 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001508 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001509 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511
Eric Laurenta553c252009-07-17 12:17:14 -07001512 { // scope for mLock
1513 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001514
1515 // all tracks in same audio session must share the same routing strategy otherwise
1516 // conflicts will happen when tracks are moved from one output to another by audio policy
1517 // manager
1518 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001519 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001520 for (size_t i = 0; i < mTracks.size(); ++i) {
1521 sp<Track> t = mTracks[i];
1522 if (t != 0) {
1523 if (sessionId == t->sessionId() &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001524 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001525 lStatus = BAD_VALUE;
1526 goto Exit;
1527 }
1528 }
1529 }
1530
Eric Laurenta553c252009-07-17 12:17:14 -07001531 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001532 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001533 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001534 lStatus = NO_MEMORY;
1535 goto Exit;
1536 }
1537 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001538
1539 sp<EffectChain> chain = getEffectChain_l(sessionId);
1540 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001541 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001542 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001543 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001544 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001545 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001546
1547 // invalidate track immediately if the stream type was moved to another thread since
1548 // createTrack() was called by the client process.
1549 if (!mStreamTypes[streamType].valid) {
1550 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1551 this, streamType);
1552 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1553 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001554 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001555 lStatus = NO_ERROR;
1556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557Exit:
1558 if(status) {
1559 *status = lStatus;
1560 }
1561 return track;
1562}
1563
Eric Laurenta553c252009-07-17 12:17:14 -07001564uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565{
Eric Laurent828b9772011-08-07 16:32:26 -07001566 Mutex::Autolock _l(mLock);
1567 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001568 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001569 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 return 0;
1571 }
1572}
1573
Eric Laurenta553c252009-07-17 12:17:14 -07001574status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575{
1576 mMasterVolume = value;
1577 return NO_ERROR;
1578}
1579
Eric Laurenta553c252009-07-17 12:17:14 -07001580status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581{
1582 mMasterMute = muted;
1583 return NO_ERROR;
1584}
1585
Eric Laurenta553c252009-07-17 12:17:14 -07001586float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587{
1588 return mMasterVolume;
1589}
1590
Eric Laurenta553c252009-07-17 12:17:14 -07001591bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592{
1593 return mMasterMute;
1594}
1595
Eric Laurenta553c252009-07-17 12:17:14 -07001596status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597{
1598 mStreamTypes[stream].volume = value;
1599 return NO_ERROR;
1600}
1601
Eric Laurenta553c252009-07-17 12:17:14 -07001602status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603{
1604 mStreamTypes[stream].mute = muted;
1605 return NO_ERROR;
1606}
1607
Eric Laurenta553c252009-07-17 12:17:14 -07001608float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609{
1610 return mStreamTypes[stream].volume;
1611}
1612
Eric Laurenta553c252009-07-17 12:17:14 -07001613bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614{
1615 return mStreamTypes[stream].mute;
1616}
1617
Eric Laurenta553c252009-07-17 12:17:14 -07001618// addTrack_l() must be called with ThreadBase::mLock held
1619status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620{
1621 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001622
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001623 // set retry count for buffer fill
1624 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001625 if (mActiveTracks.indexOf(track) < 0) {
1626 // the track is newly added, make sure it fills up all its
1627 // buffers before playing. This is to ensure the client will
1628 // effectively get the latency it requested.
1629 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001630 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001631 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001632 if (track->mainBuffer() != mMixBuffer) {
1633 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1634 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001635 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001636 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001637 }
1638 }
1639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001641 }
Eric Laurenta553c252009-07-17 12:17:14 -07001642
Steve Block71f2cf12011-10-20 11:56:00 +01001643 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001644 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645
1646 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001647}
1648
Eric Laurenta553c252009-07-17 12:17:14 -07001649// destroyTrack_l() must be called with ThreadBase::mLock held
1650void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001651{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001652 track->mState = TrackBase::TERMINATED;
1653 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001654 removeTrack_l(track);
1655 }
1656}
1657
1658void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1659{
1660 mTracks.remove(track);
1661 deleteTrackName_l(track->name());
1662 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1663 if (chain != 0) {
1664 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001665 }
1666}
1667
Eric Laurenta553c252009-07-17 12:17:14 -07001668String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001669{
Eric Laurent828b9772011-08-07 16:32:26 -07001670 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001671 char *s;
1672
Eric Laurent828b9772011-08-07 16:32:26 -07001673 Mutex::Autolock _l(mLock);
1674 if (initCheck() != NO_ERROR) {
1675 return out_s8;
1676 }
1677
Dima Zavin31f188892011-04-18 16:57:27 -07001678 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001679 out_s8 = String8(s);
1680 free(s);
1681 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001682}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001683
Eric Laurent828b9772011-08-07 16:32:26 -07001684// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001685void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001686 AudioSystem::OutputDescriptor desc;
1687 void *param2 = 0;
1688
Steve Block71f2cf12011-10-20 11:56:00 +01001689 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001690
1691 switch (event) {
1692 case AudioSystem::OUTPUT_OPENED:
1693 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001694 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001695 desc.samplingRate = mSampleRate;
1696 desc.format = mFormat;
1697 desc.frameCount = mFrameCount;
1698 desc.latency = latency();
1699 param2 = &desc;
1700 break;
1701
1702 case AudioSystem::STREAM_CONFIG_CHANGED:
1703 param2 = &param;
1704 case AudioSystem::OUTPUT_CLOSED:
1705 default:
1706 break;
1707 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001708 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001709}
1710
1711void AudioFlinger::PlaybackThread::readOutputParameters()
1712{
Dima Zavin31f188892011-04-18 16:57:27 -07001713 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001714 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1715 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001716 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1717 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1718 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001719
Eric Laurenta553c252009-07-17 12:17:14 -07001720 // FIXME - Current mixer implementation only supports stereo output: Always
1721 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001722 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001723 mMixBuffer = new int16_t[mFrameCount * 2];
1724 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001725
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001726 // force reconfiguration of effect chains and engines to take new buffer size and audio
1727 // parameters into account
1728 // Note that mLock is not held when readOutputParameters() is called from the constructor
1729 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1730 // matter.
1731 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1732 Vector< sp<EffectChain> > effectChains = mEffectChains;
1733 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001734 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001735 }
Eric Laurenta553c252009-07-17 12:17:14 -07001736}
1737
Eric Laurent0986e792010-01-19 17:37:09 -08001738status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1739{
1740 if (halFrames == 0 || dspFrames == 0) {
1741 return BAD_VALUE;
1742 }
Eric Laurent828b9772011-08-07 16:32:26 -07001743 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001744 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001745 return INVALID_OPERATION;
1746 }
Dima Zavin31f188892011-04-18 16:57:27 -07001747 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001748
Dima Zavin31f188892011-04-18 16:57:27 -07001749 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001750}
1751
Eric Laurent493941b2010-07-28 01:32:47 -07001752uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001753{
1754 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001755 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001756 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001757 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001758 }
1759
1760 for (size_t i = 0; i < mTracks.size(); ++i) {
1761 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001762 if (sessionId == track->sessionId() &&
1763 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001764 result |= TRACK_SESSION;
1765 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001766 }
1767 }
1768
Eric Laurent493941b2010-07-28 01:32:47 -07001769 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001770}
1771
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001772uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1773{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001774 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001775 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001776 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1777 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001778 }
1779 for (size_t i = 0; i < mTracks.size(); i++) {
1780 sp<Track> track = mTracks[i];
1781 if (sessionId == track->sessionId() &&
1782 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001783 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001784 }
1785 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001786 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001787}
1788
Eric Laurent53334cd2010-06-23 17:38:20 -07001789
Eric Laurent828b9772011-08-07 16:32:26 -07001790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1791{
1792 Mutex::Autolock _l(mLock);
1793 return mOutput;
1794}
1795
1796AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1797{
1798 Mutex::Autolock _l(mLock);
1799 AudioStreamOut *output = mOutput;
1800 mOutput = NULL;
1801 return output;
1802}
1803
1804// this method must always be called either with ThreadBase mLock held or inside the thread loop
1805audio_stream_t* AudioFlinger::PlaybackThread::stream()
1806{
1807 if (mOutput == NULL) {
1808 return NULL;
1809 }
1810 return &mOutput->stream->common;
1811}
1812
Eric Laurenta553c252009-07-17 12:17:14 -07001813// ----------------------------------------------------------------------------
1814
Dima Zavin31f188892011-04-18 16:57:27 -07001815AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001816 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001817 mAudioMixer(0)
1818{
Eric Laurent464d5b32011-06-17 21:29:58 -07001819 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001820 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1821
1822 // FIXME - Current mixer implementation only supports stereo output
1823 if (mChannelCount == 1) {
1824 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001826}
1827
Eric Laurenta553c252009-07-17 12:17:14 -07001828AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001829{
Eric Laurenta553c252009-07-17 12:17:14 -07001830 delete mAudioMixer;
1831}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832
Eric Laurenta553c252009-07-17 12:17:14 -07001833bool AudioFlinger::MixerThread::threadLoop()
1834{
Eric Laurenta553c252009-07-17 12:17:14 -07001835 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001836 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001837 nsecs_t standbyTime = systemTime();
1838 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001839 // FIXME: Relaxed timing because of a certain device that can't meet latency
1840 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001841 // increase threshold again due to low power audio mode. The way this warning threshold is
1842 // calculated and its usefulness should be reconsidered anyway.
1843 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001844 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001845 bool longStandbyExit = false;
1846 uint32_t activeSleepTime = activeSleepTimeUs();
1847 uint32_t idleSleepTime = idleSleepTimeUs();
1848 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001849 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001850#ifdef DEBUG_CPU_USAGE
1851 ThreadCpuUsage cpu;
1852 const CentralTendencyStatistics& stats = cpu.statistics();
1853#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854
Eric Laurent6dbdc402011-07-22 09:04:31 -07001855 acquireWakeLock();
1856
Eric Laurenta553c252009-07-17 12:17:14 -07001857 while (!exitPending())
1858 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001859#ifdef DEBUG_CPU_USAGE
1860 cpu.sampleAndEnable();
1861 unsigned n = stats.n();
1862 // cpu.elapsed() is expensive, so don't call it every loop
1863 if ((n & 127) == 1) {
1864 long long elapsed = cpu.elapsed();
1865 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1866 double perLoop = elapsed / (double) n;
1867 double perLoop100 = perLoop * 0.01;
1868 double mean = stats.mean();
1869 double stddev = stats.stddev();
1870 double minimum = stats.minimum();
1871 double maximum = stats.maximum();
1872 cpu.resetStatistics();
1873 LOGI("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",
1874 elapsed * .000000001, n, perLoop * .000001,
1875 mean * .001,
1876 stddev * .001,
1877 minimum * .001,
1878 maximum * .001,
1879 mean / perLoop100,
1880 stddev / perLoop100,
1881 minimum / perLoop100,
1882 maximum / perLoop100);
1883 }
1884 }
1885#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001886 processConfigEvents();
1887
Eric Laurent059b4be2009-11-09 23:32:22 -08001888 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001889 { // scope for mLock
1890
1891 Mutex::Autolock _l(mLock);
1892
1893 if (checkForNewParameters_l()) {
1894 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001895 // FIXME: Relaxed timing because of a certain device that can't meet latency
1896 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001897 // increase threshold again due to low power audio mode. The way this warning
1898 // threshold is calculated and its usefulness should be reconsidered anyway.
1899 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001900 activeSleepTime = activeSleepTimeUs();
1901 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001902 }
1903
1904 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1905
1906 // put audio hardware into standby after short delay
1907 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1908 mSuspended) {
1909 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001910 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001911 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001912 mStandby = true;
1913 mBytesWritten = 0;
1914 }
1915
1916 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1917 // we're about to wait, flush the binder command buffer
1918 IPCThreadState::self()->flushCommands();
1919
1920 if (exitPending()) break;
1921
Eric Laurent6dbdc402011-07-22 09:04:31 -07001922 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001923 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001924 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001925 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001926 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001927 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001928
1929 if (mMasterMute == false) {
1930 char value[PROPERTY_VALUE_MAX];
1931 property_get("ro.audio.silent", value, "0");
1932 if (atoi(value)) {
1933 LOGD("Silence is golden");
1934 setMasterMute(true);
1935 }
1936 }
1937
1938 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001939 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001940 continue;
1941 }
1942 }
1943
Eric Laurent059b4be2009-11-09 23:32:22 -08001944 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001945
1946 // prevent any changes in effect chain list and in each effect chain
1947 // during mixing and effect process as the audio buffers could be deleted
1948 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001949 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001950 }
1951
Eric Laurent059b4be2009-11-09 23:32:22 -08001952 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001953 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001954 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001955 sleepTime = 0;
1956 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001957 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001958 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001959 // If no tracks are ready, sleep once for the duration of an output
1960 // buffer size, then write 0s to the output
1961 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001962 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1963 sleepTime = activeSleepTime;
1964 } else {
1965 sleepTime = idleSleepTime;
1966 }
1967 } else if (mBytesWritten != 0 ||
1968 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001969 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001970 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01001971 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001972 }
Eric Laurent65b65452010-06-01 23:49:17 -07001973 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001974 }
1975
1976 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001977 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001978 }
1979 // sleepTime == 0 means we must write to audio hardware
1980 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001981 for (size_t i = 0; i < effectChains.size(); i ++) {
1982 effectChains[i]->process_l();
1983 }
1984 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001985 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07001986 mLastWriteTime = systemTime();
1987 mInWrite = true;
1988 mBytesWritten += mixBufferSize;
1989
Dima Zavin31f188892011-04-18 16:57:27 -07001990 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001991 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001992 mNumWrites++;
1993 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001994 nsecs_t now = systemTime();
1995 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07001996 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001997 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001998 if ((now - lastWarning) > kWarningThrottle) {
1999 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2000 ns2ms(delta), mNumDelayedWrites, this);
2001 lastWarning = now;
2002 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002003 if (mStandby) {
2004 longStandbyExit = true;
2005 }
Eric Laurenta553c252009-07-17 12:17:14 -07002006 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002007 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002008 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002009 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002010 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002011 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002012 }
2013
2014 // finally let go of all our tracks, without the lock held
2015 // since we can't guarantee the destructors won't acquire that
2016 // same lock.
2017 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002018
2019 // Effect chains will be actually deleted here if they were removed from
2020 // mEffectChains list during mixing or effects processing
2021 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002022 }
2023
2024 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002025 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002026 }
Eric Laurenta553c252009-07-17 12:17:14 -07002027
Eric Laurent6dbdc402011-07-22 09:04:31 -07002028 releaseWakeLock();
2029
Steve Block71f2cf12011-10-20 11:56:00 +01002030 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002031 return false;
2032}
2033
2034// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002035uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002036{
2037
Eric Laurent059b4be2009-11-09 23:32:22 -08002038 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002039 // find out which tracks need to be processed
2040 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002041 size_t mixedTracks = 0;
2042 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002043
2044 float masterVolume = mMasterVolume;
2045 bool masterMute = mMasterMute;
2046
Eric Laurent8cc93b92010-08-11 05:20:11 -07002047 if (masterMute) {
2048 masterVolume = 0;
2049 }
Eric Laurent65b65452010-06-01 23:49:17 -07002050 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002051 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002052 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002053 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002054 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002055 masterVolume = (float)((v + (1 << 23)) >> 24);
2056 chain.clear();
2057 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002058
Eric Laurenta553c252009-07-17 12:17:14 -07002059 for (size_t i=0 ; i<count ; i++) {
2060 sp<Track> t = activeTracks[i].promote();
2061 if (t == 0) continue;
2062
2063 Track* const track = t.get();
2064 audio_track_cblk_t* cblk = track->cblk();
2065
2066 // The first time a track is added we wait
2067 // for all its buffers to be filled before processing it
2068 mAudioMixer->setActiveTrack(track->name());
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002069 // make sure that we have enough frames to mix one full buffer
2070 uint32_t minFrames = 1;
2071 if (!track->isStopped() && !track->isPausing()) {
2072 if (t->sampleRate() == (int)mSampleRate) {
2073 minFrames = mFrameCount;
2074 } else {
2075 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1;
2076 }
2077 }
2078 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002079 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002080 {
Steve Block71f2cf12011-10-20 11:56:00 +01002081 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002082
Eric Laurent65b65452010-06-01 23:49:17 -07002083 mixedTracks++;
2084
2085 // track->mainBuffer() != mMixBuffer means there is an effect chain
2086 // connected to the track
2087 chain.clear();
2088 if (track->mainBuffer() != mMixBuffer) {
2089 chain = getEffectChain_l(track->sessionId());
2090 // Delegate volume control to effect in track effect chain if needed
2091 if (chain != 0) {
2092 tracksWithEffect++;
2093 } else {
2094 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2095 track->name(), track->sessionId());
2096 }
2097 }
2098
2099
2100 int param = AudioMixer::VOLUME;
2101 if (track->mFillingUpStatus == Track::FS_FILLED) {
2102 // no ramp for the first volume setting
2103 track->mFillingUpStatus = Track::FS_ACTIVE;
2104 if (track->mState == TrackBase::RESUMING) {
2105 track->mState = TrackBase::ACTIVE;
2106 param = AudioMixer::RAMP_VOLUME;
2107 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08002108 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002109 } else if (cblk->server != 0) {
2110 // If the track is stopped before the first frame was mixed,
2111 // do not apply ramp
2112 param = AudioMixer::RAMP_VOLUME;
2113 }
2114
Eric Laurenta553c252009-07-17 12:17:14 -07002115 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002116 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002117 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002118 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002119 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002120 if (track->isPausing()) {
2121 track->setPaused();
2122 }
2123 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002124
Glenn Kasten871c16c2010-03-05 12:18:01 -08002125 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002126 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002127 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002128 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2129 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002130
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002131 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002132 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002133 // Delegate volume control to effect in track effect chain if needed
2134 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2135 // Do not ramp volume if volume is controlled by effect
2136 param = AudioMixer::VOLUME;
2137 track->mHasVolumeController = true;
2138 } else {
2139 // force no volume ramp when volume controller was just disabled or removed
2140 // from effect chain to avoid volume spike
2141 if (track->mHasVolumeController) {
2142 param = AudioMixer::VOLUME;
2143 }
2144 track->mHasVolumeController = false;
2145 }
2146
2147 // Convert volumes from 8.24 to 4.12 format
2148 int16_t left, right, aux;
2149 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2150 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2151 left = int16_t(v_clamped);
2152 v_clamped = (vr + (1 << 11)) >> 12;
2153 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2154 right = int16_t(v_clamped);
2155
2156 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2157 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002158
Eric Laurent65b65452010-06-01 23:49:17 -07002159 // XXX: these things DON'T need to be done each time
2160 mAudioMixer->setBufferProvider(track);
2161 mAudioMixer->enable(AudioMixer::MIXING);
2162
2163 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2164 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2165 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002166 mAudioMixer->setParameter(
2167 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002168 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002169 mAudioMixer->setParameter(
2170 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002171 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002172 mAudioMixer->setParameter(
2173 AudioMixer::RESAMPLE,
2174 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002175 (void *)(cblk->sampleRate));
2176 mAudioMixer->setParameter(
2177 AudioMixer::TRACK,
2178 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2179 mAudioMixer->setParameter(
2180 AudioMixer::TRACK,
2181 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002182
2183 // reset retry count
2184 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002185 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002186 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002187 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002188 if (track->isStopped()) {
2189 track->reset();
2190 }
2191 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2192 // We have consumed all the buffers of this track.
2193 // Remove it from the list of active tracks.
2194 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002195 } else {
2196 // No buffers for this track. Give it a few chances to
2197 // fill a buffer, then remove it from active list.
2198 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002199 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002200 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002201 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002202 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002203 } else if (mixerStatus != MIXER_TRACKS_READY) {
2204 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002205 }
Eric Laurenta553c252009-07-17 12:17:14 -07002206 }
Eric Laurent65b65452010-06-01 23:49:17 -07002207 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07002208 }
2209 }
2210
2211 // remove all the tracks that need to be...
2212 count = tracksToRemove->size();
2213 if (UNLIKELY(count)) {
2214 for (size_t i=0 ; i<count ; i++) {
2215 const sp<Track>& track = tracksToRemove->itemAt(i);
2216 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002217 if (track->mainBuffer() != mMixBuffer) {
2218 chain = getEffectChain_l(track->sessionId());
2219 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002220 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002221 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002222 }
2223 }
Eric Laurenta553c252009-07-17 12:17:14 -07002224 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002225 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002226 }
2227 }
2228 }
2229
Eric Laurent65b65452010-06-01 23:49:17 -07002230 // mix buffer must be cleared if all tracks are connected to an
2231 // effect chain as in this case the mixer will not write to
2232 // mix buffer and track effects will accumulate into it
2233 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2234 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2235 }
2236
Eric Laurent059b4be2009-11-09 23:32:22 -08002237 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002238}
2239
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002240void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002241{
Steve Block71f2cf12011-10-20 11:56:00 +01002242 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002243 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002244 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002245
Eric Laurenta553c252009-07-17 12:17:14 -07002246 size_t size = mTracks.size();
2247 for (size_t i = 0; i < size; i++) {
2248 sp<Track> t = mTracks[i];
2249 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002250 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002251 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002252 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002253 }
2254}
Eric Laurenta553c252009-07-17 12:17:14 -07002255
Eric Laurent05ce0942011-08-30 10:18:54 -07002256void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2257{
Steve Block71f2cf12011-10-20 11:56:00 +01002258 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002259 this, streamType, valid);
2260 Mutex::Autolock _l(mLock);
2261
2262 mStreamTypes[streamType].valid = valid;
2263}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264
Eric Laurenta553c252009-07-17 12:17:14 -07002265// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002266int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267{
2268 return mAudioMixer->getTrackName();
2269}
2270
Eric Laurenta553c252009-07-17 12:17:14 -07002271// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002272void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273{
Steve Block71f2cf12011-10-20 11:56:00 +01002274 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 mAudioMixer->deleteTrackName(name);
2276}
2277
Eric Laurenta553c252009-07-17 12:17:14 -07002278// checkForNewParameters_l() must be called with ThreadBase::mLock held
2279bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280{
Eric Laurenta553c252009-07-17 12:17:14 -07002281 bool reconfig = false;
2282
Eric Laurent8fce46a2009-08-04 09:45:33 -07002283 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002284 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002285 String8 keyValuePair = mNewParameters[0];
2286 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002287 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002288
Eric Laurenta553c252009-07-17 12:17:14 -07002289 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2290 reconfig = true;
2291 }
2292 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002293 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002294 status = BAD_VALUE;
2295 } else {
2296 reconfig = true;
2297 }
2298 }
2299 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002300 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002301 status = BAD_VALUE;
2302 } else {
2303 reconfig = true;
2304 }
2305 }
2306 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2307 // do not accept frame count changes if tracks are open as the track buffer
2308 // size depends on frame count and correct behavior would not be garantied
2309 // if frame count is changed after track creation
2310 if (!mTracks.isEmpty()) {
2311 status = INVALID_OPERATION;
2312 } else {
2313 reconfig = true;
2314 }
2315 }
Eric Laurent65b65452010-06-01 23:49:17 -07002316 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002317 // when changing the audio output device, call addBatteryData to notify
2318 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002319 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002320 uint32_t params = 0;
2321 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002322 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002323 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2324 }
2325
2326 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002327 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002328 // check if any other device (except speaker) is on
2329 if (value & deviceWithoutSpeaker ) {
2330 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2331 }
2332
2333 if (params != 0) {
2334 addBatteryData(params);
2335 }
2336 }
2337
Eric Laurent65b65452010-06-01 23:49:17 -07002338 // forward device change to effects that have requested to be
2339 // aware of attached audio device.
2340 mDevice = (uint32_t)value;
2341 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002342 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002343 }
2344 }
2345
Eric Laurenta553c252009-07-17 12:17:14 -07002346 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002347 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002348 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002349 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002350 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002351 mStandby = true;
2352 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002353 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002354 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002355 }
2356 if (status == NO_ERROR && reconfig) {
2357 delete mAudioMixer;
2358 readOutputParameters();
2359 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2360 for (size_t i = 0; i < mTracks.size() ; i++) {
2361 int name = getTrackName_l();
2362 if (name < 0) break;
2363 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002364 // limit track sample rate to 2 x new output sample rate
2365 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2366 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2367 }
Eric Laurenta553c252009-07-17 12:17:14 -07002368 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002369 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002370 }
2371 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002372
2373 mNewParameters.removeAt(0);
2374
Eric Laurenta553c252009-07-17 12:17:14 -07002375 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002376 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002377 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2378 // already timed out waiting for the status and will never signal the condition.
2379 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07002380 }
2381 return reconfig;
2382}
2383
2384status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2385{
2386 const size_t SIZE = 256;
2387 char buffer[SIZE];
2388 String8 result;
2389
2390 PlaybackThread::dumpInternals(fd, args);
2391
2392 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2393 result.append(buffer);
2394 write(fd, result.string(), result.size());
2395 return NO_ERROR;
2396}
2397
Eric Laurent059b4be2009-11-09 23:32:22 -08002398uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002399{
Dima Zavin31f188892011-04-18 16:57:27 -07002400 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002401}
2402
2403uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2404{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002405 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002406}
2407
Eric Laurent8448a792010-08-18 18:13:17 -07002408uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2409{
2410 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2411}
2412
Eric Laurenta553c252009-07-17 12:17:14 -07002413// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002414AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002415 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002416{
Eric Laurent464d5b32011-06-17 21:29:58 -07002417 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002418}
2419
2420AudioFlinger::DirectOutputThread::~DirectOutputThread()
2421{
2422}
2423
2424
Eric Laurent65b65452010-06-01 23:49:17 -07002425static inline int16_t clamp16(int32_t sample)
2426{
2427 if ((sample>>15) ^ (sample>>31))
2428 sample = 0x7FFF ^ (sample>>31);
2429 return sample;
2430}
2431
2432static inline
2433int32_t mul(int16_t in, int16_t v)
2434{
2435#if defined(__arm__) && !defined(__thumb__)
2436 int32_t out;
2437 asm( "smulbb %[out], %[in], %[v] \n"
2438 : [out]"=r"(out)
2439 : [in]"%r"(in), [v]"r"(v)
2440 : );
2441 return out;
2442#else
2443 return in * int32_t(v);
2444#endif
2445}
2446
2447void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2448{
2449 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002450 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002451 return;
2452 }
2453
2454 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002455 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002456 size_t count = mFrameCount * mChannelCount;
2457 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2458 int16_t *dst = mMixBuffer + count-1;
2459 while(count--) {
2460 *dst-- = (int16_t)(*src--^0x80) << 8;
2461 }
2462 }
2463
2464 size_t frameCount = mFrameCount;
2465 int16_t *out = mMixBuffer;
2466 if (ramp) {
2467 if (mChannelCount == 1) {
2468 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2469 int32_t vlInc = d / (int32_t)frameCount;
2470 int32_t vl = ((int32_t)mLeftVolShort << 16);
2471 do {
2472 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2473 out++;
2474 vl += vlInc;
2475 } while (--frameCount);
2476
2477 } else {
2478 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2479 int32_t vlInc = d / (int32_t)frameCount;
2480 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2481 int32_t vrInc = d / (int32_t)frameCount;
2482 int32_t vl = ((int32_t)mLeftVolShort << 16);
2483 int32_t vr = ((int32_t)mRightVolShort << 16);
2484 do {
2485 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2486 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2487 out += 2;
2488 vl += vlInc;
2489 vr += vrInc;
2490 } while (--frameCount);
2491 }
2492 } else {
2493 if (mChannelCount == 1) {
2494 do {
2495 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2496 out++;
2497 } while (--frameCount);
2498 } else {
2499 do {
2500 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2501 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2502 out += 2;
2503 } while (--frameCount);
2504 }
2505 }
2506
2507 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002508 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002509 size_t count = mFrameCount * mChannelCount;
2510 int16_t *src = mMixBuffer;
2511 uint8_t *dst = (uint8_t *)mMixBuffer;
2512 while(count--) {
2513 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2514 }
2515 }
2516
2517 mLeftVolShort = leftVol;
2518 mRightVolShort = rightVol;
2519}
2520
Eric Laurenta553c252009-07-17 12:17:14 -07002521bool AudioFlinger::DirectOutputThread::threadLoop()
2522{
Eric Laurent059b4be2009-11-09 23:32:22 -08002523 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002524 sp<Track> trackToRemove;
2525 sp<Track> activeTrack;
2526 nsecs_t standbyTime = systemTime();
2527 int8_t *curBuf;
2528 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002529 uint32_t activeSleepTime = activeSleepTimeUs();
2530 uint32_t idleSleepTime = idleSleepTimeUs();
2531 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002532 // use shorter standby delay as on normal output to release
2533 // hardware resources as soon as possible
2534 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002535
Eric Laurent6dbdc402011-07-22 09:04:31 -07002536 acquireWakeLock();
2537
Eric Laurenta553c252009-07-17 12:17:14 -07002538 while (!exitPending())
2539 {
Eric Laurent65b65452010-06-01 23:49:17 -07002540 bool rampVolume;
2541 uint16_t leftVol;
2542 uint16_t rightVol;
2543 Vector< sp<EffectChain> > effectChains;
2544
Eric Laurenta553c252009-07-17 12:17:14 -07002545 processConfigEvents();
2546
Eric Laurent059b4be2009-11-09 23:32:22 -08002547 mixerStatus = MIXER_IDLE;
2548
Eric Laurenta553c252009-07-17 12:17:14 -07002549 { // scope for the mLock
2550
2551 Mutex::Autolock _l(mLock);
2552
2553 if (checkForNewParameters_l()) {
2554 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002555 activeSleepTime = activeSleepTimeUs();
2556 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002557 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002558 }
2559
2560 // put audio hardware into standby after short delay
2561 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2562 mSuspended) {
2563 // wait until we have something to do...
2564 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002565 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002566 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002567 mStandby = true;
2568 mBytesWritten = 0;
2569 }
2570
2571 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2572 // we're about to wait, flush the binder command buffer
2573 IPCThreadState::self()->flushCommands();
2574
2575 if (exitPending()) break;
2576
Eric Laurent6dbdc402011-07-22 09:04:31 -07002577 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002578 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002579 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002580 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002581 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002582
2583 if (mMasterMute == false) {
2584 char value[PROPERTY_VALUE_MAX];
2585 property_get("ro.audio.silent", value, "0");
2586 if (atoi(value)) {
2587 LOGD("Silence is golden");
2588 setMasterMute(true);
2589 }
2590 }
2591
Eric Laurentef9500f2010-03-11 14:47:00 -08002592 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002593 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002594 continue;
2595 }
2596 }
2597
Eric Laurent65b65452010-06-01 23:49:17 -07002598 effectChains = mEffectChains;
2599
Eric Laurenta553c252009-07-17 12:17:14 -07002600 // find out which tracks need to be processed
2601 if (mActiveTracks.size() != 0) {
2602 sp<Track> t = mActiveTracks[0].promote();
2603 if (t == 0) continue;
2604
2605 Track* const track = t.get();
2606 audio_track_cblk_t* cblk = track->cblk();
2607
2608 // The first time a track is added we wait
2609 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002610 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002611 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002612 {
Steve Block71f2cf12011-10-20 11:56:00 +01002613 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002614
Eric Laurent65b65452010-06-01 23:49:17 -07002615 if (track->mFillingUpStatus == Track::FS_FILLED) {
2616 track->mFillingUpStatus = Track::FS_ACTIVE;
2617 mLeftVolFloat = mRightVolFloat = 0;
2618 mLeftVolShort = mRightVolShort = 0;
2619 if (track->mState == TrackBase::RESUMING) {
2620 track->mState = TrackBase::ACTIVE;
2621 rampVolume = true;
2622 }
2623 } else if (cblk->server != 0) {
2624 // If the track is stopped before the first frame was mixed,
2625 // do not apply ramp
2626 rampVolume = true;
2627 }
Eric Laurenta553c252009-07-17 12:17:14 -07002628 // compute volume for this track
2629 float left, right;
2630 if (track->isMuted() || mMasterMute || track->isPausing() ||
2631 mStreamTypes[track->type()].mute) {
2632 left = right = 0;
2633 if (track->isPausing()) {
2634 track->setPaused();
2635 }
2636 } else {
2637 float typeVolume = mStreamTypes[track->type()].volume;
2638 float v = mMasterVolume * typeVolume;
2639 float v_clamped = v * cblk->volume[0];
2640 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2641 left = v_clamped/MAX_GAIN;
2642 v_clamped = v * cblk->volume[1];
2643 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2644 right = v_clamped/MAX_GAIN;
2645 }
2646
Eric Laurent65b65452010-06-01 23:49:17 -07002647 if (left != mLeftVolFloat || right != mRightVolFloat) {
2648 mLeftVolFloat = left;
2649 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002650
Eric Laurent65b65452010-06-01 23:49:17 -07002651 // If audio HAL implements volume control,
2652 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002653 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002654 left = 1.0f;
2655 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002656 }
Eric Laurent65b65452010-06-01 23:49:17 -07002657
2658 // Convert volumes from float to 8.24
2659 uint32_t vl = (uint32_t)(left * (1 << 24));
2660 uint32_t vr = (uint32_t)(right * (1 << 24));
2661
2662 // Delegate volume control to effect in track effect chain if needed
2663 // only one effect chain can be present on DirectOutputThread, so if
2664 // there is one, the track is connected to it
2665 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002666 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002667 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002668 rampVolume = false;
2669 }
2670 }
2671
2672 // Convert volumes from 8.24 to 4.12 format
2673 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2674 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2675 leftVol = (uint16_t)v_clamped;
2676 v_clamped = (vr + (1 << 11)) >> 12;
2677 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2678 rightVol = (uint16_t)v_clamped;
2679 } else {
2680 leftVol = mLeftVolShort;
2681 rightVol = mRightVolShort;
2682 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002683 }
2684
2685 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002686 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002687 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002688 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002689 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002690 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002691 if (track->isStopped()) {
2692 track->reset();
2693 }
2694 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2695 // We have consumed all the buffers of this track.
2696 // Remove it from the list of active tracks.
2697 trackToRemove = track;
2698 } else {
2699 // No buffers for this track. Give it a few chances to
2700 // fill a buffer, then remove it from active list.
2701 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002702 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002703 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002704 } else {
2705 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002706 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002707 }
Eric Laurenta553c252009-07-17 12:17:14 -07002708 }
2709 }
2710
2711 // remove all the tracks that need to be...
2712 if (UNLIKELY(trackToRemove != 0)) {
2713 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002714 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002715 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002716 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002717 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002718 }
Eric Laurenta553c252009-07-17 12:17:14 -07002719 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002720 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002721 }
2722 }
Eric Laurent65b65452010-06-01 23:49:17 -07002723
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002724 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002725 }
2726
Eric Laurent059b4be2009-11-09 23:32:22 -08002727 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002728 AudioBufferProvider::Buffer buffer;
2729 size_t frameCount = mFrameCount;
2730 curBuf = (int8_t *)mMixBuffer;
2731 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002732 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002733 buffer.frameCount = frameCount;
2734 activeTrack->getNextBuffer(&buffer);
2735 if (UNLIKELY(buffer.raw == 0)) {
2736 memset(curBuf, 0, frameCount * mFrameSize);
2737 break;
2738 }
2739 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2740 frameCount -= buffer.frameCount;
2741 curBuf += buffer.frameCount * mFrameSize;
2742 activeTrack->releaseBuffer(&buffer);
2743 }
2744 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002745 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002746 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002747 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002748 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2749 sleepTime = activeSleepTime;
2750 } else {
2751 sleepTime = idleSleepTime;
2752 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002753 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002754 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002755 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002756 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002757 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002758
Eric Laurentf69a3f82009-09-22 00:35:48 -07002759 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002760 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002761 }
2762 // sleepTime == 0 means we must write to audio hardware
2763 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002764 if (mixerStatus == MIXER_TRACKS_READY) {
2765 applyVolume(leftVol, rightVol, rampVolume);
2766 }
2767 for (size_t i = 0; i < effectChains.size(); i ++) {
2768 effectChains[i]->process_l();
2769 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002770 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002771
Eric Laurentf69a3f82009-09-22 00:35:48 -07002772 mLastWriteTime = systemTime();
2773 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002774 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002775 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002776 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002777 mNumWrites++;
2778 mInWrite = false;
2779 mStandby = false;
2780 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002781 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002782 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002783 }
2784
2785 // finally let go of removed track, without the lock held
2786 // since we can't guarantee the destructors won't acquire that
2787 // same lock.
2788 trackToRemove.clear();
2789 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002790
2791 // Effect chains will be actually deleted here if they were removed from
2792 // mEffectChains list during mixing or effects processing
2793 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002794 }
2795
2796 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002797 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002798 }
Eric Laurenta553c252009-07-17 12:17:14 -07002799
Eric Laurent6dbdc402011-07-22 09:04:31 -07002800 releaseWakeLock();
2801
Steve Block71f2cf12011-10-20 11:56:00 +01002802 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002803 return false;
2804}
2805
2806// getTrackName_l() must be called with ThreadBase::mLock held
2807int AudioFlinger::DirectOutputThread::getTrackName_l()
2808{
2809 return 0;
2810}
2811
2812// deleteTrackName_l() must be called with ThreadBase::mLock held
2813void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2814{
2815}
2816
2817// checkForNewParameters_l() must be called with ThreadBase::mLock held
2818bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2819{
2820 bool reconfig = false;
2821
Eric Laurent8fce46a2009-08-04 09:45:33 -07002822 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002823 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002824 String8 keyValuePair = mNewParameters[0];
2825 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002826 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002827
Eric Laurenta553c252009-07-17 12:17:14 -07002828 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2829 // do not accept frame count changes if tracks are open as the track buffer
2830 // size depends on frame count and correct behavior would not be garantied
2831 // if frame count is changed after track creation
2832 if (!mTracks.isEmpty()) {
2833 status = INVALID_OPERATION;
2834 } else {
2835 reconfig = true;
2836 }
2837 }
2838 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002839 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002840 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002841 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002842 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002843 mStandby = true;
2844 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002845 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002846 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002847 }
2848 if (status == NO_ERROR && reconfig) {
2849 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002850 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002851 }
2852 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002853
2854 mNewParameters.removeAt(0);
2855
Eric Laurenta553c252009-07-17 12:17:14 -07002856 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002857 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002858 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2859 // already timed out waiting for the status and will never signal the condition.
2860 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07002861 }
2862 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002863}
2864
Eric Laurent059b4be2009-11-09 23:32:22 -08002865uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002866{
2867 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002868 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin31f188892011-04-18 16:57:27 -07002869 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002870 } else {
2871 time = 10000;
2872 }
2873 return time;
2874}
2875
2876uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2877{
2878 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002879 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002880 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002881 } else {
2882 time = 10000;
2883 }
2884 return time;
2885}
2886
Eric Laurent8448a792010-08-18 18:13:17 -07002887uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2888{
2889 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002890 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002891 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2892 } else {
2893 time = 10000;
2894 }
2895 return time;
2896}
2897
2898
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002899// ----------------------------------------------------------------------------
2900
Eric Laurent49f02be2009-11-19 09:00:56 -08002901AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002902 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002903{
Eric Laurent464d5b32011-06-17 21:29:58 -07002904 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002905 addOutputTrack(mainThread);
2906}
2907
2908AudioFlinger::DuplicatingThread::~DuplicatingThread()
2909{
Eric Laurent0a080292009-12-07 10:53:10 -08002910 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2911 mOutputTracks[i]->destroy();
2912 }
Eric Laurenta553c252009-07-17 12:17:14 -07002913 mOutputTracks.clear();
2914}
2915
2916bool AudioFlinger::DuplicatingThread::threadLoop()
2917{
Eric Laurenta553c252009-07-17 12:17:14 -07002918 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002919 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002920 nsecs_t standbyTime = systemTime();
2921 size_t mixBufferSize = mFrameCount*mFrameSize;
2922 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002923 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002924 uint32_t activeSleepTime = activeSleepTimeUs();
2925 uint32_t idleSleepTime = idleSleepTimeUs();
2926 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002927 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002928
Eric Laurent6dbdc402011-07-22 09:04:31 -07002929 acquireWakeLock();
2930
Eric Laurenta553c252009-07-17 12:17:14 -07002931 while (!exitPending())
2932 {
2933 processConfigEvents();
2934
Eric Laurent059b4be2009-11-09 23:32:22 -08002935 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002936 { // scope for the mLock
2937
2938 Mutex::Autolock _l(mLock);
2939
2940 if (checkForNewParameters_l()) {
2941 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002942 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002943 activeSleepTime = activeSleepTimeUs();
2944 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002945 }
2946
2947 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2948
2949 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2950 outputTracks.add(mOutputTracks[i]);
2951 }
2952
2953 // put audio hardware into standby after short delay
2954 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2955 mSuspended) {
2956 if (!mStandby) {
2957 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002958 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002959 }
2960 mStandby = true;
2961 mBytesWritten = 0;
2962 }
2963
2964 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2965 // we're about to wait, flush the binder command buffer
2966 IPCThreadState::self()->flushCommands();
2967 outputTracks.clear();
2968
2969 if (exitPending()) break;
2970
Eric Laurent6dbdc402011-07-22 09:04:31 -07002971 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002972 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002973 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002974 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002975 acquireWakeLock_l();
2976
Eric Laurenta553c252009-07-17 12:17:14 -07002977 if (mMasterMute == false) {
2978 char value[PROPERTY_VALUE_MAX];
2979 property_get("ro.audio.silent", value, "0");
2980 if (atoi(value)) {
2981 LOGD("Silence is golden");
2982 setMasterMute(true);
2983 }
2984 }
2985
2986 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002987 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002988 continue;
2989 }
2990 }
2991
Eric Laurent059b4be2009-11-09 23:32:22 -08002992 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002993
2994 // prevent any changes in effect chain list and in each effect chain
2995 // during mixing and effect process as the audio buffers could be deleted
2996 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002997 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002998 }
Eric Laurenta553c252009-07-17 12:17:14 -07002999
Eric Laurent059b4be2009-11-09 23:32:22 -08003000 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003001 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003002 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003003 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003004 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003005 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003006 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003007 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003008 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003009 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003010 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003011 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3012 sleepTime = activeSleepTime;
3013 } else {
3014 sleepTime = idleSleepTime;
3015 }
Eric Laurent62443f52009-10-05 20:29:18 -07003016 } else if (mBytesWritten != 0) {
3017 // flush remaining overflow buffers in output tracks
3018 for (size_t i = 0; i < outputTracks.size(); i++) {
3019 if (outputTracks[i]->isActive()) {
3020 sleepTime = 0;
3021 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003022 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003023 break;
3024 }
3025 }
Eric Laurenta553c252009-07-17 12:17:14 -07003026 }
3027 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003028
3029 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003030 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003031 }
3032 // sleepTime == 0 means we must write to audio hardware
3033 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003034 for (size_t i = 0; i < effectChains.size(); i ++) {
3035 effectChains[i]->process_l();
3036 }
3037 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003038 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003039
Eric Laurent62443f52009-10-05 20:29:18 -07003040 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003041 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003042 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003043 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003044 mStandby = false;
3045 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003046 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003047 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003048 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003049 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003050 }
3051
3052 // finally let go of all our tracks, without the lock held
3053 // since we can't guarantee the destructors won't acquire that
3054 // same lock.
3055 tracksToRemove.clear();
3056 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003057
3058 // Effect chains will be actually deleted here if they were removed from
3059 // mEffectChains list during mixing or effects processing
3060 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003061 }
3062
Eric Laurent6dbdc402011-07-22 09:04:31 -07003063 releaseWakeLock();
3064
Eric Laurenta553c252009-07-17 12:17:14 -07003065 return false;
3066}
3067
3068void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3069{
3070 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3071 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003072 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003073 mSampleRate,
3074 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003075 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003076 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003077 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003078 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003079 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003080 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003081 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003082 }
Eric Laurenta553c252009-07-17 12:17:14 -07003083}
3084
3085void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3086{
3087 Mutex::Autolock _l(mLock);
3088 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3089 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003090 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003091 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003092 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003093 return;
3094 }
3095 }
Steve Block71f2cf12011-10-20 11:56:00 +01003096 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003097}
3098
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003099void AudioFlinger::DuplicatingThread::updateWaitTime()
3100{
3101 mWaitTimeMs = UINT_MAX;
3102 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3103 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3104 if (strong != NULL) {
3105 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3106 if (waitTimeMs < mWaitTimeMs) {
3107 mWaitTimeMs = waitTimeMs;
3108 }
3109 }
3110 }
3111}
3112
3113
3114bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3115{
3116 for (size_t i = 0; i < outputTracks.size(); i++) {
3117 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3118 if (thread == 0) {
3119 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3120 return false;
3121 }
3122 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3123 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003124 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003125 return false;
3126 }
3127 }
3128 return true;
3129}
3130
3131uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3132{
3133 return (mWaitTimeMs * 1000) / 2;
3134}
3135
Eric Laurenta553c252009-07-17 12:17:14 -07003136// ----------------------------------------------------------------------------
3137
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003138// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003139AudioFlinger::ThreadBase::TrackBase::TrackBase(
3140 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003141 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003142 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003143 uint32_t format,
3144 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003145 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003147 const sp<IMemory>& sharedBuffer,
3148 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003149 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003150 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003151 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003152 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003153 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003154 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003155 mClientTid(-1),
3156 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003157 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3158 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003159{
Steve Block71f2cf12011-10-20 11:56:00 +01003160 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003161
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003162 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003163 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003164 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003165 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3166 if (sharedBuffer == 0) {
3167 size += bufferSize;
3168 }
3169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 if (client != NULL) {
3171 mCblkMemory = client->heap()->allocate(size);
3172 if (mCblkMemory != 0) {
3173 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3174 if (mCblk) { // construct the shared structure in-place.
3175 new(mCblk) audio_track_cblk_t();
3176 // clear all buffers
3177 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003178 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003179 mChannelCount = channelCount;
3180 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 if (sharedBuffer == 0) {
3182 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3183 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3184 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003185 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003186 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 } else {
3188 mBuffer = sharedBuffer->pointer();
3189 }
3190 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 } else {
3193 LOGE("not enough memory for AudioTrack size=%u", size);
3194 client->heap()->dump("AudioTrack");
3195 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 } else {
3198 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3199 if (mCblk) { // construct the shared structure in-place.
3200 new(mCblk) audio_track_cblk_t();
3201 // clear all buffers
3202 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003203 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003204 mChannelCount = channelCount;
3205 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3207 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3208 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003209 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003210 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3212 }
3213 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003214}
3215
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003216AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003217{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003219 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3220 if (mClient == NULL) {
3221 delete mCblk;
3222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003224 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003225 if (mClient != NULL) {
3226 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3227 mClient.clear();
3228 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003229}
3230
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003231void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003232{
3233 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003234 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003235 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003236 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003237}
3238
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003239bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003240 bool result;
3241 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003242
3243 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003244 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003245 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003246 mFlags |= STEPSERVER_FAILED;
3247 }
3248 return result;
3249}
3250
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003251void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003252 audio_track_cblk_t* cblk = this->cblk();
3253
3254 cblk->user = 0;
3255 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003256 cblk->userBase = 0;
3257 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003259 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003260}
3261
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003262sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003263{
3264 return mCblkMemory;
3265}
3266
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003267int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003268 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003269}
3270
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003271int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003272 return (const int)mChannelCount;
3273}
3274
3275uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3276 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003277}
3278
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003279void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003280 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003281 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3282 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003283
3284 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003285 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3286 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003287 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003288 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003289 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003290 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003291 return 0;
3292 }
3293
3294 return bufferStart;
3295}
3296
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003297// ----------------------------------------------------------------------------
3298
Eric Laurenta553c252009-07-17 12:17:14 -07003299// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3300AudioFlinger::PlaybackThread::Track::Track(
3301 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003302 const sp<Client>& client,
3303 int streamType,
3304 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003305 uint32_t format,
3306 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003307 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003308 const sp<IMemory>& sharedBuffer,
3309 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003310 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003311 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3312 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003313{
Eric Laurent8a77a992009-09-09 05:16:08 -07003314 if (mCblk != NULL) {
3315 sp<ThreadBase> baseThread = thread.promote();
3316 if (baseThread != 0) {
3317 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3318 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003319 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003320 }
Steve Block71f2cf12011-10-20 11:56:00 +01003321 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003322 if (mName < 0) {
3323 LOGE("no more track names available");
3324 }
3325 mVolume[0] = 1.0f;
3326 mVolume[1] = 1.0f;
3327 mStreamType = streamType;
3328 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3329 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003330 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003331 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003332}
3333
Eric Laurenta553c252009-07-17 12:17:14 -07003334AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003335{
Steve Block71f2cf12011-10-20 11:56:00 +01003336 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003337 sp<ThreadBase> thread = mThread.promote();
3338 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003339 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003340 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003341 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003342}
3343
Eric Laurenta553c252009-07-17 12:17:14 -07003344void AudioFlinger::PlaybackThread::Track::destroy()
3345{
3346 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3347 // by removing it from mTracks vector, so there is a risk that this Tracks's
3348 // desctructor is called. As the destructor needs to lock mLock,
3349 // we must acquire a strong reference on this Track before locking mLock
3350 // here so that the destructor is called only when exiting this function.
3351 // On the other hand, as long as Track::destroy() is only called by
3352 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3353 // this Track with its member mTrack.
3354 sp<Track> keep(this);
3355 { // scope for mLock
3356 sp<ThreadBase> thread = mThread.promote();
3357 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003358 if (!isOutputTrack()) {
3359 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003360 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003361 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003362 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003363
3364 // to track the speaker usage
3365 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003366 }
3367 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003368 }
Eric Laurenta553c252009-07-17 12:17:14 -07003369 Mutex::Autolock _l(thread->mLock);
3370 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3371 playbackThread->destroyTrack_l(this);
3372 }
3373 }
3374}
3375
3376void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003377{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003378 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 -07003379 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003381 mStreamType,
3382 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003383 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003384 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003385 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003386 mState,
3387 mMute,
3388 mFillingUpStatus,
3389 mCblk->sampleRate,
3390 mCblk->volume[0],
3391 mCblk->volume[1],
3392 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003393 mCblk->user,
3394 (int)mMainBuffer,
3395 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003396}
3397
Eric Laurenta553c252009-07-17 12:17:14 -07003398status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003399{
3400 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003401 uint32_t framesReady;
3402 uint32_t framesReq = buffer->frameCount;
3403
3404 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003405 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3406 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003407 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003408 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3409 }
3410
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003411 framesReady = cblk->framesReady();
3412
3413 if (LIKELY(framesReady)) {
3414 uint32_t s = cblk->server;
3415 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3416
3417 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3418 if (framesReq > framesReady) {
3419 framesReq = framesReady;
3420 }
3421 if (s + framesReq > bufferEnd) {
3422 framesReq = bufferEnd - s;
3423 }
3424
3425 buffer->raw = getBuffer(s, framesReq);
3426 if (buffer->raw == 0) goto getNextBuffer_exit;
3427
3428 buffer->frameCount = framesReq;
3429 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003430 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003431
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003432getNextBuffer_exit:
3433 buffer->raw = 0;
3434 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003435 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 -07003436 return NOT_ENOUGH_DATA;
3437}
3438
Eric Laurenta553c252009-07-17 12:17:14 -07003439bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003440 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003441
3442 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003443 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003444 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003445 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003446 return true;
3447 }
3448 return false;
3449}
3450
Eric Laurenta553c252009-07-17 12:17:14 -07003451status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003452{
Eric Laurent49f02be2009-11-19 09:00:56 -08003453 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003454 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003455 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003456 sp<ThreadBase> thread = mThread.promote();
3457 if (thread != 0) {
3458 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003459 int state = mState;
3460 // here the track could be either new, or restarted
3461 // in both cases "unstop" the track
3462 if (mState == PAUSED) {
3463 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003464 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003465 } else {
3466 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003467 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003468 }
3469
3470 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3471 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003472 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003473 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003474 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003475 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003476
3477 // to track the speaker usage
3478 if (status == NO_ERROR) {
3479 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3480 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003481 }
3482 if (status == NO_ERROR) {
3483 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3484 playbackThread->addTrack_l(this);
3485 } else {
3486 mState = state;
3487 }
3488 } else {
3489 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003490 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003491 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003492}
3493
Eric Laurenta553c252009-07-17 12:17:14 -07003494void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003495{
Steve Block71f2cf12011-10-20 11:56:00 +01003496 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003497 sp<ThreadBase> thread = mThread.promote();
3498 if (thread != 0) {
3499 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003500 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003501 if (mState > STOPPED) {
3502 mState = STOPPED;
3503 // If the track is not active (PAUSED and buffers full), flush buffers
3504 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3505 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3506 reset();
3507 }
Steve Block71f2cf12011-10-20 11:56:00 +01003508 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003509 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003510 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3511 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003512 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003513 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003514 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003515 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003516
3517 // to track the speaker usage
3518 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003519 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003520 }
3521}
3522
Eric Laurenta553c252009-07-17 12:17:14 -07003523void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003524{
Steve Block71f2cf12011-10-20 11:56:00 +01003525 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003526 sp<ThreadBase> thread = mThread.promote();
3527 if (thread != 0) {
3528 Mutex::Autolock _l(thread->mLock);
3529 if (mState == ACTIVE || mState == RESUMING) {
3530 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003531 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003532 if (!isOutputTrack()) {
3533 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003534 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003535 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003536 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003537 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003538
3539 // to track the speaker usage
3540 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003541 }
Eric Laurenta553c252009-07-17 12:17:14 -07003542 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003543 }
3544}
3545
Eric Laurenta553c252009-07-17 12:17:14 -07003546void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003547{
Steve Block71f2cf12011-10-20 11:56:00 +01003548 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003549 sp<ThreadBase> thread = mThread.promote();
3550 if (thread != 0) {
3551 Mutex::Autolock _l(thread->mLock);
3552 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3553 return;
3554 }
3555 // No point remaining in PAUSED state after a flush => go to
3556 // STOPPED state
3557 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003558
Eric Laurentae29b762011-03-28 18:37:07 -07003559 // do not reset the track if it is still in the process of being stopped or paused.
3560 // this will be done by prepareTracks_l() when the track is stopped.
3561 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3562 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3563 reset();
3564 }
Eric Laurenta553c252009-07-17 12:17:14 -07003565 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003566}
3567
Eric Laurenta553c252009-07-17 12:17:14 -07003568void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003569{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003570 // Do not reset twice to avoid discarding data written just after a flush and before
3571 // the audioflinger thread detects the track is stopped.
3572 if (!mResetDone) {
3573 TrackBase::reset();
3574 // Force underrun condition to avoid false underrun callback until first data is
3575 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003576 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3577 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003578 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003579 mResetDone = true;
3580 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003581}
3582
Eric Laurenta553c252009-07-17 12:17:14 -07003583void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003584{
3585 mMute = muted;
3586}
3587
Eric Laurenta553c252009-07-17 12:17:14 -07003588void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003589{
3590 mVolume[0] = left;
3591 mVolume[1] = right;
3592}
3593
Eric Laurent65b65452010-06-01 23:49:17 -07003594status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3595{
3596 status_t status = DEAD_OBJECT;
3597 sp<ThreadBase> thread = mThread.promote();
3598 if (thread != 0) {
3599 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3600 status = playbackThread->attachAuxEffect(this, EffectId);
3601 }
3602 return status;
3603}
3604
3605void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3606{
3607 mAuxEffectId = EffectId;
3608 mAuxBuffer = buffer;
3609}
3610
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003611// ----------------------------------------------------------------------------
3612
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003613// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003614AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3615 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003618 uint32_t format,
3619 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003621 uint32_t flags,
3622 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003623 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003624 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003625 mOverflow(false)
3626{
Eric Laurent8a77a992009-09-09 05:16:08 -07003627 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003628 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003629 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003630 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003631 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003632 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003633 } else {
3634 mCblk->frameSize = sizeof(int8_t);
3635 }
3636 }
Eric Laurenta553c252009-07-17 12:17:14 -07003637}
3638
3639AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640{
Eric Laurent49f02be2009-11-19 09:00:56 -08003641 sp<ThreadBase> thread = mThread.promote();
3642 if (thread != 0) {
3643 AudioSystem::releaseInput(thread->id());
3644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645}
3646
Eric Laurenta553c252009-07-17 12:17:14 -07003647status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648{
3649 audio_track_cblk_t* cblk = this->cblk();
3650 uint32_t framesAvail;
3651 uint32_t framesReq = buffer->frameCount;
3652
3653 // Check if last stepServer failed, try to step now
3654 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3655 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003656 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3658 }
3659
3660 framesAvail = cblk->framesAvailable_l();
3661
3662 if (LIKELY(framesAvail)) {
3663 uint32_t s = cblk->server;
3664 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3665
3666 if (framesReq > framesAvail) {
3667 framesReq = framesAvail;
3668 }
3669 if (s + framesReq > bufferEnd) {
3670 framesReq = bufferEnd - s;
3671 }
3672
3673 buffer->raw = getBuffer(s, framesReq);
3674 if (buffer->raw == 0) goto getNextBuffer_exit;
3675
3676 buffer->frameCount = framesReq;
3677 return NO_ERROR;
3678 }
3679
3680getNextBuffer_exit:
3681 buffer->raw = 0;
3682 buffer->frameCount = 0;
3683 return NOT_ENOUGH_DATA;
3684}
3685
Eric Laurenta553c252009-07-17 12:17:14 -07003686status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687{
Eric Laurenta553c252009-07-17 12:17:14 -07003688 sp<ThreadBase> thread = mThread.promote();
3689 if (thread != 0) {
3690 RecordThread *recordThread = (RecordThread *)thread.get();
3691 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003692 } else {
3693 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695}
3696
Eric Laurenta553c252009-07-17 12:17:14 -07003697void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698{
Eric Laurenta553c252009-07-17 12:17:14 -07003699 sp<ThreadBase> thread = mThread.promote();
3700 if (thread != 0) {
3701 RecordThread *recordThread = (RecordThread *)thread.get();
3702 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003703 TrackBase::reset();
3704 // Force overerrun condition to avoid false overrun callback until first data is
3705 // read from buffer
3706 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708}
3709
Eric Laurent3fdb1262009-11-07 00:01:32 -08003710void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3711{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003712 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003713 (mClient == NULL) ? getpid() : mClient->pid(),
3714 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003715 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003716 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003717 mFrameCount,
3718 mState,
3719 mCblk->sampleRate,
3720 mCblk->server,
3721 mCblk->user);
3722}
3723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724
3725// ----------------------------------------------------------------------------
3726
Eric Laurenta553c252009-07-17 12:17:14 -07003727AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3728 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003729 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003731 uint32_t format,
3732 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003734 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003735 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736{
Eric Laurenta553c252009-07-17 12:17:14 -07003737
3738 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003739 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003740 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003741 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3742 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3743 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003744 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003745 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003746 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3747 mCblk, mBuffer, mCblk->buffers,
3748 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003749 } else {
3750 LOGW("Error creating output track on thread %p", playbackThread);
3751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752}
3753
Eric Laurenta553c252009-07-17 12:17:14 -07003754AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755{
Eric Laurent6c30a712009-08-10 23:22:32 -07003756 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757}
3758
Eric Laurenta553c252009-07-17 12:17:14 -07003759status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760{
3761 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003762 if (status != NO_ERROR) {
3763 return status;
3764 }
3765
3766 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 mRetryCount = 127;
3768 return status;
3769}
3770
Eric Laurenta553c252009-07-17 12:17:14 -07003771void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772{
3773 Track::stop();
3774 clearBufferQueue();
3775 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003776 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777}
3778
Eric Laurenta553c252009-07-17 12:17:14 -07003779bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780{
3781 Buffer *pInBuffer;
3782 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003783 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003784 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 inBuffer.frameCount = frames;
3786 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003787
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003788 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003789
Eric Laurent62443f52009-10-05 20:29:18 -07003790 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003791 start();
3792 sp<ThreadBase> thread = mThread.promote();
3793 if (thread != 0) {
3794 MixerThread *mixerThread = (MixerThread *)thread.get();
3795 if (mCblk->frameCount > frames){
3796 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3797 uint32_t startFrames = (mCblk->frameCount - frames);
3798 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003799 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003800 pInBuffer->frameCount = startFrames;
3801 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003802 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003803 mBufferQueue.add(pInBuffer);
3804 } else {
3805 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 }
Eric Laurenta553c252009-07-17 12:17:14 -07003808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 }
3810
Eric Laurenta553c252009-07-17 12:17:14 -07003811 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 // First write pending buffers, then new data
3813 if (mBufferQueue.size()) {
3814 pInBuffer = mBufferQueue.itemAt(0);
3815 } else {
3816 pInBuffer = &inBuffer;
3817 }
Eric Laurenta553c252009-07-17 12:17:14 -07003818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 if (pInBuffer->frameCount == 0) {
3820 break;
3821 }
Eric Laurenta553c252009-07-17 12:17:14 -07003822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 if (mOutBuffer.frameCount == 0) {
3824 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003825 nsecs_t startTime = systemTime();
3826 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003827 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003828 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 break;
3830 }
Eric Laurenta553c252009-07-17 12:17:14 -07003831 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003832 if (waitTimeLeftMs >= waitTimeMs) {
3833 waitTimeLeftMs -= waitTimeMs;
3834 } else {
3835 waitTimeLeftMs = 0;
3836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 }
Eric Laurenta553c252009-07-17 12:17:14 -07003838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003840 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 mCblk->stepUser(outFrames);
3842 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003843 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003845 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 if (pInBuffer->frameCount == 0) {
3848 if (mBufferQueue.size()) {
3849 mBufferQueue.removeAt(0);
3850 delete [] pInBuffer->mBuffer;
3851 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003852 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 -08003853 } else {
3854 break;
3855 }
3856 }
3857 }
Eric Laurenta553c252009-07-17 12:17:14 -07003858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 // If we could not write all frames, allocate a buffer and queue it for next time.
3860 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003861 sp<ThreadBase> thread = mThread.promote();
3862 if (thread != 0 && !thread->standby()) {
3863 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3864 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003865 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003866 pInBuffer->frameCount = inBuffer.frameCount;
3867 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003868 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003869 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003870 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003871 } else {
3872 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 }
3875 }
Eric Laurenta553c252009-07-17 12:17:14 -07003876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003878 // 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 -08003879 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003880 if (frames == 0 && mBufferQueue.size() == 0) {
3881 if (mCblk->user < mCblk->frameCount) {
3882 frames = mCblk->frameCount - mCblk->user;
3883 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003884 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003885 pInBuffer->frameCount = frames;
3886 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003887 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003888 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003889 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003890 stop();
3891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 }
3893
Eric Laurenta553c252009-07-17 12:17:14 -07003894 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895}
3896
Eric Laurenta553c252009-07-17 12:17:14 -07003897status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898{
3899 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 status_t result;
3901 audio_track_cblk_t* cblk = mCblk;
3902 uint32_t framesReq = buffer->frameCount;
3903
Steve Block71f2cf12011-10-20 11:56:00 +01003904// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 uint32_t framesAvail = cblk->framesAvailable();
3908
Eric Laurenta553c252009-07-17 12:17:14 -07003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003911 Mutex::Autolock _l(cblk->lock);
3912 goto start_loop_here;
3913 while (framesAvail == 0) {
3914 active = mActive;
3915 if (UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003916 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurenta553c252009-07-17 12:17:14 -07003917 return AudioTrack::NO_MORE_BUFFERS;
3918 }
3919 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3920 if (result != NO_ERROR) {
3921 return AudioTrack::NO_MORE_BUFFERS;
3922 }
3923 // read the server count again
3924 start_loop_here:
3925 framesAvail = cblk->framesAvailable_l();
3926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
3928
Eric Laurenta553c252009-07-17 12:17:14 -07003929// if (framesAvail < framesReq) {
3930// return AudioTrack::NO_MORE_BUFFERS;
3931// }
3932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 if (framesReq > framesAvail) {
3934 framesReq = framesAvail;
3935 }
3936
3937 uint32_t u = cblk->user;
3938 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3939
3940 if (u + framesReq > bufferEnd) {
3941 framesReq = bufferEnd - u;
3942 }
3943
3944 buffer->frameCount = framesReq;
3945 buffer->raw = (void *)cblk->buffer(u);
3946 return NO_ERROR;
3947}
3948
3949
Eric Laurenta553c252009-07-17 12:17:14 -07003950void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951{
3952 size_t size = mBufferQueue.size();
3953 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 for (size_t i = 0; i < size; i++) {
3956 pBuffer = mBufferQueue.itemAt(i);
3957 delete [] pBuffer->mBuffer;
3958 delete pBuffer;
3959 }
3960 mBufferQueue.clear();
3961}
3962
3963// ----------------------------------------------------------------------------
3964
3965AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3966 : RefBase(),
3967 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003968 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 mPid(pid)
3970{
3971 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3972}
3973
Eric Laurentb9481d82009-09-17 05:12:56 -07003974// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975AudioFlinger::Client::~Client()
3976{
Eric Laurentb9481d82009-09-17 05:12:56 -07003977 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978}
3979
3980const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3981{
3982 return mMemoryDealer;
3983}
3984
3985// ----------------------------------------------------------------------------
3986
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003987AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3988 const sp<IAudioFlingerClient>& client,
3989 pid_t pid)
3990 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3991{
3992}
3993
3994AudioFlinger::NotificationClient::~NotificationClient()
3995{
3996 mClient.clear();
3997}
3998
3999void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4000{
4001 sp<NotificationClient> keep(this);
4002 {
4003 mAudioFlinger->removeNotificationClient(mPid);
4004 }
4005}
4006
4007// ----------------------------------------------------------------------------
4008
Eric Laurenta553c252009-07-17 12:17:14 -07004009AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004010 : BnAudioTrack(),
4011 mTrack(track)
4012{
4013}
4014
4015AudioFlinger::TrackHandle::~TrackHandle() {
4016 // just stop the track on deletion, associated resources
4017 // will be freed from the main thread once all pending buffers have
4018 // been played. Unless it's not in the active track list, in which
4019 // case we free everything now...
4020 mTrack->destroy();
4021}
4022
4023status_t AudioFlinger::TrackHandle::start() {
4024 return mTrack->start();
4025}
4026
4027void AudioFlinger::TrackHandle::stop() {
4028 mTrack->stop();
4029}
4030
4031void AudioFlinger::TrackHandle::flush() {
4032 mTrack->flush();
4033}
4034
4035void AudioFlinger::TrackHandle::mute(bool e) {
4036 mTrack->mute(e);
4037}
4038
4039void AudioFlinger::TrackHandle::pause() {
4040 mTrack->pause();
4041}
4042
4043void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4044 mTrack->setVolume(left, right);
4045}
4046
4047sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4048 return mTrack->getCblk();
4049}
4050
Eric Laurent65b65452010-06-01 23:49:17 -07004051status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4052{
4053 return mTrack->attachAuxEffect(EffectId);
4054}
4055
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004056status_t AudioFlinger::TrackHandle::onTransact(
4057 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4058{
4059 return BnAudioTrack::onTransact(code, data, reply, flags);
4060}
4061
4062// ----------------------------------------------------------------------------
4063
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004064sp<IAudioRecord> AudioFlinger::openRecord(
4065 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004066 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004067 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004068 uint32_t format,
4069 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004070 int frameCount,
4071 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004072 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004073 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004074{
Eric Laurenta553c252009-07-17 12:17:14 -07004075 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004076 sp<RecordHandle> recordHandle;
4077 sp<Client> client;
4078 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004079 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004080 RecordThread *thread;
4081 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004082 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004083
4084 // check calling permissions
4085 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004086 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004087 goto Exit;
4088 }
4089
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004090 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004091 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004092 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004093 thread = checkRecordThread_l(input);
4094 if (thread == NULL) {
4095 lStatus = BAD_VALUE;
4096 goto Exit;
4097 }
4098
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004099 wclient = mClients.valueFor(pid);
4100 if (wclient != NULL) {
4101 client = wclient.promote();
4102 } else {
4103 client = new Client(this, pid);
4104 mClients.add(pid, client);
4105 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004106
Eric Laurent65b65452010-06-01 23:49:17 -07004107 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004108 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004109 lSessionId = *sessionId;
4110 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004111 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004112 if (sessionId != NULL) {
4113 *sessionId = lSessionId;
4114 }
4115 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004116 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004117 recordTrack = thread->createRecordTrack_l(client,
4118 sampleRate,
4119 format,
4120 channelMask,
4121 frameCount,
4122 flags,
4123 lSessionId,
4124 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004125 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004126 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004127 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4128 // destructor is called by the TrackBase destructor with mLock held
4129 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 goto Exit;
4132 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004133
4134 // return to handle to client
4135 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004136 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004137
4138Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004139 if (status) {
4140 *status = lStatus;
4141 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004142 return recordHandle;
4143}
4144
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004145// ----------------------------------------------------------------------------
4146
Eric Laurenta553c252009-07-17 12:17:14 -07004147AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004148 : BnAudioRecord(),
4149 mRecordTrack(recordTrack)
4150{
4151}
4152
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004153AudioFlinger::RecordHandle::~RecordHandle() {
4154 stop();
4155}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004156
4157status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004158 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004159 return mRecordTrack->start();
4160}
4161
4162void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004163 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004164 mRecordTrack->stop();
4165}
4166
4167sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4168 return mRecordTrack->getCblk();
4169}
4170
4171status_t AudioFlinger::RecordHandle::onTransact(
4172 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4173{
4174 return BnAudioRecord::onTransact(code, data, reply, flags);
4175}
4176
4177// ----------------------------------------------------------------------------
4178
Eric Laurent464d5b32011-06-17 21:29:58 -07004179AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4180 AudioStreamIn *input,
4181 uint32_t sampleRate,
4182 uint32_t channels,
4183 int id,
4184 uint32_t device) :
4185 ThreadBase(audioFlinger, id, device),
4186 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004187{
Eric Laurent464d5b32011-06-17 21:29:58 -07004188 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004189
4190 snprintf(mName, kNameLength, "AudioIn_%d", id);
4191
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004192 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004193 mReqSampleRate = sampleRate;
4194 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004195}
4196
Eric Laurenta553c252009-07-17 12:17:14 -07004197
4198AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004199{
Eric Laurenta553c252009-07-17 12:17:14 -07004200 delete[] mRsmpInBuffer;
4201 if (mResampler != 0) {
4202 delete mResampler;
4203 delete[] mRsmpOutBuffer;
4204 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004205}
4206
Eric Laurenta553c252009-07-17 12:17:14 -07004207void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004208{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004209 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004210}
Eric Laurent49f02be2009-11-19 09:00:56 -08004211
Eric Laurent828b9772011-08-07 16:32:26 -07004212status_t AudioFlinger::RecordThread::readyToRun()
4213{
4214 status_t status = initCheck();
4215 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4216 return status;
4217}
4218
Eric Laurenta553c252009-07-17 12:17:14 -07004219bool AudioFlinger::RecordThread::threadLoop()
4220{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004221 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004222 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004223 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004224
Eric Laurent4712baa2010-09-30 16:12:31 -07004225 nsecs_t lastWarning = 0;
4226
Eric Laurent6dbdc402011-07-22 09:04:31 -07004227 acquireWakeLock();
4228
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004229 // start recording
4230 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004231
Eric Laurenta553c252009-07-17 12:17:14 -07004232 processConfigEvents();
4233
4234 { // scope for mLock
4235 Mutex::Autolock _l(mLock);
4236 checkForNewParameters_l();
4237 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4238 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004239 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004240 mStandby = true;
4241 }
4242
4243 if (exitPending()) break;
4244
Eric Laurent6dbdc402011-07-22 09:04:31 -07004245 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004246 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004247 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004248 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004249 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004250 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004251 continue;
4252 }
4253 if (mActiveTrack != 0) {
4254 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004255 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004256 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004257 mStandby = true;
4258 }
Eric Laurenta553c252009-07-17 12:17:14 -07004259 mActiveTrack.clear();
4260 mStartStopCond.broadcast();
4261 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004262 if (mReqChannelCount != mActiveTrack->channelCount()) {
4263 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004264 mStartStopCond.broadcast();
4265 } else if (mBytesRead != 0) {
4266 // record start succeeds only if first read from audio input
4267 // succeeds
4268 if (mBytesRead > 0) {
4269 mActiveTrack->mState = TrackBase::ACTIVE;
4270 } else {
4271 mActiveTrack.clear();
4272 }
4273 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004274 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004275 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004276 }
Eric Laurenta553c252009-07-17 12:17:14 -07004277 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004278 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004279 }
4280
4281 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004282 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4283 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004284 unlockEffectChains(effectChains);
4285 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004286 continue;
4287 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004288 for (size_t i = 0; i < effectChains.size(); i ++) {
4289 effectChains[i]->process_l();
4290 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004291
Eric Laurenta553c252009-07-17 12:17:14 -07004292 buffer.frameCount = mFrameCount;
4293 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4294 size_t framesOut = buffer.frameCount;
4295 if (mResampler == 0) {
4296 // no resampling
4297 while (framesOut) {
4298 size_t framesIn = mFrameCount - mRsmpInIndex;
4299 if (framesIn) {
4300 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4301 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4302 if (framesIn > framesOut)
4303 framesIn = framesOut;
4304 mRsmpInIndex += framesIn;
4305 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004306 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004307 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004308 memcpy(dst, src, framesIn * mFrameSize);
4309 } else {
4310 int16_t *src16 = (int16_t *)src;
4311 int16_t *dst16 = (int16_t *)dst;
4312 if (mChannelCount == 1) {
4313 while (framesIn--) {
4314 *dst16++ = *src16;
4315 *dst16++ = *src16++;
4316 }
4317 } else {
4318 while (framesIn--) {
4319 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4320 src16 += 2;
4321 }
4322 }
4323 }
4324 }
4325 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004326 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004327 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004328 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004329 framesOut = 0;
4330 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004331 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004332 mRsmpInIndex = 0;
4333 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004334 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004335 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004336 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004337 // Force input into standby so that it tries to
4338 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004339 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004340 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004341 }
Eric Laurenta553c252009-07-17 12:17:14 -07004342 mRsmpInIndex = mFrameCount;
4343 framesOut = 0;
4344 buffer.frameCount = 0;
4345 }
4346 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004347 }
4348 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004349 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004350
Eric Laurenta553c252009-07-17 12:17:14 -07004351 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4352 // alter output frame count as if we were expecting stereo samples
4353 if (mChannelCount == 1 && mReqChannelCount == 1) {
4354 framesOut >>= 1;
4355 }
4356 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4357 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4358 // are 32 bit aligned which should be always true.
4359 if (mChannelCount == 2 && mReqChannelCount == 1) {
4360 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4361 // the resampler always outputs stereo samples: do post stereo to mono conversion
4362 int16_t *src = (int16_t *)mRsmpOutBuffer;
4363 int16_t *dst = buffer.i16;
4364 while (framesOut--) {
4365 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4366 src += 2;
4367 }
4368 } else {
4369 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4370 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004371
Eric Laurenta553c252009-07-17 12:17:14 -07004372 }
4373 mActiveTrack->releaseBuffer(&buffer);
4374 mActiveTrack->overflow();
4375 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004376 // client isn't retrieving buffers fast enough
4377 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004378 if (!mActiveTrack->setOverflow()) {
4379 nsecs_t now = systemTime();
4380 if ((now - lastWarning) > kWarningThrottle) {
4381 LOGW("RecordThread: buffer overflow");
4382 lastWarning = now;
4383 }
4384 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004385 // Release the processor for a while before asking for a new buffer.
4386 // This will give the application more chance to read from the buffer and
4387 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004388 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004389 }
4390 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004391 // enable changes in effect chain
4392 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004393 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004394 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004395
Eric Laurenta553c252009-07-17 12:17:14 -07004396 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004397 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004398 }
Eric Laurenta553c252009-07-17 12:17:14 -07004399 mActiveTrack.clear();
4400
Eric Laurent49f02be2009-11-19 09:00:56 -08004401 mStartStopCond.broadcast();
4402
Eric Laurent6dbdc402011-07-22 09:04:31 -07004403 releaseWakeLock();
4404
Steve Block71f2cf12011-10-20 11:56:00 +01004405 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004406 return false;
4407}
4408
Eric Laurent464d5b32011-06-17 21:29:58 -07004409
4410sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4411 const sp<AudioFlinger::Client>& client,
4412 uint32_t sampleRate,
4413 int format,
4414 int channelMask,
4415 int frameCount,
4416 uint32_t flags,
4417 int sessionId,
4418 status_t *status)
4419{
4420 sp<RecordTrack> track;
4421 status_t lStatus;
4422
4423 lStatus = initCheck();
4424 if (lStatus != NO_ERROR) {
4425 LOGE("Audio driver not initialized.");
4426 goto Exit;
4427 }
4428
4429 { // scope for mLock
4430 Mutex::Autolock _l(mLock);
4431
4432 track = new RecordTrack(this, client, sampleRate,
4433 format, channelMask, frameCount, flags, sessionId);
4434
4435 if (track->getCblk() == NULL) {
4436 lStatus = NO_MEMORY;
4437 goto Exit;
4438 }
4439
4440 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004441 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4442 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004443 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004444 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4445 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004446 }
4447 lStatus = NO_ERROR;
4448
4449Exit:
4450 if (status) {
4451 *status = lStatus;
4452 }
4453 return track;
4454}
4455
Eric Laurenta553c252009-07-17 12:17:14 -07004456status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004457{
Steve Block71f2cf12011-10-20 11:56:00 +01004458 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004459 sp <ThreadBase> strongMe = this;
4460 status_t status = NO_ERROR;
4461 {
4462 AutoMutex lock(&mLock);
4463 if (mActiveTrack != 0) {
4464 if (recordTrack != mActiveTrack.get()) {
4465 status = -EBUSY;
4466 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004467 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004468 }
4469 return status;
4470 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004471
Eric Laurent49f02be2009-11-19 09:00:56 -08004472 recordTrack->mState = TrackBase::IDLE;
4473 mActiveTrack = recordTrack;
4474 mLock.unlock();
4475 status_t status = AudioSystem::startInput(mId);
4476 mLock.lock();
4477 if (status != NO_ERROR) {
4478 mActiveTrack.clear();
4479 return status;
4480 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004481 mRsmpInIndex = mFrameCount;
4482 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004483 if (mResampler != NULL) {
4484 mResampler->reset();
4485 }
4486 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004487 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004488 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004489 mWaitWorkCV.signal();
4490 // do not wait for mStartStopCond if exiting
4491 if (mExiting) {
4492 mActiveTrack.clear();
4493 status = INVALID_OPERATION;
4494 goto startError;
4495 }
4496 mStartStopCond.wait(mLock);
4497 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004498 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004499 status = BAD_VALUE;
4500 goto startError;
4501 }
Steve Block71f2cf12011-10-20 11:56:00 +01004502 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004503 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004504 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004505startError:
4506 AudioSystem::stopInput(mId);
4507 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004508}
4509
Eric Laurenta553c252009-07-17 12:17:14 -07004510void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004511 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004512 sp <ThreadBase> strongMe = this;
4513 {
4514 AutoMutex lock(&mLock);
4515 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4516 mActiveTrack->mState = TrackBase::PAUSING;
4517 // do not wait for mStartStopCond if exiting
4518 if (mExiting) {
4519 return;
4520 }
4521 mStartStopCond.wait(mLock);
4522 // if we have been restarted, recordTrack == mActiveTrack.get() here
4523 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4524 mLock.unlock();
4525 AudioSystem::stopInput(mId);
4526 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004527 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004528 }
4529 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004530 }
4531}
4532
Eric Laurenta553c252009-07-17 12:17:14 -07004533status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534{
4535 const size_t SIZE = 256;
4536 char buffer[SIZE];
4537 String8 result;
4538 pid_t pid = 0;
4539
Eric Laurent3fdb1262009-11-07 00:01:32 -08004540 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4541 result.append(buffer);
4542
4543 if (mActiveTrack != 0) {
4544 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004545 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004546 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004548
4549 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4550 result.append(buffer);
4551 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4552 result.append(buffer);
4553 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4554 result.append(buffer);
4555 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4556 result.append(buffer);
4557 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4558 result.append(buffer);
4559
4560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 } else {
4562 result.append("No record client\n");
4563 }
4564 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004565
4566 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004567 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 return NO_ERROR;
4570}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004571
Eric Laurenta553c252009-07-17 12:17:14 -07004572status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4573{
4574 size_t framesReq = buffer->frameCount;
4575 size_t framesReady = mFrameCount - mRsmpInIndex;
4576 int channelCount;
4577
4578 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004579 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004580 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004581 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004582 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004583 // Force input into standby so that it tries to
4584 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004585 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004586 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004587 }
Eric Laurenta553c252009-07-17 12:17:14 -07004588 buffer->raw = 0;
4589 buffer->frameCount = 0;
4590 return NOT_ENOUGH_DATA;
4591 }
4592 mRsmpInIndex = 0;
4593 framesReady = mFrameCount;
4594 }
4595
4596 if (framesReq > framesReady) {
4597 framesReq = framesReady;
4598 }
4599
4600 if (mChannelCount == 1 && mReqChannelCount == 2) {
4601 channelCount = 1;
4602 } else {
4603 channelCount = 2;
4604 }
4605 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4606 buffer->frameCount = framesReq;
4607 return NO_ERROR;
4608}
4609
4610void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4611{
4612 mRsmpInIndex += buffer->frameCount;
4613 buffer->frameCount = 0;
4614}
4615
4616bool AudioFlinger::RecordThread::checkForNewParameters_l()
4617{
4618 bool reconfig = false;
4619
Eric Laurent8fce46a2009-08-04 09:45:33 -07004620 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004621 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004622 String8 keyValuePair = mNewParameters[0];
4623 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004624 int value;
4625 int reqFormat = mFormat;
4626 int reqSamplingRate = mReqSampleRate;
4627 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004628
Eric Laurenta553c252009-07-17 12:17:14 -07004629 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4630 reqSamplingRate = value;
4631 reconfig = true;
4632 }
4633 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4634 reqFormat = value;
4635 reconfig = true;
4636 }
4637 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004638 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004639 reconfig = true;
4640 }
4641 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4642 // do not accept frame count changes if tracks are open as the track buffer
4643 // size depends on frame count and correct behavior would not be garantied
4644 // if frame count is changed after track creation
4645 if (mActiveTrack != 0) {
4646 status = INVALID_OPERATION;
4647 } else {
4648 reconfig = true;
4649 }
4650 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004651 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4652 // forward device change to effects that have requested to be
4653 // aware of attached audio device.
4654 for (size_t i = 0; i < mEffectChains.size(); i++) {
4655 mEffectChains[i]->setDevice_l(value);
4656 }
4657 // store input device and output device but do not forward output device to audio HAL.
4658 // Note that status is ignored by the caller for output device
4659 // (see AudioFlinger::setParameters()
4660 if (value & AUDIO_DEVICE_OUT_ALL) {
4661 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4662 status = BAD_VALUE;
4663 } else {
4664 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004665 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4666 if (mTrack != NULL) {
4667 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004668 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004669 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4670 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4671 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004672 }
4673 mDevice |= (uint32_t)value;
4674 }
Eric Laurenta553c252009-07-17 12:17:14 -07004675 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004676 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004677 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004678 mInput->stream->common.standby(&mInput->stream->common);
4679 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004680 }
4681 if (reconfig) {
4682 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004683 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004684 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004685 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4686 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004687 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004688 status = NO_ERROR;
4689 }
4690 if (status == NO_ERROR) {
4691 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004692 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004693 }
4694 }
4695 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004696
4697 mNewParameters.removeAt(0);
4698
Eric Laurenta553c252009-07-17 12:17:14 -07004699 mParamStatus = status;
4700 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004701 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4702 // already timed out waiting for the status and will never signal the condition.
4703 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07004704 }
4705 return reconfig;
4706}
4707
4708String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4709{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004710 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004711 String8 out_s8 = String8();
4712
4713 Mutex::Autolock _l(mLock);
4714 if (initCheck() != NO_ERROR) {
4715 return out_s8;
4716 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004717
Dima Zavin31f188892011-04-18 16:57:27 -07004718 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004719 out_s8 = String8(s);
4720 free(s);
4721 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004722}
4723
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004724void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004725 AudioSystem::OutputDescriptor desc;
4726 void *param2 = 0;
4727
4728 switch (event) {
4729 case AudioSystem::INPUT_OPENED:
4730 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004731 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004732 desc.samplingRate = mSampleRate;
4733 desc.format = mFormat;
4734 desc.frameCount = mFrameCount;
4735 desc.latency = 0;
4736 param2 = &desc;
4737 break;
4738
4739 case AudioSystem::INPUT_CLOSED:
4740 default:
4741 break;
4742 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004743 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004744}
4745
4746void AudioFlinger::RecordThread::readInputParameters()
4747{
4748 if (mRsmpInBuffer) delete mRsmpInBuffer;
4749 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4750 if (mResampler) delete mResampler;
4751 mResampler = 0;
4752
Dima Zavin31f188892011-04-18 16:57:27 -07004753 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004754 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4755 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004756 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4757 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4758 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004759 mFrameCount = mInputBytes / mFrameSize;
4760 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4761
4762 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4763 {
4764 int channelCount;
4765 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4766 // stereo to mono post process as the resampler always outputs stereo.
4767 if (mChannelCount == 1 && mReqChannelCount == 2) {
4768 channelCount = 1;
4769 } else {
4770 channelCount = 2;
4771 }
4772 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4773 mResampler->setSampleRate(mSampleRate);
4774 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4775 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4776
4777 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4778 if (mChannelCount == 1 && mReqChannelCount == 1) {
4779 mFrameCount >>= 1;
4780 }
4781
4782 }
4783 mRsmpInIndex = mFrameCount;
4784}
4785
Eric Laurent47d0a922010-02-26 02:47:27 -08004786unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4787{
Eric Laurent828b9772011-08-07 16:32:26 -07004788 Mutex::Autolock _l(mLock);
4789 if (initCheck() != NO_ERROR) {
4790 return 0;
4791 }
4792
Dima Zavin31f188892011-04-18 16:57:27 -07004793 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004794}
4795
Eric Laurent464d5b32011-06-17 21:29:58 -07004796uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4797{
4798 Mutex::Autolock _l(mLock);
4799 uint32_t result = 0;
4800 if (getEffectChain_l(sessionId) != 0) {
4801 result = EFFECT_SESSION;
4802 }
4803
4804 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4805 result |= TRACK_SESSION;
4806 }
4807
4808 return result;
4809}
4810
Eric Laurent6639b552011-08-01 09:52:20 -07004811AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4812{
4813 Mutex::Autolock _l(mLock);
4814 return mTrack;
4815}
4816
Eric Laurent828b9772011-08-07 16:32:26 -07004817AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4818{
4819 Mutex::Autolock _l(mLock);
4820 return mInput;
4821}
4822
4823AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4824{
4825 Mutex::Autolock _l(mLock);
4826 AudioStreamIn *input = mInput;
4827 mInput = NULL;
4828 return input;
4829}
4830
4831// this method must always be called either with ThreadBase mLock held or inside the thread loop
4832audio_stream_t* AudioFlinger::RecordThread::stream()
4833{
4834 if (mInput == NULL) {
4835 return NULL;
4836 }
4837 return &mInput->stream->common;
4838}
4839
4840
Eric Laurenta553c252009-07-17 12:17:14 -07004841// ----------------------------------------------------------------------------
4842
Eric Laurentddb78e72009-07-28 08:44:33 -07004843int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004844 uint32_t *pSamplingRate,
4845 uint32_t *pFormat,
4846 uint32_t *pChannels,
4847 uint32_t *pLatencyMs,
4848 uint32_t flags)
4849{
4850 status_t status;
4851 PlaybackThread *thread = NULL;
4852 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4853 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4854 uint32_t format = pFormat ? *pFormat : 0;
4855 uint32_t channels = pChannels ? *pChannels : 0;
4856 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004857 audio_stream_out_t *outStream;
4858 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004859
Steve Block71f2cf12011-10-20 11:56:00 +01004860 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004861 pDevices ? *pDevices : 0,
4862 samplingRate,
4863 format,
4864 channels,
4865 flags);
4866
4867 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004868 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004869 }
Dima Zavin31f188892011-04-18 16:57:27 -07004870
Eric Laurenta553c252009-07-17 12:17:14 -07004871 Mutex::Autolock _l(mLock);
4872
Dima Zavin31f188892011-04-18 16:57:27 -07004873 outHwDev = findSuitableHwDev_l(*pDevices);
4874 if (outHwDev == NULL)
4875 return 0;
4876
4877 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4878 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004879 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004880 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004881 samplingRate,
4882 format,
4883 channels,
4884 status);
4885
4886 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004887 if (outStream != NULL) {
4888 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004889 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004890
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004891 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4892 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4893 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004894 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004895 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004896 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004897 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004898 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004899 }
Eric Laurent65b65452010-06-01 23:49:17 -07004900 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004901
4902 if (pSamplingRate) *pSamplingRate = samplingRate;
4903 if (pFormat) *pFormat = format;
4904 if (pChannels) *pChannels = channels;
4905 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004906
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004907 // notify client processes of the new output creation
4908 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004909 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004910 }
4911
Eric Laurent9cc489a22009-12-05 05:20:01 -08004912 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004913}
4914
Eric Laurentddb78e72009-07-28 08:44:33 -07004915int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004916{
4917 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004918 MixerThread *thread1 = checkMixerThread_l(output1);
4919 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004920
Eric Laurentddb78e72009-07-28 08:44:33 -07004921 if (thread1 == NULL || thread2 == NULL) {
4922 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4923 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004924 }
4925
Eric Laurent464d5b32011-06-17 21:29:58 -07004926 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004927 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004928 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004929 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004930 // notify client processes of the new output creation
4931 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004932 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004933}
4934
Eric Laurentddb78e72009-07-28 08:44:33 -07004935status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004936{
Eric Laurent49018a52009-08-04 08:37:05 -07004937 // keep strong reference on the playback thread so that
4938 // it is not destroyed while exit() is executed
4939 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004940 {
4941 Mutex::Autolock _l(mLock);
4942 thread = checkPlaybackThread_l(output);
4943 if (thread == NULL) {
4944 return BAD_VALUE;
4945 }
4946
Steve Block71f2cf12011-10-20 11:56:00 +01004947 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004948
Eric Laurent464d5b32011-06-17 21:29:58 -07004949 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004950 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004951 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004952 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004953 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004954 }
4955 }
4956 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004957 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004958 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004959 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004960 }
4961 thread->exit();
4962
Eric Laurent464d5b32011-06-17 21:29:58 -07004963 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07004964 AudioStreamOut *out = thread->clearOutput();
4965 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07004966 out->hwDev->close_output_stream(out->hwDev, out->stream);
4967 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07004968 }
Eric Laurenta553c252009-07-17 12:17:14 -07004969 return NO_ERROR;
4970}
4971
Eric Laurentddb78e72009-07-28 08:44:33 -07004972status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004973{
4974 Mutex::Autolock _l(mLock);
4975 PlaybackThread *thread = checkPlaybackThread_l(output);
4976
4977 if (thread == NULL) {
4978 return BAD_VALUE;
4979 }
4980
Steve Block71f2cf12011-10-20 11:56:00 +01004981 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004982 thread->suspend();
4983
4984 return NO_ERROR;
4985}
4986
Eric Laurentddb78e72009-07-28 08:44:33 -07004987status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004988{
4989 Mutex::Autolock _l(mLock);
4990 PlaybackThread *thread = checkPlaybackThread_l(output);
4991
4992 if (thread == NULL) {
4993 return BAD_VALUE;
4994 }
4995
Steve Block71f2cf12011-10-20 11:56:00 +01004996 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004997
4998 thread->restore();
4999
5000 return NO_ERROR;
5001}
5002
Eric Laurentddb78e72009-07-28 08:44:33 -07005003int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005004 uint32_t *pSamplingRate,
5005 uint32_t *pFormat,
5006 uint32_t *pChannels,
5007 uint32_t acoustics)
5008{
5009 status_t status;
5010 RecordThread *thread = NULL;
5011 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5012 uint32_t format = pFormat ? *pFormat : 0;
5013 uint32_t channels = pChannels ? *pChannels : 0;
5014 uint32_t reqSamplingRate = samplingRate;
5015 uint32_t reqFormat = format;
5016 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005017 audio_stream_in_t *inStream;
5018 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005019
5020 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005021 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005022 }
Dima Zavin31f188892011-04-18 16:57:27 -07005023
Eric Laurenta553c252009-07-17 12:17:14 -07005024 Mutex::Autolock _l(mLock);
5025
Dima Zavin31f188892011-04-18 16:57:27 -07005026 inHwDev = findSuitableHwDev_l(*pDevices);
5027 if (inHwDev == NULL)
5028 return 0;
5029
5030 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5031 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005032 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005033 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005034 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005035 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005036 samplingRate,
5037 format,
5038 channels,
5039 acoustics,
5040 status);
5041
5042 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5043 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5044 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005045 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005046 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005047 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005048 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005049 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005050 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5051 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005052 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005053 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005054 }
5055
Dima Zavin31f188892011-04-18 16:57:27 -07005056 if (inStream != NULL) {
5057 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5058
Eric Laurent464d5b32011-06-17 21:29:58 -07005059 int id = nextUniqueId();
5060 // Start record thread
5061 // RecorThread require both input and output device indication to forward to audio
5062 // pre processing modules
5063 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5064 thread = new RecordThread(this,
5065 input,
5066 reqSamplingRate,
5067 reqChannels,
5068 id,
5069 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005070 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005071 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005072 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5073 if (pFormat) *pFormat = format;
5074 if (pChannels) *pChannels = reqChannels;
5075
Dima Zavin31f188892011-04-18 16:57:27 -07005076 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005077
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005078 // notify client processes of the new input creation
5079 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005080 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005081 }
5082
Eric Laurent9cc489a22009-12-05 05:20:01 -08005083 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005084}
5085
Eric Laurentddb78e72009-07-28 08:44:33 -07005086status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005087{
Eric Laurent49018a52009-08-04 08:37:05 -07005088 // keep strong reference on the record thread so that
5089 // it is not destroyed while exit() is executed
5090 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005091 {
5092 Mutex::Autolock _l(mLock);
5093 thread = checkRecordThread_l(input);
5094 if (thread == NULL) {
5095 return BAD_VALUE;
5096 }
5097
Steve Block71f2cf12011-10-20 11:56:00 +01005098 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005099 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005100 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005101 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005102 }
5103 thread->exit();
5104
Eric Laurent828b9772011-08-07 16:32:26 -07005105 AudioStreamIn *in = thread->clearInput();
5106 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005107 in->hwDev->close_input_stream(in->hwDev, in->stream);
5108 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005109
Eric Laurenta553c252009-07-17 12:17:14 -07005110 return NO_ERROR;
5111}
5112
Eric Laurentddb78e72009-07-28 08:44:33 -07005113status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005114{
5115 Mutex::Autolock _l(mLock);
5116 MixerThread *dstThread = checkMixerThread_l(output);
5117 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005118 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005119 return BAD_VALUE;
5120 }
5121
Steve Block71f2cf12011-10-20 11:56:00 +01005122 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005123 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005124
Eric Laurent05ce0942011-08-30 10:18:54 -07005125 dstThread->setStreamValid(stream, true);
5126
Eric Laurenta553c252009-07-17 12:17:14 -07005127 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005128 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005129 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005130 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005131 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005132 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005133 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005134 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005135 }
Eric Laurentd069f322009-09-01 05:56:26 -07005136
Eric Laurenta553c252009-07-17 12:17:14 -07005137 return NO_ERROR;
5138}
5139
Eric Laurent65b65452010-06-01 23:49:17 -07005140
5141int AudioFlinger::newAudioSessionId()
5142{
Eric Laurent464d5b32011-06-17 21:29:58 -07005143 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005144}
5145
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005146void AudioFlinger::acquireAudioSessionId(int audioSession)
5147{
5148 Mutex::Autolock _l(mLock);
5149 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005150 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005151 int num = mAudioSessionRefs.size();
5152 for (int i = 0; i< num; i++) {
5153 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5154 if (ref->sessionid == audioSession && ref->pid == caller) {
5155 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005156 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005157 return;
5158 }
5159 }
5160 AudioSessionRef *ref = new AudioSessionRef();
5161 ref->sessionid = audioSession;
5162 ref->pid = caller;
5163 ref->cnt = 1;
5164 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005165 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005166}
5167
5168void AudioFlinger::releaseAudioSessionId(int audioSession)
5169{
5170 Mutex::Autolock _l(mLock);
5171 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005172 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005173 int num = mAudioSessionRefs.size();
5174 for (int i = 0; i< num; i++) {
5175 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5176 if (ref->sessionid == audioSession && ref->pid == caller) {
5177 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005178 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005179 if (ref->cnt == 0) {
5180 mAudioSessionRefs.removeAt(i);
5181 delete ref;
5182 purgeStaleEffects_l();
5183 }
5184 return;
5185 }
5186 }
5187 LOGW("session id %d not found for pid %d", audioSession, caller);
5188}
5189
5190void AudioFlinger::purgeStaleEffects_l() {
5191
Steve Block71f2cf12011-10-20 11:56:00 +01005192 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005193
5194 Vector< sp<EffectChain> > chains;
5195
5196 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5197 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5198 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5199 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005200 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5201 chains.push(ec);
5202 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005203 }
5204 }
5205 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5206 sp<RecordThread> t = mRecordThreads.valueAt(i);
5207 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5208 sp<EffectChain> ec = t->mEffectChains[j];
5209 chains.push(ec);
5210 }
5211 }
5212
5213 for (size_t i = 0; i < chains.size(); i++) {
5214 sp<EffectChain> ec = chains[i];
5215 int sessionid = ec->sessionId();
5216 sp<ThreadBase> t = ec->mThread.promote();
5217 if (t == 0) {
5218 continue;
5219 }
5220 size_t numsessionrefs = mAudioSessionRefs.size();
5221 bool found = false;
5222 for (size_t k = 0; k < numsessionrefs; k++) {
5223 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5224 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005225 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005226 sessionid, ref->pid, ref->cnt);
5227 found = true;
5228 break;
5229 }
5230 }
5231 if (!found) {
5232 // remove all effects from the chain
5233 while (ec->mEffects.size()) {
5234 sp<EffectModule> effect = ec->mEffects[0];
5235 effect->unPin();
5236 Mutex::Autolock _l (t->mLock);
5237 t->removeEffect_l(effect);
5238 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5239 sp<EffectHandle> handle = effect->mHandles[j].promote();
5240 if (handle != 0) {
5241 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005242 if (handle->mHasControl && handle->mEnabled) {
5243 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5244 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005245 }
5246 }
5247 AudioSystem::unregisterEffect(effect->id());
5248 }
5249 }
5250 }
5251 return;
5252}
5253
Eric Laurenta553c252009-07-17 12:17:14 -07005254// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005255AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005256{
5257 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005258 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5259 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005260 }
Eric Laurenta553c252009-07-17 12:17:14 -07005261 return thread;
5262}
5263
5264// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005265AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005266{
5267 PlaybackThread *thread = checkPlaybackThread_l(output);
5268 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005269 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005270 thread = NULL;
5271 }
5272 }
5273 return (MixerThread *)thread;
5274}
5275
5276// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005277AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005278{
5279 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005280 if (mRecordThreads.indexOfKey(input) >= 0) {
5281 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005282 }
Eric Laurenta553c252009-07-17 12:17:14 -07005283 return thread;
5284}
5285
Eric Laurent464d5b32011-06-17 21:29:58 -07005286uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005287{
Eric Laurent464d5b32011-06-17 21:29:58 -07005288 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005289}
5290
Eric Laurent464d5b32011-06-17 21:29:58 -07005291AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5292{
5293 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5294 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005295 AudioStreamOut *output = thread->getOutput();
5296 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005297 return thread;
5298 }
5299 }
5300 return NULL;
5301}
5302
5303uint32_t AudioFlinger::primaryOutputDevice_l()
5304{
5305 PlaybackThread *thread = primaryPlaybackThread_l();
5306
5307 if (thread == NULL) {
5308 return 0;
5309 }
5310
5311 return thread->device();
5312}
5313
5314
Eric Laurent65b65452010-06-01 23:49:17 -07005315// ----------------------------------------------------------------------------
5316// Effect management
5317// ----------------------------------------------------------------------------
5318
5319
Eric Laurent65b65452010-06-01 23:49:17 -07005320status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5321{
5322 Mutex::Autolock _l(mLock);
5323 return EffectQueryNumberEffects(numEffects);
5324}
5325
Eric Laurent53334cd2010-06-23 17:38:20 -07005326status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005327{
5328 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005329 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005330}
5331
5332status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5333{
5334 Mutex::Autolock _l(mLock);
5335 return EffectGetDescriptor(pUuid, descriptor);
5336}
5337
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005338
Eric Laurent65b65452010-06-01 23:49:17 -07005339sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5340 effect_descriptor_t *pDesc,
5341 const sp<IEffectClient>& effectClient,
5342 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005343 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005344 int sessionId,
5345 status_t *status,
5346 int *id,
5347 int *enabled)
5348{
5349 status_t lStatus = NO_ERROR;
5350 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005351 effect_descriptor_t desc;
5352 sp<Client> client;
5353 wp<Client> wclient;
5354
Steve Block71f2cf12011-10-20 11:56:00 +01005355 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005356 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005357
5358 if (pDesc == NULL) {
5359 lStatus = BAD_VALUE;
5360 goto Exit;
5361 }
5362
Eric Laurent98c92592010-09-23 16:10:16 -07005363 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005364 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005365 lStatus = PERMISSION_DENIED;
5366 goto Exit;
5367 }
5368
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005369 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005370 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005371 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005372 lStatus = PERMISSION_DENIED;
5373 goto Exit;
5374 }
5375
Eric Laurent464d5b32011-06-17 21:29:58 -07005376 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005377 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005378 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005379 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005380 lStatus = BAD_VALUE;
5381 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005382 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005383 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005384 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005385 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005386 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005387 }
5388 }
5389
Eric Laurent65b65452010-06-01 23:49:17 -07005390 {
5391 Mutex::Autolock _l(mLock);
5392
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005393
Eric Laurent65b65452010-06-01 23:49:17 -07005394 if (!EffectIsNullUuid(&pDesc->uuid)) {
5395 // if uuid is specified, request effect descriptor
5396 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5397 if (lStatus < 0) {
5398 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5399 goto Exit;
5400 }
5401 } else {
5402 // if uuid is not specified, look for an available implementation
5403 // of the required type in effect factory
5404 if (EffectIsNullUuid(&pDesc->type)) {
5405 LOGW("createEffect() no effect type");
5406 lStatus = BAD_VALUE;
5407 goto Exit;
5408 }
5409 uint32_t numEffects = 0;
5410 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005411 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005412 bool found = false;
5413
5414 lStatus = EffectQueryNumberEffects(&numEffects);
5415 if (lStatus < 0) {
5416 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5417 goto Exit;
5418 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005419 for (uint32_t i = 0; i < numEffects; i++) {
5420 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005421 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005422 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005423 continue;
5424 }
5425 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5426 // If matching type found save effect descriptor. If the session is
5427 // 0 and the effect is not auxiliary, continue enumeration in case
5428 // an auxiliary version of this effect type is available
5429 found = true;
5430 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005431 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005432 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5433 break;
5434 }
5435 }
5436 }
5437 if (!found) {
5438 lStatus = BAD_VALUE;
5439 LOGW("createEffect() effect not found");
5440 goto Exit;
5441 }
5442 // For same effect type, chose auxiliary version over insert version if
5443 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005444 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005445 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5446 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5447 }
5448 }
5449
5450 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005451 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005452 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5453 lStatus = INVALID_OPERATION;
5454 goto Exit;
5455 }
5456
Eric Laurentf82fccd2011-07-27 19:49:51 -07005457 // check recording permission for visualizer
5458 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5459 !recordingAllowed()) {
5460 lStatus = PERMISSION_DENIED;
5461 goto Exit;
5462 }
5463
Eric Laurent65b65452010-06-01 23:49:17 -07005464 // return effect descriptor
5465 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5466
5467 // If output is not specified try to find a matching audio session ID in one of the
5468 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005469 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5470 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005471 // Note: io is never 0 when creating an effect on an input
5472 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005473 // look for the thread where the specified audio session is present
5474 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5475 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005476 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005477 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005478 }
Eric Laurent65b65452010-06-01 23:49:17 -07005479 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005480 if (io == 0) {
5481 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5482 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5483 io = mRecordThreads.keyAt(i);
5484 break;
5485 }
5486 }
5487 }
Eric Laurent98c92592010-09-23 16:10:16 -07005488 // If no output thread contains the requested session ID, default to
5489 // first output. The effect chain will be moved to the correct output
5490 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005491 if (io == 0 && mPlaybackThreads.size()) {
5492 io = mPlaybackThreads.keyAt(0);
5493 }
Steve Block71f2cf12011-10-20 11:56:00 +01005494 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005495 }
5496 ThreadBase *thread = checkRecordThread_l(io);
5497 if (thread == NULL) {
5498 thread = checkPlaybackThread_l(io);
5499 if (thread == NULL) {
5500 LOGE("createEffect() unknown output thread");
5501 lStatus = BAD_VALUE;
5502 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005503 }
Eric Laurent65b65452010-06-01 23:49:17 -07005504 }
Eric Laurent98c92592010-09-23 16:10:16 -07005505
Eric Laurent65b65452010-06-01 23:49:17 -07005506 wclient = mClients.valueFor(pid);
5507
5508 if (wclient != NULL) {
5509 client = wclient.promote();
5510 } else {
5511 client = new Client(this, pid);
5512 mClients.add(pid, client);
5513 }
5514
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005515 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005516 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5517 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005518 if (handle != 0 && id != NULL) {
5519 *id = handle->id();
5520 }
5521 }
5522
5523Exit:
5524 if(status) {
5525 *status = lStatus;
5526 }
5527 return handle;
5528}
5529
Eric Laurentf82fccd2011-07-27 19:49:51 -07005530status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005531{
Steve Block71f2cf12011-10-20 11:56:00 +01005532 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005533 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005534 Mutex::Autolock _l(mLock);
5535 if (srcOutput == dstOutput) {
5536 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5537 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005538 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005539 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5540 if (srcThread == NULL) {
5541 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5542 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005543 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005544 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5545 if (dstThread == NULL) {
5546 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5547 return BAD_VALUE;
5548 }
5549
5550 Mutex::Autolock _dl(dstThread->mLock);
5551 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005552 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005553
Eric Laurent53334cd2010-06-23 17:38:20 -07005554 return NO_ERROR;
5555}
5556
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005557// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005558status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005559 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005560 AudioFlinger::PlaybackThread *dstThread,
5561 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005562{
Steve Block71f2cf12011-10-20 11:56:00 +01005563 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005564 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005565
Eric Laurentf82fccd2011-07-27 19:49:51 -07005566 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005567 if (chain == 0) {
5568 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005569 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005570 return INVALID_OPERATION;
5571 }
5572
Eric Laurent493941b2010-07-28 01:32:47 -07005573 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005574 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005575 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005576 // removed.
5577 srcThread->removeEffectChain_l(chain);
5578
5579 // transfer all effects one by one so that new effect chain is created on new thread with
5580 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005581 int dstOutput = dstThread->id();
5582 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005583 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005584 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5585 while (effect != 0) {
5586 srcThread->removeEffect_l(effect);
5587 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005588 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5589 if (effect->state() == EffectModule::ACTIVE ||
5590 effect->state() == EffectModule::STOPPING) {
5591 effect->start();
5592 }
Eric Laurent493941b2010-07-28 01:32:47 -07005593 // if the move request is not received from audio policy manager, the effect must be
5594 // re-registered with the new strategy and output
5595 if (dstChain == 0) {
5596 dstChain = effect->chain().promote();
5597 if (dstChain == 0) {
5598 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5599 srcThread->addEffect_l(effect);
5600 return NO_INIT;
5601 }
5602 strategy = dstChain->strategy();
5603 }
5604 if (reRegister) {
5605 AudioSystem::unregisterEffect(effect->id());
5606 AudioSystem::registerEffect(&effect->desc(),
5607 dstOutput,
5608 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005609 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005610 effect->id());
5611 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612 effect = chain->getEffectFromId_l(0);
5613 }
5614
5615 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005616}
5617
Eric Laurent464d5b32011-06-17 21:29:58 -07005618
Eric Laurent65b65452010-06-01 23:49:17 -07005619// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005620sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005621 const sp<AudioFlinger::Client>& client,
5622 const sp<IEffectClient>& effectClient,
5623 int32_t priority,
5624 int sessionId,
5625 effect_descriptor_t *desc,
5626 int *enabled,
5627 status_t *status
5628 )
5629{
5630 sp<EffectModule> effect;
5631 sp<EffectHandle> handle;
5632 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005633 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005634 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005635 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005636 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005637
Eric Laurent464d5b32011-06-17 21:29:58 -07005638 lStatus = initCheck();
5639 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005640 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005641 goto Exit;
5642 }
5643
5644 // Do not allow effects with session ID 0 on direct output or duplicating threads
5645 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005646 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005647 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5648 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005649 lStatus = BAD_VALUE;
5650 goto Exit;
5651 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005652 // Only Pre processor effects are allowed on input threads and only on input threads
5653 if ((mType == RECORD &&
5654 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5655 (mType != RECORD &&
5656 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5657 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5658 desc->name, desc->flags, mType);
5659 lStatus = BAD_VALUE;
5660 goto Exit;
5661 }
Eric Laurent65b65452010-06-01 23:49:17 -07005662
Steve Block71f2cf12011-10-20 11:56:00 +01005663 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005664
5665 { // scope for mLock
5666 Mutex::Autolock _l(mLock);
5667
5668 // check for existing effect chain with the requested audio session
5669 chain = getEffectChain_l(sessionId);
5670 if (chain == 0) {
5671 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005672 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005673 chain = new EffectChain(this, sessionId);
5674 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005675 chain->setStrategy(getStrategyForSession_l(sessionId));
5676 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005677 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005678 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005679 }
5680
Steve Block71f2cf12011-10-20 11:56:00 +01005681 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005682
5683 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005684 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005685 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005686 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005687 if (lStatus != NO_ERROR) {
5688 goto Exit;
5689 }
5690 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005691 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005692 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005693 lStatus = effect->status();
5694 if (lStatus != NO_ERROR) {
5695 goto Exit;
5696 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005697 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005698 if (lStatus != NO_ERROR) {
5699 goto Exit;
5700 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005701 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005702
5703 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005704 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005705 }
5706 // create effect handle and connect it to effect module
5707 handle = new EffectHandle(effect, client, effectClient, priority);
5708 lStatus = effect->addHandle(handle);
5709 if (enabled) {
5710 *enabled = (int)effect->isEnabled();
5711 }
5712 }
5713
5714Exit:
5715 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005716 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005717 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005718 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005719 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005720 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005721 AudioSystem::unregisterEffect(effect->id());
5722 }
5723 if (chainCreated) {
5724 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005725 }
Eric Laurent65b65452010-06-01 23:49:17 -07005726 handle.clear();
5727 }
5728
5729 if(status) {
5730 *status = lStatus;
5731 }
5732 return handle;
5733}
5734
Eric Laurent464d5b32011-06-17 21:29:58 -07005735sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5736{
5737 sp<EffectModule> effect;
5738
5739 sp<EffectChain> chain = getEffectChain_l(sessionId);
5740 if (chain != 0) {
5741 effect = chain->getEffectFromId_l(effectId);
5742 }
5743 return effect;
5744}
5745
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005746// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5747// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005748status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005749{
5750 // check for existing effect chain with the requested audio session
5751 int sessionId = effect->sessionId();
5752 sp<EffectChain> chain = getEffectChain_l(sessionId);
5753 bool chainCreated = false;
5754
5755 if (chain == 0) {
5756 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005757 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005758 chain = new EffectChain(this, sessionId);
5759 addEffectChain_l(chain);
5760 chain->setStrategy(getStrategyForSession_l(sessionId));
5761 chainCreated = true;
5762 }
Steve Block71f2cf12011-10-20 11:56:00 +01005763 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005764
5765 if (chain->getEffectFromId_l(effect->id()) != 0) {
5766 LOGW("addEffect_l() %p effect %s already present in chain %p",
5767 this, effect->desc().name, chain.get());
5768 return BAD_VALUE;
5769 }
5770
5771 status_t status = chain->addEffect_l(effect);
5772 if (status != NO_ERROR) {
5773 if (chainCreated) {
5774 removeEffectChain_l(chain);
5775 }
5776 return status;
5777 }
5778
5779 effect->setDevice(mDevice);
5780 effect->setMode(mAudioFlinger->getMode());
5781 return NO_ERROR;
5782}
5783
Eric Laurent464d5b32011-06-17 21:29:58 -07005784void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005785
Steve Block71f2cf12011-10-20 11:56:00 +01005786 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005787 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005788 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5789 detachAuxEffect_l(effect->id());
5790 }
5791
5792 sp<EffectChain> chain = effect->chain().promote();
5793 if (chain != 0) {
5794 // remove effect chain if removing last effect
5795 if (chain->removeEffect_l(effect) == 0) {
5796 removeEffectChain_l(chain);
5797 }
5798 } else {
5799 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5800 }
5801}
5802
Eric Laurent464d5b32011-06-17 21:29:58 -07005803void AudioFlinger::ThreadBase::lockEffectChains_l(
5804 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5805{
5806 effectChains = mEffectChains;
5807 for (size_t i = 0; i < mEffectChains.size(); i++) {
5808 mEffectChains[i]->lock();
5809 }
5810}
5811
5812void AudioFlinger::ThreadBase::unlockEffectChains(
5813 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5814{
5815 for (size_t i = 0; i < effectChains.size(); i++) {
5816 effectChains[i]->unlock();
5817 }
5818}
5819
5820sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5821{
5822 Mutex::Autolock _l(mLock);
5823 return getEffectChain_l(sessionId);
5824}
5825
5826sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5827{
5828 sp<EffectChain> chain;
5829
5830 size_t size = mEffectChains.size();
5831 for (size_t i = 0; i < size; i++) {
5832 if (mEffectChains[i]->sessionId() == sessionId) {
5833 chain = mEffectChains[i];
5834 break;
5835 }
5836 }
5837 return chain;
5838}
5839
5840void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5841{
5842 Mutex::Autolock _l(mLock);
5843 size_t size = mEffectChains.size();
5844 for (size_t i = 0; i < size; i++) {
5845 mEffectChains[i]->setMode_l(mode);
5846 }
5847}
5848
5849void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005850 const wp<EffectHandle>& handle,
5851 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005852
Eric Laurent53334cd2010-06-23 17:38:20 -07005853 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005854 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005855 // delete the effect module if removing last handle on it
5856 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005857 if (!effect->isPinned() || unpiniflast) {
5858 removeEffect_l(effect);
5859 AudioSystem::unregisterEffect(effect->id());
5860 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005861 }
5862}
5863
Eric Laurent65b65452010-06-01 23:49:17 -07005864status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5865{
5866 int session = chain->sessionId();
5867 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005868 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005869
Steve Block71f2cf12011-10-20 11:56:00 +01005870 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005871 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005872 // Only one effect chain can be present in direct output thread and it uses
5873 // the mix buffer as input
5874 if (mType != DIRECT) {
5875 size_t numSamples = mFrameCount * mChannelCount;
5876 buffer = new int16_t[numSamples];
5877 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005878 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005879 ownsBuffer = true;
5880 }
Eric Laurent65b65452010-06-01 23:49:17 -07005881
Eric Laurent53334cd2010-06-23 17:38:20 -07005882 // Attach all tracks with same session ID to this chain.
5883 for (size_t i = 0; i < mTracks.size(); ++i) {
5884 sp<Track> track = mTracks[i];
5885 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005886 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005887 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005888 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005889 }
5890 }
5891
5892 // indicate all active tracks in the chain
5893 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5894 sp<Track> track = mActiveTracks[i].promote();
5895 if (track == 0) continue;
5896 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005897 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005898 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005899 }
Eric Laurent65b65452010-06-01 23:49:17 -07005900 }
5901 }
5902
Eric Laurent53334cd2010-06-23 17:38:20 -07005903 chain->setInBuffer(buffer, ownsBuffer);
5904 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005905 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005906 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005907 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5908 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005909 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005910 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5911 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005912 // Effect chain for other sessions are inserted at beginning of effect
5913 // chains list to be processed before output mix effects. Relative order between other
5914 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005915 size_t size = mEffectChains.size();
5916 size_t i = 0;
5917 for (i = 0; i < size; i++) {
5918 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005919 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005920 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005921 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005922
5923 return NO_ERROR;
5924}
5925
5926size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5927{
5928 int session = chain->sessionId();
5929
Steve Block71f2cf12011-10-20 11:56:00 +01005930 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005931
5932 for (size_t i = 0; i < mEffectChains.size(); i++) {
5933 if (chain == mEffectChains[i]) {
5934 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005935 // detach all active tracks from the chain
5936 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5937 sp<Track> track = mActiveTracks[i].promote();
5938 if (track == 0) continue;
5939 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005940 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005941 chain.get(), session);
5942 chain->decActiveTrackCnt();
5943 }
5944 }
5945
Eric Laurent65b65452010-06-01 23:49:17 -07005946 // detach all tracks with same session ID from this chain
5947 for (size_t i = 0; i < mTracks.size(); ++i) {
5948 sp<Track> track = mTracks[i];
5949 if (session == track->sessionId()) {
5950 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005951 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005952 }
5953 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005954 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005955 }
5956 }
5957 return mEffectChains.size();
5958}
5959
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005960status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5961 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005962{
5963 Mutex::Autolock _l(mLock);
5964 return attachAuxEffect_l(track, EffectId);
5965}
5966
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005967status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5968 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005969{
5970 status_t status = NO_ERROR;
5971
5972 if (EffectId == 0) {
5973 track->setAuxBuffer(0, NULL);
5974 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005975 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5976 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005977 if (effect != 0) {
5978 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5979 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5980 } else {
5981 status = INVALID_OPERATION;
5982 }
5983 } else {
5984 status = BAD_VALUE;
5985 }
5986 }
5987 return status;
5988}
5989
5990void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5991{
5992 for (size_t i = 0; i < mTracks.size(); ++i) {
5993 sp<Track> track = mTracks[i];
5994 if (track->auxEffectId() == effectId) {
5995 attachAuxEffect_l(track, 0);
5996 }
5997 }
5998}
5999
Eric Laurent464d5b32011-06-17 21:29:58 -07006000status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6001{
6002 // only one chain per input thread
6003 if (mEffectChains.size() != 0) {
6004 return INVALID_OPERATION;
6005 }
Steve Block71f2cf12011-10-20 11:56:00 +01006006 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006007
6008 chain->setInBuffer(NULL);
6009 chain->setOutBuffer(NULL);
6010
Eric Laurentf82fccd2011-07-27 19:49:51 -07006011 checkSuspendOnAddEffectChain_l(chain);
6012
Eric Laurent464d5b32011-06-17 21:29:58 -07006013 mEffectChains.add(chain);
6014
6015 return NO_ERROR;
6016}
6017
6018size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6019{
Steve Block71f2cf12011-10-20 11:56:00 +01006020 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006021 LOGW_IF(mEffectChains.size() != 1,
6022 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6023 chain.get(), mEffectChains.size(), this);
6024 if (mEffectChains.size() == 1) {
6025 mEffectChains.removeAt(0);
6026 }
6027 return 0;
6028}
6029
Eric Laurent65b65452010-06-01 23:49:17 -07006030// ----------------------------------------------------------------------------
6031// EffectModule implementation
6032// ----------------------------------------------------------------------------
6033
6034#undef LOG_TAG
6035#define LOG_TAG "AudioFlinger::EffectModule"
6036
6037AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6038 const wp<AudioFlinger::EffectChain>& chain,
6039 effect_descriptor_t *desc,
6040 int id,
6041 int sessionId)
6042 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006043 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006044{
Steve Block71f2cf12011-10-20 11:56:00 +01006045 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006046 int lStatus;
6047 sp<ThreadBase> thread = mThread.promote();
6048 if (thread == 0) {
6049 return;
6050 }
Eric Laurent65b65452010-06-01 23:49:17 -07006051
6052 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6053
6054 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006055 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006056
Eric Laurent65b65452010-06-01 23:49:17 -07006057 if (mStatus != NO_ERROR) {
6058 return;
6059 }
6060 lStatus = init();
6061 if (lStatus < 0) {
6062 mStatus = lStatus;
6063 goto Error;
6064 }
6065
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006066 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6067 mPinned = true;
6068 }
Steve Block71f2cf12011-10-20 11:56:00 +01006069 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006070 return;
6071Error:
6072 EffectRelease(mEffectInterface);
6073 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006074 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006075}
6076
6077AudioFlinger::EffectModule::~EffectModule()
6078{
Steve Block71f2cf12011-10-20 11:56:00 +01006079 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006080 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006081 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6082 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6083 sp<ThreadBase> thread = mThread.promote();
6084 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006085 audio_stream_t *stream = thread->stream();
6086 if (stream != NULL) {
6087 stream->remove_audio_effect(stream, mEffectInterface);
6088 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006089 }
6090 }
Eric Laurent65b65452010-06-01 23:49:17 -07006091 // release effect engine
6092 EffectRelease(mEffectInterface);
6093 }
6094}
6095
6096status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6097{
6098 status_t status;
6099
6100 Mutex::Autolock _l(mLock);
6101 // First handle in mHandles has highest priority and controls the effect module
6102 int priority = handle->priority();
6103 size_t size = mHandles.size();
6104 sp<EffectHandle> h;
6105 size_t i;
6106 for (i = 0; i < size; i++) {
6107 h = mHandles[i].promote();
6108 if (h == 0) continue;
6109 if (h->priority() <= priority) break;
6110 }
6111 // if inserted in first place, move effect control from previous owner to this handle
6112 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006113 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006114 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006115 enabled = h->enabled();
6116 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006117 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006118 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006119 status = NO_ERROR;
6120 } else {
6121 status = ALREADY_EXISTS;
6122 }
Steve Block71f2cf12011-10-20 11:56:00 +01006123 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006124 mHandles.insertAt(handle, i);
6125 return status;
6126}
6127
6128size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6129{
6130 Mutex::Autolock _l(mLock);
6131 size_t size = mHandles.size();
6132 size_t i;
6133 for (i = 0; i < size; i++) {
6134 if (mHandles[i] == handle) break;
6135 }
6136 if (i == size) {
6137 return size;
6138 }
Steve Block71f2cf12011-10-20 11:56:00 +01006139 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006140
6141 bool enabled = false;
6142 EffectHandle *hdl = handle.unsafe_get();
6143 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006144 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006145 enabled = hdl->enabled();
6146 }
Eric Laurent65b65452010-06-01 23:49:17 -07006147 mHandles.removeAt(i);
6148 size = mHandles.size();
6149 // if removed from first place, move effect control from this handle to next in line
6150 if (i == 0 && size != 0) {
6151 sp<EffectHandle> h = mHandles[0].promote();
6152 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006153 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006154 }
6155 }
6156
Eric Laurent21b5c472011-07-26 20:54:46 -07006157 // Prevent calls to process() and other functions on effect interface from now on.
6158 // The effect engine will be released by the destructor when the last strong reference on
6159 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006160 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006161 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006162 }
6163
Eric Laurent65b65452010-06-01 23:49:17 -07006164 return size;
6165}
6166
Eric Laurentf82fccd2011-07-27 19:49:51 -07006167sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6168{
6169 Mutex::Autolock _l(mLock);
6170 sp<EffectHandle> handle;
6171 if (mHandles.size() != 0) {
6172 handle = mHandles[0].promote();
6173 }
6174 return handle;
6175}
6176
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006177void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006178{
Steve Block71f2cf12011-10-20 11:56:00 +01006179 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006180 // keep a strong reference on this EffectModule to avoid calling the
6181 // destructor before we exit
6182 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006183 {
6184 sp<ThreadBase> thread = mThread.promote();
6185 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006186 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006187 }
6188 }
6189}
6190
Eric Laurent7d850f22010-07-09 13:34:17 -07006191void AudioFlinger::EffectModule::updateState() {
6192 Mutex::Autolock _l(mLock);
6193
6194 switch (mState) {
6195 case RESTART:
6196 reset_l();
6197 // FALL THROUGH
6198
6199 case STARTING:
6200 // clear auxiliary effect input buffer for next accumulation
6201 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6202 memset(mConfig.inputCfg.buffer.raw,
6203 0,
6204 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6205 }
6206 start_l();
6207 mState = ACTIVE;
6208 break;
6209 case STOPPING:
6210 stop_l();
6211 mDisableWaitCnt = mMaxDisableWaitCnt;
6212 mState = STOPPED;
6213 break;
6214 case STOPPED:
6215 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6216 // turn off sequence.
6217 if (--mDisableWaitCnt == 0) {
6218 reset_l();
6219 mState = IDLE;
6220 }
6221 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006222 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006223 break;
6224 }
6225}
6226
Eric Laurent65b65452010-06-01 23:49:17 -07006227void AudioFlinger::EffectModule::process()
6228{
6229 Mutex::Autolock _l(mLock);
6230
Eric Laurent21b5c472011-07-26 20:54:46 -07006231 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006232 mConfig.inputCfg.buffer.raw == NULL ||
6233 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006234 return;
6235 }
6236
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006237 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006238 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6239 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6240 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6241 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006242 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006243 }
6244
Eric Laurent65b65452010-06-01 23:49:17 -07006245 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006246 int ret = (*mEffectInterface)->process(mEffectInterface,
6247 &mConfig.inputCfg.buffer,
6248 &mConfig.outputCfg.buffer);
6249
6250 // force transition to IDLE state when engine is ready
6251 if (mState == STOPPED && ret == -ENODATA) {
6252 mDisableWaitCnt = 1;
6253 }
Eric Laurent65b65452010-06-01 23:49:17 -07006254
6255 // clear auxiliary effect input buffer for next accumulation
6256 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006257 memset(mConfig.inputCfg.buffer.raw, 0,
6258 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006259 }
6260 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006261 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6262 // If an insert effect is idle and input buffer is different from output buffer,
6263 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006264 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006265 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006266 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6267 int16_t *in = mConfig.inputCfg.buffer.s16;
6268 int16_t *out = mConfig.outputCfg.buffer.s16;
6269 for (size_t i = 0; i < frameCnt; i++) {
6270 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006271 }
Eric Laurent65b65452010-06-01 23:49:17 -07006272 }
6273 }
6274}
6275
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006276void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006277{
6278 if (mEffectInterface == NULL) {
6279 return;
6280 }
6281 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6282}
6283
6284status_t AudioFlinger::EffectModule::configure()
6285{
6286 uint32_t channels;
6287 if (mEffectInterface == NULL) {
6288 return NO_INIT;
6289 }
6290
6291 sp<ThreadBase> thread = mThread.promote();
6292 if (thread == 0) {
6293 return DEAD_OBJECT;
6294 }
6295
6296 // TODO: handle configuration of effects replacing track process
6297 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006298 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006299 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006300 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006301 }
6302
6303 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006304 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006305 } else {
6306 mConfig.inputCfg.channels = channels;
6307 }
6308 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006309 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6310 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006311 mConfig.inputCfg.samplingRate = thread->sampleRate();
6312 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6313 mConfig.inputCfg.bufferProvider.cookie = NULL;
6314 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6315 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6316 mConfig.outputCfg.bufferProvider.cookie = NULL;
6317 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6318 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6319 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6320 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006321 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006322 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006323 // - in other sessions:
6324 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6325 // other effect: overwrites output buffer: input buffer == output buffer
6326 // Auxiliary effect:
6327 // accumulates in output buffer: input buffer != output buffer
6328 // Therefore: accumulate <=> input buffer != output buffer
6329 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6330 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6331 } else {
6332 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6333 }
6334 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6335 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6336 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6337 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6338
Steve Block71f2cf12011-10-20 11:56:00 +01006339 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006340 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6341
Eric Laurent65b65452010-06-01 23:49:17 -07006342 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006343 uint32_t size = sizeof(int);
6344 status_t status = (*mEffectInterface)->command(mEffectInterface,
6345 EFFECT_CMD_CONFIGURE,
6346 sizeof(effect_config_t),
6347 &mConfig,
6348 &size,
6349 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006350 if (status == 0) {
6351 status = cmdStatus;
6352 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006353
6354 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6355 (1000 * mConfig.outputCfg.buffer.frameCount);
6356
Eric Laurent65b65452010-06-01 23:49:17 -07006357 return status;
6358}
6359
6360status_t AudioFlinger::EffectModule::init()
6361{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006362 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006363 if (mEffectInterface == NULL) {
6364 return NO_INIT;
6365 }
6366 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006367 uint32_t size = sizeof(status_t);
6368 status_t status = (*mEffectInterface)->command(mEffectInterface,
6369 EFFECT_CMD_INIT,
6370 0,
6371 NULL,
6372 &size,
6373 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006374 if (status == 0) {
6375 status = cmdStatus;
6376 }
6377 return status;
6378}
6379
Eric Laurent6fccbd02011-10-05 17:42:25 -07006380status_t AudioFlinger::EffectModule::start()
6381{
6382 Mutex::Autolock _l(mLock);
6383 return start_l();
6384}
6385
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006386status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006387{
6388 if (mEffectInterface == NULL) {
6389 return NO_INIT;
6390 }
6391 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006392 uint32_t size = sizeof(status_t);
6393 status_t status = (*mEffectInterface)->command(mEffectInterface,
6394 EFFECT_CMD_ENABLE,
6395 0,
6396 NULL,
6397 &size,
6398 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006399 if (status == 0) {
6400 status = cmdStatus;
6401 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006402 if (status == 0 &&
6403 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6404 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6405 sp<ThreadBase> thread = mThread.promote();
6406 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006407 audio_stream_t *stream = thread->stream();
6408 if (stream != NULL) {
6409 stream->add_audio_effect(stream, mEffectInterface);
6410 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006411 }
6412 }
Eric Laurent65b65452010-06-01 23:49:17 -07006413 return status;
6414}
6415
Eric Laurent21b5c472011-07-26 20:54:46 -07006416status_t AudioFlinger::EffectModule::stop()
6417{
6418 Mutex::Autolock _l(mLock);
6419 return stop_l();
6420}
6421
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006422status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006423{
6424 if (mEffectInterface == NULL) {
6425 return NO_INIT;
6426 }
6427 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006428 uint32_t size = sizeof(status_t);
6429 status_t status = (*mEffectInterface)->command(mEffectInterface,
6430 EFFECT_CMD_DISABLE,
6431 0,
6432 NULL,
6433 &size,
6434 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006435 if (status == 0) {
6436 status = cmdStatus;
6437 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006438 if (status == 0 &&
6439 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6440 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6441 sp<ThreadBase> thread = mThread.promote();
6442 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006443 audio_stream_t *stream = thread->stream();
6444 if (stream != NULL) {
6445 stream->remove_audio_effect(stream, mEffectInterface);
6446 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006447 }
6448 }
Eric Laurent65b65452010-06-01 23:49:17 -07006449 return status;
6450}
6451
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006452status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6453 uint32_t cmdSize,
6454 void *pCmdData,
6455 uint32_t *replySize,
6456 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006457{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006458 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006459// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006460
Eric Laurent21b5c472011-07-26 20:54:46 -07006461 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006462 return NO_INIT;
6463 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006464 status_t status = (*mEffectInterface)->command(mEffectInterface,
6465 cmdCode,
6466 cmdSize,
6467 pCmdData,
6468 replySize,
6469 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006470 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006471 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006472 for (size_t i = 1; i < mHandles.size(); i++) {
6473 sp<EffectHandle> h = mHandles[i].promote();
6474 if (h != 0) {
6475 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6476 }
6477 }
6478 }
6479 return status;
6480}
6481
6482status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6483{
Eric Laurent6752ec82011-08-10 10:37:50 -07006484
Eric Laurent65b65452010-06-01 23:49:17 -07006485 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006486 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006487
6488 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006489 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6490 if (enabled && status != NO_ERROR) {
6491 return status;
6492 }
6493
Eric Laurent65b65452010-06-01 23:49:17 -07006494 switch (mState) {
6495 // going from disabled to enabled
6496 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006497 mState = STARTING;
6498 break;
6499 case STOPPED:
6500 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006501 break;
6502 case STOPPING:
6503 mState = ACTIVE;
6504 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006505
6506 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006507 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006508 mState = STOPPED;
6509 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006510 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006511 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006512 break;
6513 case ACTIVE:
6514 mState = STOPPING;
6515 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006516 case DESTROYED:
6517 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006518 }
6519 for (size_t i = 1; i < mHandles.size(); i++) {
6520 sp<EffectHandle> h = mHandles[i].promote();
6521 if (h != 0) {
6522 h->setEnabled(enabled);
6523 }
6524 }
6525 }
6526 return NO_ERROR;
6527}
6528
6529bool AudioFlinger::EffectModule::isEnabled()
6530{
6531 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006532 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006533 case STARTING:
6534 case ACTIVE:
6535 return true;
6536 case IDLE:
6537 case STOPPING:
6538 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006539 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006540 default:
6541 return false;
6542 }
6543}
6544
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006545bool AudioFlinger::EffectModule::isProcessEnabled()
6546{
6547 switch (mState) {
6548 case RESTART:
6549 case ACTIVE:
6550 case STOPPING:
6551 case STOPPED:
6552 return true;
6553 case IDLE:
6554 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006555 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006556 default:
6557 return false;
6558 }
6559}
6560
Eric Laurent65b65452010-06-01 23:49:17 -07006561status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6562{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006563 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006564 status_t status = NO_ERROR;
6565
6566 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6567 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006568 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006569 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6570 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006571 status_t cmdStatus;
6572 uint32_t volume[2];
6573 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006574 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006575 volume[0] = *left;
6576 volume[1] = *right;
6577 if (controller) {
6578 pVolume = volume;
6579 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006580 status = (*mEffectInterface)->command(mEffectInterface,
6581 EFFECT_CMD_SET_VOLUME,
6582 size,
6583 volume,
6584 &size,
6585 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006586 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6587 *left = volume[0];
6588 *right = volume[1];
6589 }
6590 }
6591 return status;
6592}
6593
6594status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6595{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006596 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006597 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006598 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6599 // audio pre processing modules on RecordThread can receive both output and
6600 // input device indication in the same call
6601 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6602 if (dev) {
6603 status_t cmdStatus;
6604 uint32_t size = sizeof(status_t);
6605
6606 status = (*mEffectInterface)->command(mEffectInterface,
6607 EFFECT_CMD_SET_DEVICE,
6608 sizeof(uint32_t),
6609 &dev,
6610 &size,
6611 &cmdStatus);
6612 if (status == NO_ERROR) {
6613 status = cmdStatus;
6614 }
6615 }
6616 dev = device & AUDIO_DEVICE_IN_ALL;
6617 if (dev) {
6618 status_t cmdStatus;
6619 uint32_t size = sizeof(status_t);
6620
6621 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6622 EFFECT_CMD_SET_INPUT_DEVICE,
6623 sizeof(uint32_t),
6624 &dev,
6625 &size,
6626 &cmdStatus);
6627 if (status2 == NO_ERROR) {
6628 status2 = cmdStatus;
6629 }
6630 if (status == NO_ERROR) {
6631 status = status2;
6632 }
Eric Laurent65b65452010-06-01 23:49:17 -07006633 }
6634 }
6635 return status;
6636}
6637
Eric Laurent53334cd2010-06-23 17:38:20 -07006638status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6639{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006640 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006641 status_t status = NO_ERROR;
6642 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006643 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006644 uint32_t size = sizeof(status_t);
6645 status = (*mEffectInterface)->command(mEffectInterface,
6646 EFFECT_CMD_SET_AUDIO_MODE,
6647 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006648 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006649 &size,
6650 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006651 if (status == NO_ERROR) {
6652 status = cmdStatus;
6653 }
6654 }
6655 return status;
6656}
6657
Eric Laurentf82fccd2011-07-27 19:49:51 -07006658void AudioFlinger::EffectModule::setSuspended(bool suspended)
6659{
6660 Mutex::Autolock _l(mLock);
6661 mSuspended = suspended;
6662}
6663bool AudioFlinger::EffectModule::suspended()
6664{
6665 Mutex::Autolock _l(mLock);
6666 return mSuspended;
6667}
6668
Eric Laurent65b65452010-06-01 23:49:17 -07006669status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6670{
6671 const size_t SIZE = 256;
6672 char buffer[SIZE];
6673 String8 result;
6674
6675 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6676 result.append(buffer);
6677
6678 bool locked = tryLock(mLock);
6679 // failed to lock - AudioFlinger is probably deadlocked
6680 if (!locked) {
6681 result.append("\t\tCould not lock Fx mutex:\n");
6682 }
6683
6684 result.append("\t\tSession Status State Engine:\n");
6685 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6686 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6687 result.append(buffer);
6688
6689 result.append("\t\tDescriptor:\n");
6690 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6691 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6692 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6693 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6694 result.append(buffer);
6695 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6696 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6697 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6698 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6699 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006700 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006701 mDescriptor.apiVersion,
6702 mDescriptor.flags);
6703 result.append(buffer);
6704 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6705 mDescriptor.name);
6706 result.append(buffer);
6707 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6708 mDescriptor.implementor);
6709 result.append(buffer);
6710
6711 result.append("\t\t- Input configuration:\n");
6712 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6713 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6714 (uint32_t)mConfig.inputCfg.buffer.raw,
6715 mConfig.inputCfg.buffer.frameCount,
6716 mConfig.inputCfg.samplingRate,
6717 mConfig.inputCfg.channels,
6718 mConfig.inputCfg.format);
6719 result.append(buffer);
6720
6721 result.append("\t\t- Output configuration:\n");
6722 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6723 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6724 (uint32_t)mConfig.outputCfg.buffer.raw,
6725 mConfig.outputCfg.buffer.frameCount,
6726 mConfig.outputCfg.samplingRate,
6727 mConfig.outputCfg.channels,
6728 mConfig.outputCfg.format);
6729 result.append(buffer);
6730
6731 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6732 result.append(buffer);
6733 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6734 for (size_t i = 0; i < mHandles.size(); ++i) {
6735 sp<EffectHandle> handle = mHandles[i].promote();
6736 if (handle != 0) {
6737 handle->dump(buffer, SIZE);
6738 result.append(buffer);
6739 }
6740 }
6741
6742 result.append("\n");
6743
6744 write(fd, result.string(), result.length());
6745
6746 if (locked) {
6747 mLock.unlock();
6748 }
6749
6750 return NO_ERROR;
6751}
6752
6753// ----------------------------------------------------------------------------
6754// EffectHandle implementation
6755// ----------------------------------------------------------------------------
6756
6757#undef LOG_TAG
6758#define LOG_TAG "AudioFlinger::EffectHandle"
6759
6760AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6761 const sp<AudioFlinger::Client>& client,
6762 const sp<IEffectClient>& effectClient,
6763 int32_t priority)
6764 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006765 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006766 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006767{
Steve Block71f2cf12011-10-20 11:56:00 +01006768 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006769
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006770 if (client == 0) {
6771 return;
6772 }
Eric Laurent65b65452010-06-01 23:49:17 -07006773 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6774 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6775 if (mCblkMemory != 0) {
6776 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6777
6778 if (mCblk) {
6779 new(mCblk) effect_param_cblk_t();
6780 mBuffer = (uint8_t *)mCblk + bufOffset;
6781 }
6782 } else {
6783 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6784 return;
6785 }
6786}
6787
6788AudioFlinger::EffectHandle::~EffectHandle()
6789{
Steve Block71f2cf12011-10-20 11:56:00 +01006790 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006791 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006792 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006793}
6794
6795status_t AudioFlinger::EffectHandle::enable()
6796{
Steve Block71f2cf12011-10-20 11:56:00 +01006797 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006798 if (!mHasControl) return INVALID_OPERATION;
6799 if (mEffect == 0) return DEAD_OBJECT;
6800
Eric Laurent6752ec82011-08-10 10:37:50 -07006801 if (mEnabled) {
6802 return NO_ERROR;
6803 }
6804
Eric Laurentf82fccd2011-07-27 19:49:51 -07006805 mEnabled = true;
6806
6807 sp<ThreadBase> thread = mEffect->thread().promote();
6808 if (thread != 0) {
6809 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6810 }
6811
6812 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6813 if (mEffect->suspended()) {
6814 return NO_ERROR;
6815 }
6816
Eric Laurent6752ec82011-08-10 10:37:50 -07006817 status_t status = mEffect->setEnabled(true);
6818 if (status != NO_ERROR) {
6819 if (thread != 0) {
6820 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6821 }
6822 mEnabled = false;
6823 }
6824 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006825}
6826
6827status_t AudioFlinger::EffectHandle::disable()
6828{
Steve Block71f2cf12011-10-20 11:56:00 +01006829 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006830 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006831 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006832
Eric Laurent6752ec82011-08-10 10:37:50 -07006833 if (!mEnabled) {
6834 return NO_ERROR;
6835 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006836 mEnabled = false;
6837
6838 if (mEffect->suspended()) {
6839 return NO_ERROR;
6840 }
6841
6842 status_t status = mEffect->setEnabled(false);
6843
6844 sp<ThreadBase> thread = mEffect->thread().promote();
6845 if (thread != 0) {
6846 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6847 }
6848
6849 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006850}
6851
6852void AudioFlinger::EffectHandle::disconnect()
6853{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006854 disconnect(true);
6855}
6856
6857void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6858{
Steve Block71f2cf12011-10-20 11:56:00 +01006859 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006860 if (mEffect == 0) {
6861 return;
6862 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006863 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006864
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006865 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006866 sp<ThreadBase> thread = mEffect->thread().promote();
6867 if (thread != 0) {
6868 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6869 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006870 }
6871
Eric Laurent65b65452010-06-01 23:49:17 -07006872 // release sp on module => module destructor can be called now
6873 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006874 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006875 if (mCblk) {
6876 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6877 }
6878 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006879 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6880 mClient.clear();
6881 }
6882}
6883
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006884status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6885 uint32_t cmdSize,
6886 void *pCmdData,
6887 uint32_t *replySize,
6888 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006889{
Steve Block71f2cf12011-10-20 11:56:00 +01006890// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006891// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006892
6893 // only get parameter command is permitted for applications not controlling the effect
6894 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6895 return INVALID_OPERATION;
6896 }
6897 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006898 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006899
6900 // handle commands that are not forwarded transparently to effect engine
6901 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6902 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6903 // no risk to block the whole media server process or mixer threads is we are stuck here
6904 Mutex::Autolock _l(mCblk->lock);
6905 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6906 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6907 mCblk->serverIndex = 0;
6908 mCblk->clientIndex = 0;
6909 return BAD_VALUE;
6910 }
6911 status_t status = NO_ERROR;
6912 while (mCblk->serverIndex < mCblk->clientIndex) {
6913 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006914 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006915 int *p = (int *)(mBuffer + mCblk->serverIndex);
6916 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006917 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6918 LOGW("command(): invalid parameter block size");
6919 break;
6920 }
Eric Laurent65b65452010-06-01 23:49:17 -07006921 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006922 if (param->psize == 0 || param->vsize == 0) {
6923 LOGW("command(): null parameter or value size");
6924 mCblk->serverIndex += size;
6925 continue;
6926 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006927 uint32_t psize = sizeof(effect_param_t) +
6928 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6929 param->vsize;
6930 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6931 psize,
6932 p,
6933 &rsize,
6934 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006935 // stop at first error encountered
6936 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006937 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006938 *(int *)pReplyData = reply;
6939 break;
6940 } else if (reply != NO_ERROR) {
6941 *(int *)pReplyData = reply;
6942 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006943 }
6944 mCblk->serverIndex += size;
6945 }
6946 mCblk->serverIndex = 0;
6947 mCblk->clientIndex = 0;
6948 return status;
6949 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006950 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006951 return enable();
6952 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006953 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006954 return disable();
6955 }
6956
6957 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6958}
6959
6960sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6961 return mCblkMemory;
6962}
6963
Eric Laurentf82fccd2011-07-27 19:49:51 -07006964void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07006965{
Steve Block71f2cf12011-10-20 11:56:00 +01006966 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07006967
6968 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006969 mEnabled = enabled;
6970
Eric Laurent65b65452010-06-01 23:49:17 -07006971 if (signal && mEffectClient != 0) {
6972 mEffectClient->controlStatusChanged(hasControl);
6973 }
6974}
6975
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006976void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6977 uint32_t cmdSize,
6978 void *pCmdData,
6979 uint32_t replySize,
6980 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006981{
6982 if (mEffectClient != 0) {
6983 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6984 }
6985}
6986
6987
6988
6989void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6990{
6991 if (mEffectClient != 0) {
6992 mEffectClient->enableStatusChanged(enabled);
6993 }
6994}
6995
6996status_t AudioFlinger::EffectHandle::onTransact(
6997 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6998{
6999 return BnEffect::onTransact(code, data, reply, flags);
7000}
7001
7002
7003void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7004{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007005 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007006
7007 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7008 (mClient == NULL) ? getpid() : mClient->pid(),
7009 mPriority,
7010 mHasControl,
7011 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007012 mCblk ? mCblk->clientIndex : 0,
7013 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007014 );
7015
7016 if (locked) {
7017 mCblk->lock.unlock();
7018 }
7019}
7020
7021#undef LOG_TAG
7022#define LOG_TAG "AudioFlinger::EffectChain"
7023
7024AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7025 int sessionId)
Eric Laurent90681d62011-05-09 12:09:06 -07007026 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
7027 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7028 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007029{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007030 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07007031}
7032
7033AudioFlinger::EffectChain::~EffectChain()
7034{
7035 if (mOwnInBuffer) {
7036 delete mInBuffer;
7037 }
7038
7039}
7040
Eric Laurentf82fccd2011-07-27 19:49:51 -07007041// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007042sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007043{
7044 sp<EffectModule> effect;
7045 size_t size = mEffects.size();
7046
7047 for (size_t i = 0; i < size; i++) {
7048 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7049 effect = mEffects[i];
7050 break;
7051 }
7052 }
7053 return effect;
7054}
7055
Eric Laurentf82fccd2011-07-27 19:49:51 -07007056// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007057sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007058{
7059 sp<EffectModule> effect;
7060 size_t size = mEffects.size();
7061
7062 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007063 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7064 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007065 effect = mEffects[i];
7066 break;
7067 }
7068 }
7069 return effect;
7070}
7071
Eric Laurentf82fccd2011-07-27 19:49:51 -07007072// getEffectFromType_l() must be called with ThreadBase::mLock held
7073sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7074 const effect_uuid_t *type)
7075{
7076 sp<EffectModule> effect;
7077 size_t size = mEffects.size();
7078
7079 for (size_t i = 0; i < size; i++) {
7080 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7081 effect = mEffects[i];
7082 break;
7083 }
7084 }
7085 return effect;
7086}
7087
Eric Laurent65b65452010-06-01 23:49:17 -07007088// Must be called with EffectChain::mLock locked
7089void AudioFlinger::EffectChain::process_l()
7090{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007091 sp<ThreadBase> thread = mThread.promote();
7092 if (thread == 0) {
7093 LOGW("process_l(): cannot promote mixer thread");
7094 return;
7095 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007096 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7097 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007098 bool tracksOnSession = false;
7099 if (!isGlobalSession) {
Eric Laurent90681d62011-05-09 12:09:06 -07007100 tracksOnSession = (trackCnt() != 0);
7101 }
7102
7103 // if no track is active, input buffer must be cleared here as the mixer process
7104 // will not do it
7105 if (tracksOnSession &&
7106 activeTrackCnt() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07007107 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurent90681d62011-05-09 12:09:06 -07007108 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007109 }
7110
Eric Laurent65b65452010-06-01 23:49:17 -07007111 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007112 // do not process effect if no track is present in same audio session
7113 if (isGlobalSession || tracksOnSession) {
7114 for (size_t i = 0; i < size; i++) {
7115 mEffects[i]->process();
7116 }
Eric Laurent65b65452010-06-01 23:49:17 -07007117 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007118 for (size_t i = 0; i < size; i++) {
7119 mEffects[i]->updateState();
7120 }
Eric Laurent65b65452010-06-01 23:49:17 -07007121}
7122
Eric Laurent76c40f72010-07-15 12:50:15 -07007123// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007124status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007125{
7126 effect_descriptor_t desc = effect->desc();
7127 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7128
7129 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007130 effect->setChain(this);
7131 sp<ThreadBase> thread = mThread.promote();
7132 if (thread == 0) {
7133 return NO_INIT;
7134 }
7135 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007136
7137 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7138 // Auxiliary effects are inserted at the beginning of mEffects vector as
7139 // they are processed first and accumulated in chain input buffer
7140 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007141
Eric Laurent65b65452010-06-01 23:49:17 -07007142 // the input buffer for auxiliary effect contains mono samples in
7143 // 32 bit format. This is to avoid saturation in AudoMixer
7144 // accumulation stage. Saturation is done in EffectModule::process() before
7145 // calling the process in effect engine
7146 size_t numSamples = thread->frameCount();
7147 int32_t *buffer = new int32_t[numSamples];
7148 memset(buffer, 0, numSamples * sizeof(int32_t));
7149 effect->setInBuffer((int16_t *)buffer);
7150 // auxiliary effects output samples to chain input buffer for further processing
7151 // by insert effects
7152 effect->setOutBuffer(mInBuffer);
7153 } else {
7154 // Insert effects are inserted at the end of mEffects vector as they are processed
7155 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007156 // Insert effect order as a function of indicated preference:
7157 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7158 // another effect is present
7159 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7160 // last effect claiming first position
7161 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7162 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007163 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007164 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7165 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007166
7167 int size = (int)mEffects.size();
7168 int idx_insert = size;
7169 int idx_insert_first = -1;
7170 int idx_insert_last = -1;
7171
7172 for (int i = 0; i < size; i++) {
7173 effect_descriptor_t d = mEffects[i]->desc();
7174 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7175 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7176 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7177 // check invalid effect chaining combinations
7178 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007179 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007180 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007181 return INVALID_OPERATION;
7182 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007183 // remember position of first insert effect and by default
7184 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007185 if (idx_insert == size) {
7186 idx_insert = i;
7187 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007188 // remember position of last insert effect claiming
7189 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007190 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7191 idx_insert_first = i;
7192 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007193 // remember position of first insert effect claiming
7194 // last position
7195 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7196 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007197 idx_insert_last = i;
7198 }
7199 }
7200 }
7201
Eric Laurent53334cd2010-06-23 17:38:20 -07007202 // modify idx_insert from first position if needed
7203 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7204 if (idx_insert_last != -1) {
7205 idx_insert = idx_insert_last;
7206 } else {
7207 idx_insert = size;
7208 }
7209 } else {
7210 if (idx_insert_first != -1) {
7211 idx_insert = idx_insert_first + 1;
7212 }
Eric Laurent65b65452010-06-01 23:49:17 -07007213 }
7214
7215 // always read samples from chain input buffer
7216 effect->setInBuffer(mInBuffer);
7217
7218 // if last effect in the chain, output samples to chain
7219 // output buffer, otherwise to chain input buffer
7220 if (idx_insert == size) {
7221 if (idx_insert != 0) {
7222 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7223 mEffects[idx_insert-1]->configure();
7224 }
7225 effect->setOutBuffer(mOutBuffer);
7226 } else {
7227 effect->setOutBuffer(mInBuffer);
7228 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007229 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007230
Steve Block71f2cf12011-10-20 11:56:00 +01007231 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007232 }
7233 effect->configure();
7234 return NO_ERROR;
7235}
7236
Eric Laurent76c40f72010-07-15 12:50:15 -07007237// removeEffect_l() must be called with PlaybackThread::mLock held
7238size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007239{
7240 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007241 int size = (int)mEffects.size();
7242 int i;
7243 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7244
7245 for (i = 0; i < size; i++) {
7246 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007247 // calling stop here will remove pre-processing effect from the audio HAL.
7248 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7249 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007250 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7251 mEffects[i]->state() == EffectModule::STOPPING) {
7252 mEffects[i]->stop();
7253 }
Eric Laurent65b65452010-06-01 23:49:17 -07007254 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7255 delete[] effect->inBuffer();
7256 } else {
7257 if (i == size - 1 && i != 0) {
7258 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7259 mEffects[i - 1]->configure();
7260 }
7261 }
7262 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007263 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007264 break;
7265 }
7266 }
Eric Laurent65b65452010-06-01 23:49:17 -07007267
7268 return mEffects.size();
7269}
7270
Eric Laurent76c40f72010-07-15 12:50:15 -07007271// setDevice_l() must be called with PlaybackThread::mLock held
7272void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007273{
7274 size_t size = mEffects.size();
7275 for (size_t i = 0; i < size; i++) {
7276 mEffects[i]->setDevice(device);
7277 }
7278}
7279
Eric Laurent76c40f72010-07-15 12:50:15 -07007280// setMode_l() must be called with PlaybackThread::mLock held
7281void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007282{
7283 size_t size = mEffects.size();
7284 for (size_t i = 0; i < size; i++) {
7285 mEffects[i]->setMode(mode);
7286 }
7287}
7288
Eric Laurent76c40f72010-07-15 12:50:15 -07007289// setVolume_l() must be called with PlaybackThread::mLock held
7290bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007291{
7292 uint32_t newLeft = *left;
7293 uint32_t newRight = *right;
7294 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007295 int ctrlIdx = -1;
7296 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007297
Eric Laurent76c40f72010-07-15 12:50:15 -07007298 // first update volume controller
7299 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007300 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007301 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7302 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007303 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007304 break;
7305 }
7306 }
7307
7308 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007309 if (hasControl) {
7310 *left = mNewLeftVolume;
7311 *right = mNewRightVolume;
7312 }
7313 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007314 }
7315
7316 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007317 mLeftVolume = newLeft;
7318 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007319
7320 // second get volume update from volume controller
7321 if (ctrlIdx >= 0) {
7322 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007323 mNewLeftVolume = newLeft;
7324 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007325 }
7326 // then indicate volume to all other effects in chain.
7327 // Pass altered volume to effects before volume controller
7328 // and requested volume to effects after controller
7329 uint32_t lVol = newLeft;
7330 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007331
Eric Laurent65b65452010-06-01 23:49:17 -07007332 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007333 if ((int)i == ctrlIdx) continue;
7334 // this also works for ctrlIdx == -1 when there is no volume controller
7335 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007336 lVol = *left;
7337 rVol = *right;
7338 }
7339 mEffects[i]->setVolume(&lVol, &rVol, false);
7340 }
7341 *left = newLeft;
7342 *right = newRight;
7343
7344 return hasControl;
7345}
7346
Eric Laurent65b65452010-06-01 23:49:17 -07007347status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7348{
7349 const size_t SIZE = 256;
7350 char buffer[SIZE];
7351 String8 result;
7352
7353 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7354 result.append(buffer);
7355
7356 bool locked = tryLock(mLock);
7357 // failed to lock - AudioFlinger is probably deadlocked
7358 if (!locked) {
7359 result.append("\tCould not lock mutex:\n");
7360 }
7361
Eric Laurent76c40f72010-07-15 12:50:15 -07007362 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7363 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007364 mEffects.size(),
7365 (uint32_t)mInBuffer,
7366 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007367 mActiveTrackCnt);
7368 result.append(buffer);
7369 write(fd, result.string(), result.size());
7370
7371 for (size_t i = 0; i < mEffects.size(); ++i) {
7372 sp<EffectModule> effect = mEffects[i];
7373 if (effect != 0) {
7374 effect->dump(fd, args);
7375 }
7376 }
7377
7378 if (locked) {
7379 mLock.unlock();
7380 }
7381
7382 return NO_ERROR;
7383}
7384
Eric Laurentf82fccd2011-07-27 19:49:51 -07007385// must be called with ThreadBase::mLock held
7386void AudioFlinger::EffectChain::setEffectSuspended_l(
7387 const effect_uuid_t *type, bool suspend)
7388{
7389 sp<SuspendedEffectDesc> desc;
7390 // use effect type UUID timelow as key as there is no real risk of identical
7391 // timeLow fields among effect type UUIDs.
7392 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7393 if (suspend) {
7394 if (index >= 0) {
7395 desc = mSuspendedEffects.valueAt(index);
7396 } else {
7397 desc = new SuspendedEffectDesc();
7398 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7399 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007400 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007401 }
7402 if (desc->mRefCount++ == 0) {
7403 sp<EffectModule> effect = getEffectIfEnabled(type);
7404 if (effect != 0) {
7405 desc->mEffect = effect;
7406 effect->setSuspended(true);
7407 effect->setEnabled(false);
7408 }
7409 }
7410 } else {
7411 if (index < 0) {
7412 return;
7413 }
7414 desc = mSuspendedEffects.valueAt(index);
7415 if (desc->mRefCount <= 0) {
7416 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7417 desc->mRefCount = 1;
7418 }
7419 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007420 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007421 if (desc->mEffect != 0) {
7422 sp<EffectModule> effect = desc->mEffect.promote();
7423 if (effect != 0) {
7424 effect->setSuspended(false);
7425 sp<EffectHandle> handle = effect->controlHandle();
7426 if (handle != 0) {
7427 effect->setEnabled(handle->enabled());
7428 }
7429 }
7430 desc->mEffect.clear();
7431 }
7432 mSuspendedEffects.removeItemsAt(index);
7433 }
7434 }
7435}
7436
7437// must be called with ThreadBase::mLock held
7438void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7439{
7440 sp<SuspendedEffectDesc> desc;
7441
7442 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7443 if (suspend) {
7444 if (index >= 0) {
7445 desc = mSuspendedEffects.valueAt(index);
7446 } else {
7447 desc = new SuspendedEffectDesc();
7448 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007449 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007450 }
7451 if (desc->mRefCount++ == 0) {
7452 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7453 for (size_t i = 0; i < effects.size(); i++) {
7454 setEffectSuspended_l(&effects[i]->desc().type, true);
7455 }
7456 }
7457 } else {
7458 if (index < 0) {
7459 return;
7460 }
7461 desc = mSuspendedEffects.valueAt(index);
7462 if (desc->mRefCount <= 0) {
7463 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7464 desc->mRefCount = 1;
7465 }
7466 if (--desc->mRefCount == 0) {
7467 Vector<const effect_uuid_t *> types;
7468 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7469 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7470 continue;
7471 }
7472 types.add(&mSuspendedEffects.valueAt(i)->mType);
7473 }
7474 for (size_t i = 0; i < types.size(); i++) {
7475 setEffectSuspended_l(types[i], false);
7476 }
Steve Block71f2cf12011-10-20 11:56:00 +01007477 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007478 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7479 }
7480 }
7481}
7482
Eric Laurent5e7acae2011-09-23 08:40:41 -07007483
7484// The volume effect is used for automated tests only
7485#ifndef OPENSL_ES_H_
7486static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7487 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7488const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7489#endif //OPENSL_ES_H_
7490
Eric Laurent6752ec82011-08-10 10:37:50 -07007491bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7492{
7493 // auxiliary effects and visualizer are never suspended on output mix
7494 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7495 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007496 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7497 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007498 return false;
7499 }
7500 return true;
7501}
7502
Eric Laurentf82fccd2011-07-27 19:49:51 -07007503Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7504{
7505 Vector< sp<EffectModule> > effects;
7506 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007507 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007508 continue;
7509 }
7510 effects.add(mEffects[i]);
7511 }
7512 return effects;
7513}
7514
7515sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7516 const effect_uuid_t *type)
7517{
7518 sp<EffectModule> effect;
7519 effect = getEffectFromType_l(type);
7520 if (effect != 0 && !effect->isEnabled()) {
7521 effect.clear();
7522 }
7523 return effect;
7524}
7525
7526void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7527 bool enabled)
7528{
7529 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7530 if (enabled) {
7531 if (index < 0) {
7532 // if the effect is not suspend check if all effects are suspended
7533 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7534 if (index < 0) {
7535 return;
7536 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007537 if (!isEffectEligibleForSuspend(effect->desc())) {
7538 return;
7539 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007540 setEffectSuspended_l(&effect->desc().type, enabled);
7541 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007542 if (index < 0) {
7543 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7544 return;
7545 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007546 }
Steve Block71f2cf12011-10-20 11:56:00 +01007547 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007548 effect->desc().type.timeLow);
7549 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7550 // if effect is requested to suspended but was not yet enabled, supend it now.
7551 if (desc->mEffect == 0) {
7552 desc->mEffect = effect;
7553 effect->setEnabled(false);
7554 effect->setSuspended(true);
7555 }
7556 } else {
7557 if (index < 0) {
7558 return;
7559 }
Steve Block71f2cf12011-10-20 11:56:00 +01007560 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007561 effect->desc().type.timeLow);
7562 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7563 desc->mEffect.clear();
7564 effect->setSuspended(false);
7565 }
7566}
7567
Eric Laurent65b65452010-06-01 23:49:17 -07007568#undef LOG_TAG
7569#define LOG_TAG "AudioFlinger"
7570
Eric Laurenta553c252009-07-17 12:17:14 -07007571// ----------------------------------------------------------------------------
7572
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007573status_t AudioFlinger::onTransact(
7574 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7575{
7576 return BnAudioFlinger::onTransact(code, data, reply, flags);
7577}
7578
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007579}; // namespace android