blob: 05d6d72280439c40287d2e7cf3e4c377687125b4 [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
Eric Laurentf1f5fc82011-11-22 18:50:29 -080092// minimum sleep time for the mixer thread loop when tracks are active but in underrun
93static const uint32_t kMinThreadSleepTimeUs = 5000;
94// maximum divider applied to the active sleep time in the mixer thread loop
95static const uint32_t kMaxThreadSleepTimeShift = 2;
96
97
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070098// ----------------------------------------------------------------------------
99
100static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700101 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
102 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
103 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
104 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700105}
106
107static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700108 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
109 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
110 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
111 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700112}
113
Gloria Wang9b3f1522011-02-24 14:51:45 -0800114// To collect the amplifier usage
115static void addBatteryData(uint32_t params) {
116 sp<IBinder> binder =
117 defaultServiceManager()->getService(String16("media.player"));
118 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
119 if (service.get() == NULL) {
120 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
121 return;
122 }
123
124 service->addBatteryData(params);
125}
126
Dima Zavin31f188892011-04-18 16:57:27 -0700127static int load_audio_interface(const char *if_name, const hw_module_t **mod,
128 audio_hw_device_t **dev)
129{
130 int rc;
131
132 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
133 if (rc)
134 goto out;
135
136 rc = audio_hw_device_open(*mod, dev);
137 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
138 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
139 if (rc)
140 goto out;
141
142 return 0;
143
144out:
145 *mod = NULL;
146 *dev = NULL;
147 return rc;
148}
149
150static const char *audio_interfaces[] = {
151 "primary",
152 "a2dp",
153 "usb",
154};
155#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
156
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700157// ----------------------------------------------------------------------------
158
159AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 : BnAudioFlinger(),
Eric Laurent6639b552011-08-01 09:52:20 -0700161 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700162 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700163{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700164}
165
166void AudioFlinger::onFirstRef()
167{
Dima Zavin31f188892011-04-18 16:57:27 -0700168 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700169
Eric Laurent01635942011-01-18 18:39:02 -0800170 Mutex::Autolock _l(mLock);
171
Dima Zavin31f188892011-04-18 16:57:27 -0700172 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700173 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700174
Dima Zavin31f188892011-04-18 16:57:27 -0700175 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
176 const hw_module_t *mod;
177 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700178
Dima Zavin31f188892011-04-18 16:57:27 -0700179 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
180 if (rc)
181 continue;
182
183 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
184 mod->name, mod->id);
185 mAudioHwDevs.push(dev);
186
187 if (!mPrimaryHardwareDev) {
188 mPrimaryHardwareDev = dev;
189 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700190 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700191 }
192 }
Eric Laurenta553c252009-07-17 12:17:14 -0700193
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700194 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700195
Dima Zavin31f188892011-04-18 16:57:27 -0700196 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
197 LOGE("Primary audio interface not found");
198 return;
199 }
200
201 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
202 audio_hw_device_t *dev = mAudioHwDevs[i];
203
204 mHardwareStatus = AUDIO_HW_INIT;
205 rc = dev->init_check(dev);
206 if (rc == 0) {
207 AutoMutex lock(mHardwareLock);
208
209 mMode = AUDIO_MODE_NORMAL;
210 mHardwareStatus = AUDIO_HW_SET_MODE;
211 dev->set_mode(dev, mMode);
212 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
213 dev->set_master_volume(dev, 1.0f);
214 mHardwareStatus = AUDIO_HW_IDLE;
215 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700216 }
217}
218
Dima Zavin2986f5b2011-04-19 19:04:32 -0700219status_t AudioFlinger::initCheck() const
220{
221 Mutex::Autolock _l(mLock);
222 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
223 return NO_INIT;
224 return NO_ERROR;
225}
226
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700227AudioFlinger::~AudioFlinger()
228{
Dima Zavin31f188892011-04-18 16:57:27 -0700229 int num_devs = mAudioHwDevs.size();
230
Eric Laurent7954c462009-08-28 10:39:03 -0700231 while (!mRecordThreads.isEmpty()) {
232 // closeInput() will remove first entry from mRecordThreads
233 closeInput(mRecordThreads.keyAt(0));
234 }
235 while (!mPlaybackThreads.isEmpty()) {
236 // closeOutput() will remove first entry from mPlaybackThreads
237 closeOutput(mPlaybackThreads.keyAt(0));
238 }
Dima Zavin31f188892011-04-18 16:57:27 -0700239
240 for (int i = 0; i < num_devs; i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700243 }
Dima Zavin31f188892011-04-18 16:57:27 -0700244 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800245}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800246
Dima Zavin31f188892011-04-18 16:57:27 -0700247audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
248{
249 /* first matching HW device is returned */
250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
251 audio_hw_device_t *dev = mAudioHwDevs[i];
252 if ((dev->get_supported_devices(dev) & devices) == devices)
253 return dev;
254 }
255 return NULL;
256}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700257
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
259{
260 const size_t SIZE = 256;
261 char buffer[SIZE];
262 String8 result;
263
264 result.append("Clients:\n");
265 for (size_t i = 0; i < mClients.size(); ++i) {
266 wp<Client> wClient = mClients.valueAt(i);
267 if (wClient != 0) {
268 sp<Client> client = wClient.promote();
269 if (client != 0) {
270 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
271 result.append(buffer);
272 }
273 }
274 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700275
276 result.append("Global session refs:\n");
277 result.append(" session pid cnt\n");
278 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
279 AudioSessionRef *r = mAudioSessionRefs[i];
280 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
281 result.append(buffer);
282 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700283 write(fd, result.string(), result.size());
284 return NO_ERROR;
285}
286
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700287
288status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700293 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700294
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700295 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296 result.append(buffer);
297 write(fd, result.string(), result.size());
298 return NO_ERROR;
299}
300
301status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306 snprintf(buffer, SIZE, "Permission Denial: "
307 "can't dump AudioFlinger from pid=%d, uid=%d\n",
308 IPCThreadState::self()->getCallingPid(),
309 IPCThreadState::self()->getCallingUid());
310 result.append(buffer);
311 write(fd, result.string(), result.size());
312 return NO_ERROR;
313}
314
The Android Open Source Project10592532009-03-18 17:39:46 -0700315static bool tryLock(Mutex& mutex)
316{
317 bool locked = false;
318 for (int i = 0; i < kDumpLockRetries; ++i) {
319 if (mutex.tryLock() == NO_ERROR) {
320 locked = true;
321 break;
322 }
323 usleep(kDumpLockSleep);
324 }
325 return locked;
326}
327
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700328status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
329{
330 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
331 dumpPermissionDenial(fd, args);
332 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700333 // get state of hardware lock
334 bool hardwareLocked = tryLock(mHardwareLock);
335 if (!hardwareLocked) {
336 String8 result(kHardwareLockedString);
337 write(fd, result.string(), result.size());
338 } else {
339 mHardwareLock.unlock();
340 }
341
342 bool locked = tryLock(mLock);
343
344 // failed to lock - AudioFlinger is probably deadlocked
345 if (!locked) {
346 String8 result(kDeadlockedString);
347 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700348 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700349
350 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700351 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352
Eric Laurenta553c252009-07-17 12:17:14 -0700353 // dump playback threads
354 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700355 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700356 }
357
358 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700359 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700360 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362
Dima Zavin31f188892011-04-18 16:57:27 -0700363 // dump all hardware devs
364 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
365 audio_hw_device_t *dev = mAudioHwDevs[i];
366 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700368 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700369 }
370 return NO_ERROR;
371}
372
Eric Laurenta553c252009-07-17 12:17:14 -0700373
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375
376
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700377sp<IAudioTrack> AudioFlinger::createTrack(
378 pid_t pid,
379 int streamType,
380 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700381 uint32_t format,
382 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800383 int frameCount,
384 uint32_t flags,
385 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700386 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700387 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800388 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389{
Eric Laurenta553c252009-07-17 12:17:14 -0700390 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700391 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800393 wp<Client> wclient;
394 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700395 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700396
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700397 if (streamType >= AUDIO_STREAM_CNT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800398 LOGE("invalid stream type");
399 lStatus = BAD_VALUE;
400 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401 }
402
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800403 {
404 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700405 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700406 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700407 if (thread == NULL) {
408 LOGE("unknown output thread");
409 lStatus = BAD_VALUE;
410 goto Exit;
411 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800412
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800413 wclient = mClients.valueFor(pid);
414
415 if (wclient != NULL) {
416 client = wclient.promote();
417 } else {
418 client = new Client(this, pid);
419 mClients.add(pid, client);
420 }
Eric Laurent65b65452010-06-01 23:49:17 -0700421
Eric Laurent65b65452010-06-01 23:49:17 -0700422 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700423 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700424 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700425 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
426 if (mPlaybackThreads.keyAt(i) != output) {
427 // prevent same audio session on different output threads
428 uint32_t sessions = t->hasAudioSession(*sessionId);
429 if (sessions & PlaybackThread::TRACK_SESSION) {
430 lStatus = BAD_VALUE;
431 goto Exit;
432 }
433 // check if an effect with same session ID is waiting for a track to be created
434 if (sessions & PlaybackThread::EFFECT_SESSION) {
435 effectThread = t.get();
436 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700437 }
438 }
Eric Laurent65b65452010-06-01 23:49:17 -0700439 lSessionId = *sessionId;
440 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700441 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700442 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700443 if (sessionId != NULL) {
444 *sessionId = lSessionId;
445 }
446 }
447 LOGV("createTrack() lSessionId: %d", lSessionId);
448
Eric Laurenta553c252009-07-17 12:17:14 -0700449 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700450 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700451
452 // move effect chain to this output thread if an effect on same session was waiting
453 // for a track to be created
454 if (lStatus == NO_ERROR && effectThread != NULL) {
455 Mutex::Autolock _dl(thread->mLock);
456 Mutex::Autolock _sl(effectThread->mLock);
457 moveEffectChain_l(lSessionId, effectThread, thread, true);
458 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700459 }
460 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800461 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700462 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700463 // remove local strong reference to Client before deleting the Track so that the Client
464 // destructor is called by the TrackBase destructor with mLock held
465 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700466 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800467 }
468
469Exit:
470 if(status) {
471 *status = lStatus;
472 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700473 return trackHandle;
474}
475
Eric Laurentddb78e72009-07-28 08:44:33 -0700476uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700477{
Eric Laurenta553c252009-07-17 12:17:14 -0700478 Mutex::Autolock _l(mLock);
479 PlaybackThread *thread = checkPlaybackThread_l(output);
480 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700481 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700482 return 0;
483 }
484 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700485}
486
Eric Laurentddb78e72009-07-28 08:44:33 -0700487int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700488{
Eric Laurenta553c252009-07-17 12:17:14 -0700489 Mutex::Autolock _l(mLock);
490 PlaybackThread *thread = checkPlaybackThread_l(output);
491 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700492 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700493 return 0;
494 }
495 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700496}
497
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700498uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700499{
Eric Laurenta553c252009-07-17 12:17:14 -0700500 Mutex::Autolock _l(mLock);
501 PlaybackThread *thread = checkPlaybackThread_l(output);
502 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700503 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700504 return 0;
505 }
506 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700507}
508
Eric Laurentddb78e72009-07-28 08:44:33 -0700509size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700510{
Eric Laurenta553c252009-07-17 12:17:14 -0700511 Mutex::Autolock _l(mLock);
512 PlaybackThread *thread = checkPlaybackThread_l(output);
513 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700514 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700515 return 0;
516 }
517 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700518}
519
Eric Laurentddb78e72009-07-28 08:44:33 -0700520uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800521{
Eric Laurenta553c252009-07-17 12:17:14 -0700522 Mutex::Autolock _l(mLock);
523 PlaybackThread *thread = checkPlaybackThread_l(output);
524 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700525 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700526 return 0;
527 }
528 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800529}
530
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700531status_t AudioFlinger::setMasterVolume(float value)
532{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700533 status_t ret = initCheck();
534 if (ret != NO_ERROR) {
535 return ret;
536 }
537
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700538 // check calling permissions
539 if (!settingsAllowed()) {
540 return PERMISSION_DENIED;
541 }
542
543 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800544 { // scope for the lock
545 AutoMutex lock(mHardwareLock);
546 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700547 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800548 value = 1.0f;
549 }
550 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700551 }
Eric Laurenta553c252009-07-17 12:17:14 -0700552
Eric Laurent01635942011-01-18 18:39:02 -0800553 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700554 mMasterVolume = value;
555 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700556 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700557
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700558 return NO_ERROR;
559}
560
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700561status_t AudioFlinger::setMode(int mode)
562{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700563 status_t ret = initCheck();
564 if (ret != NO_ERROR) {
565 return ret;
566 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700567
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700568 // check calling permissions
569 if (!settingsAllowed()) {
570 return PERMISSION_DENIED;
571 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700572 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700573 LOGW("Illegal value: setMode(%d)", mode);
574 return BAD_VALUE;
575 }
576
Eric Laurent53334cd2010-06-23 17:38:20 -0700577 { // scope for the lock
578 AutoMutex lock(mHardwareLock);
579 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700580 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700581 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800582 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700583
584 if (NO_ERROR == ret) {
585 Mutex::Autolock _l(mLock);
586 mMode = mode;
587 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
588 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700589 }
590
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700591 return ret;
592}
593
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700594status_t AudioFlinger::setMicMute(bool state)
595{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700596 status_t ret = initCheck();
597 if (ret != NO_ERROR) {
598 return ret;
599 }
600
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700601 // check calling permissions
602 if (!settingsAllowed()) {
603 return PERMISSION_DENIED;
604 }
605
606 AutoMutex lock(mHardwareLock);
607 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700608 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700609 mHardwareStatus = AUDIO_HW_IDLE;
610 return ret;
611}
612
613bool AudioFlinger::getMicMute() const
614{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700615 status_t ret = initCheck();
616 if (ret != NO_ERROR) {
617 return false;
618 }
619
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700620 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700621 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700622 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700623 mHardwareStatus = AUDIO_HW_IDLE;
624 return state;
625}
626
627status_t AudioFlinger::setMasterMute(bool muted)
628{
629 // check calling permissions
630 if (!settingsAllowed()) {
631 return PERMISSION_DENIED;
632 }
Eric Laurenta553c252009-07-17 12:17:14 -0700633
Eric Laurent01635942011-01-18 18:39:02 -0800634 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700635 mMasterMute = muted;
636 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700637 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700638
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700639 return NO_ERROR;
640}
641
642float AudioFlinger::masterVolume() const
643{
Eric Laurenta553c252009-07-17 12:17:14 -0700644 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700645}
646
647bool AudioFlinger::masterMute() const
648{
Eric Laurenta553c252009-07-17 12:17:14 -0700649 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700650}
651
Eric Laurentddb78e72009-07-28 08:44:33 -0700652status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700653{
654 // check calling permissions
655 if (!settingsAllowed()) {
656 return PERMISSION_DENIED;
657 }
658
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700659 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700660 return BAD_VALUE;
661 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800662
Eric Laurenta553c252009-07-17 12:17:14 -0700663 AutoMutex lock(mLock);
664 PlaybackThread *thread = NULL;
665 if (output) {
666 thread = checkPlaybackThread_l(output);
667 if (thread == NULL) {
668 return BAD_VALUE;
669 }
670 }
671
Eric Laurenta553c252009-07-17 12:17:14 -0700672 mStreamTypes[stream].volume = value;
673
674 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700675 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700676 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700677 }
Eric Laurenta553c252009-07-17 12:17:14 -0700678 } else {
679 thread->setStreamVolume(stream, value);
680 }
Eric Laurentef028272009-04-21 07:56:33 -0700681
Eric Laurent415f3e22009-10-21 08:14:22 -0700682 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700683}
684
685status_t AudioFlinger::setStreamMute(int stream, bool muted)
686{
687 // check calling permissions
688 if (!settingsAllowed()) {
689 return PERMISSION_DENIED;
690 }
691
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700692 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
693 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700694 return BAD_VALUE;
695 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700696
Eric Laurent01635942011-01-18 18:39:02 -0800697 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700698 mStreamTypes[stream].mute = muted;
699 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700700 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700702 return NO_ERROR;
703}
704
Eric Laurentddb78e72009-07-28 08:44:33 -0700705float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700706{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700707 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700708 return 0.0f;
709 }
Eric Laurenta553c252009-07-17 12:17:14 -0700710
711 AutoMutex lock(mLock);
712 float volume;
713 if (output) {
714 PlaybackThread *thread = checkPlaybackThread_l(output);
715 if (thread == NULL) {
716 return 0.0f;
717 }
718 volume = thread->streamVolume(stream);
719 } else {
720 volume = mStreamTypes[stream].volume;
721 }
722
Eric Laurentef028272009-04-21 07:56:33 -0700723 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700724}
725
726bool AudioFlinger::streamMute(int stream) const
727{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700728 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700729 return true;
730 }
Eric Laurenta553c252009-07-17 12:17:14 -0700731
732 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700733}
734
Eric Laurentddb78e72009-07-28 08:44:33 -0700735status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700736{
Eric Laurenta553c252009-07-17 12:17:14 -0700737 status_t result;
738
Eric Laurentddb78e72009-07-28 08:44:33 -0700739 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700740 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
741 // check calling permissions
742 if (!settingsAllowed()) {
743 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800744 }
Eric Laurenta553c252009-07-17 12:17:14 -0700745
746 // ioHandle == 0 means the parameters are global to the audio hardware interface
747 if (ioHandle == 0) {
748 AutoMutex lock(mHardwareLock);
749 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700750 status_t final_result = NO_ERROR;
751 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
752 audio_hw_device_t *dev = mAudioHwDevs[i];
753 result = dev->set_parameters(dev, keyValuePairs.string());
754 final_result = result ?: final_result;
755 }
Eric Laurenta553c252009-07-17 12:17:14 -0700756 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700757 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
758 AudioParameter param = AudioParameter(keyValuePairs);
759 String8 value;
760 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
761 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700762 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
763 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700764 for (size_t i = 0; i < mRecordThreads.size(); i++) {
765 sp<RecordThread> thread = mRecordThreads.valueAt(i);
766 RecordThread::RecordTrack *track = thread->track();
767 if (track != NULL) {
768 audio_devices_t device = (audio_devices_t)(
769 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700770 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700771 thread->setEffectSuspended(FX_IID_AEC,
772 suspend,
773 track->sessionId());
774 thread->setEffectSuspended(FX_IID_NS,
775 suspend,
776 track->sessionId());
777 }
778 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700779 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700780 }
781 }
Dima Zavin31f188892011-04-18 16:57:27 -0700782 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700783 }
784
Eric Laurentb7d94602009-09-29 11:12:57 -0700785 // hold a strong ref on thread in case closeOutput() or closeInput() is called
786 // and the thread is exited once the lock is released
787 sp<ThreadBase> thread;
788 {
789 Mutex::Autolock _l(mLock);
790 thread = checkPlaybackThread_l(ioHandle);
791 if (thread == NULL) {
792 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700793 } else if (thread.get() == primaryPlaybackThread_l()) {
794 // indicate output device change to all input threads for pre processing
795 AudioParameter param = AudioParameter(keyValuePairs);
796 int value;
Eric Laurent10c3fc82012-03-16 20:37:59 -0700797 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
798 (value != 0)) {
Eric Laurent464d5b32011-06-17 21:29:58 -0700799 for (size_t i = 0; i < mRecordThreads.size(); i++) {
800 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
801 }
802 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700803 }
Eric Laurenta553c252009-07-17 12:17:14 -0700804 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700805 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800806 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800807 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700808 }
Eric Laurenta553c252009-07-17 12:17:14 -0700809 return BAD_VALUE;
810}
811
Eric Laurentddb78e72009-07-28 08:44:33 -0700812String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700813{
Eric Laurentddb78e72009-07-28 08:44:33 -0700814// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700815// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
816
817 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700818 String8 out_s8;
819
Dima Zavin31f188892011-04-18 16:57:27 -0700820 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
821 audio_hw_device_t *dev = mAudioHwDevs[i];
822 char *s = dev->get_parameters(dev, keys.string());
823 out_s8 += String8(s);
824 free(s);
825 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700826 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700827 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700828
829 Mutex::Autolock _l(mLock);
830
Eric Laurenta553c252009-07-17 12:17:14 -0700831 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
832 if (playbackThread != NULL) {
833 return playbackThread->getParameters(keys);
834 }
835 RecordThread *recordThread = checkRecordThread_l(ioHandle);
836 if (recordThread != NULL) {
837 return recordThread->getParameters(keys);
838 }
839 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700840}
841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
843{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700844 status_t ret = initCheck();
845 if (ret != NO_ERROR) {
846 return 0;
847 }
848
Dima Zavin31f188892011-04-18 16:57:27 -0700849 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850}
851
Eric Laurent47d0a922010-02-26 02:47:27 -0800852unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
853{
854 if (ioHandle == 0) {
855 return 0;
856 }
857
858 Mutex::Autolock _l(mLock);
859
860 RecordThread *recordThread = checkRecordThread_l(ioHandle);
861 if (recordThread != NULL) {
862 return recordThread->getInputFramesLost();
863 }
864 return 0;
865}
866
Eric Laurent415f3e22009-10-21 08:14:22 -0700867status_t AudioFlinger::setVoiceVolume(float value)
868{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700869 status_t ret = initCheck();
870 if (ret != NO_ERROR) {
871 return ret;
872 }
873
Eric Laurent415f3e22009-10-21 08:14:22 -0700874 // check calling permissions
875 if (!settingsAllowed()) {
876 return PERMISSION_DENIED;
877 }
878
879 AutoMutex lock(mHardwareLock);
880 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700881 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700882 mHardwareStatus = AUDIO_HW_IDLE;
883
884 return ret;
885}
886
Eric Laurent0986e792010-01-19 17:37:09 -0800887status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
888{
889 status_t status;
890
891 Mutex::Autolock _l(mLock);
892
893 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
894 if (playbackThread != NULL) {
895 return playbackThread->getRenderPosition(halFrames, dspFrames);
896 }
897
898 return BAD_VALUE;
899}
900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
902{
Eric Laurenta553c252009-07-17 12:17:14 -0700903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 Mutex::Autolock _l(mLock);
905
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700906 int pid = IPCThreadState::self()->getCallingPid();
907 if (mNotificationClients.indexOfKey(pid) < 0) {
908 sp<NotificationClient> notificationClient = new NotificationClient(this,
909 client,
910 pid);
911 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700912
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700913 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700914
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700915 sp<IBinder> binder = client->asBinder();
916 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700918 // the config change is always sent from playback or record threads to avoid deadlock
919 // with AudioSystem::gLock
920 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
921 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
922 }
Eric Laurenta553c252009-07-17 12:17:14 -0700923
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700924 for (size_t i = 0; i < mRecordThreads.size(); i++) {
925 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
927 }
928}
929
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700930void AudioFlinger::removeNotificationClient(pid_t pid)
931{
932 Mutex::Autolock _l(mLock);
933
934 int index = mNotificationClients.indexOfKey(pid);
935 if (index >= 0) {
936 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
937 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700938 mNotificationClients.removeItem(pid);
939 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700940
941 LOGV("%d died, releasing its sessions", pid);
942 int num = mAudioSessionRefs.size();
943 bool removed = false;
944 for (int i = 0; i< num; i++) {
945 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
946 LOGV(" pid %d @ %d", ref->pid, i);
947 if (ref->pid == pid) {
948 LOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
949 mAudioSessionRefs.removeAt(i);
950 delete ref;
951 removed = true;
952 i--;
953 num--;
954 }
955 }
956 if (removed) {
957 purgeStaleEffects_l();
958 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700959}
960
Eric Laurent296a0ec2009-09-15 07:10:12 -0700961// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700962void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
963{
Eric Laurent49f02be2009-11-19 09:00:56 -0800964 size_t size = mNotificationClients.size();
965 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700966 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700967 }
968}
969
Eric Laurentb9481d82009-09-17 05:12:56 -0700970// removeClient_l() must be called with AudioFlinger::mLock held
971void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700972{
Eric Laurentb9481d82009-09-17 05:12:56 -0700973 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700974 mClients.removeItem(pid);
975}
976
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700977
Eric Laurenta553c252009-07-17 12:17:14 -0700978// ----------------------------------------------------------------------------
979
Eric Laurent464d5b32011-06-17 21:29:58 -0700980AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700981 : Thread(false),
982 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700983 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
984 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700985{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700986 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987}
988
Eric Laurenta553c252009-07-17 12:17:14 -0700989AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700991 mParamCond.broadcast();
992 mNewParameters.clear();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700993 // do not lock the mutex in destructor
994 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -0700995 if (mPowerManager != 0) {
996 sp<IBinder> binder = mPowerManager->asBinder();
997 binder->unlinkToDeath(mDeathRecipient);
998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999}
1000
Eric Laurenta553c252009-07-17 12:17:14 -07001001void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001002{
Eric Laurentb7d94602009-09-29 11:12:57 -07001003 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -07001004 // destroyed in the middle of requestExitAndWait()
1005 sp <ThreadBase> strongMe = this;
1006
1007 LOGV("ThreadBase::exit");
1008 {
1009 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001010 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001011 requestExit();
1012 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001013 }
Eric Laurenta553c252009-07-17 12:17:14 -07001014 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001015}
Eric Laurenta553c252009-07-17 12:17:14 -07001016
1017uint32_t AudioFlinger::ThreadBase::sampleRate() const
1018{
1019 return mSampleRate;
1020}
1021
1022int AudioFlinger::ThreadBase::channelCount() const
1023{
Eric Laurentb0a01472010-05-14 05:45:46 -07001024 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001025}
1026
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001027uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001028{
1029 return mFormat;
1030}
1031
1032size_t AudioFlinger::ThreadBase::frameCount() const
1033{
1034 return mFrameCount;
1035}
1036
1037status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1038{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001039 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001040
Eric Laurent8fce46a2009-08-04 09:45:33 -07001041 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001042 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001043
Eric Laurent8fce46a2009-08-04 09:45:33 -07001044 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001045 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001046 // wait condition with timeout in case the thread loop has exited
1047 // before the request could be processed
Eric Laurent5f37be32011-09-13 11:40:21 -07001048 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001049 status = mParamStatus;
1050 mWaitWorkCV.signal();
1051 } else {
1052 status = TIMED_OUT;
1053 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001054 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001055}
1056
1057void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1058{
1059 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001060 sendConfigEvent_l(event, param);
1061}
1062
1063// sendConfigEvent_l() must be called with ThreadBase::mLock held
1064void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1065{
Eric Laurenta553c252009-07-17 12:17:14 -07001066 ConfigEvent *configEvent = new ConfigEvent();
1067 configEvent->mEvent = event;
1068 configEvent->mParam = param;
1069 mConfigEvents.add(configEvent);
1070 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1071 mWaitWorkCV.signal();
1072}
1073
1074void AudioFlinger::ThreadBase::processConfigEvents()
1075{
1076 mLock.lock();
1077 while(!mConfigEvents.isEmpty()) {
1078 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1079 ConfigEvent *configEvent = mConfigEvents[0];
1080 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001081 // release mLock before locking AudioFlinger mLock: lock order is always
1082 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001083 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001084 mAudioFlinger->mLock.lock();
1085 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1086 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001087 delete configEvent;
1088 mLock.lock();
1089 }
1090 mLock.unlock();
1091}
1092
Eric Laurent3fdb1262009-11-07 00:01:32 -08001093status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1094{
1095 const size_t SIZE = 256;
1096 char buffer[SIZE];
1097 String8 result;
1098
1099 bool locked = tryLock(mLock);
1100 if (!locked) {
1101 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1102 write(fd, buffer, strlen(buffer));
1103 }
1104
1105 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1106 result.append(buffer);
1107 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1108 result.append(buffer);
1109 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1112 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001113 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1114 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001115 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1116 result.append(buffer);
1117 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1118 result.append(buffer);
1119
1120 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1121 result.append(buffer);
1122 result.append(" Index Command");
1123 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1124 snprintf(buffer, SIZE, "\n %02d ", i);
1125 result.append(buffer);
1126 result.append(mNewParameters[i]);
1127 }
1128
1129 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1130 result.append(buffer);
1131 snprintf(buffer, SIZE, " Index event param\n");
1132 result.append(buffer);
1133 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1134 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1135 result.append(buffer);
1136 }
1137 result.append("\n");
1138
1139 write(fd, result.string(), result.size());
1140
1141 if (locked) {
1142 mLock.unlock();
1143 }
1144 return NO_ERROR;
1145}
1146
Eric Laurent1345d332011-07-24 17:49:51 -07001147status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1148{
1149 const size_t SIZE = 256;
1150 char buffer[SIZE];
1151 String8 result;
1152
1153 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1154 write(fd, buffer, strlen(buffer));
1155
1156 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1157 sp<EffectChain> chain = mEffectChains[i];
1158 if (chain != 0) {
1159 chain->dump(fd, args);
1160 }
1161 }
1162 return NO_ERROR;
1163}
1164
Eric Laurent6dbdc402011-07-22 09:04:31 -07001165void AudioFlinger::ThreadBase::acquireWakeLock()
1166{
1167 Mutex::Autolock _l(mLock);
1168 acquireWakeLock_l();
1169}
1170
1171void AudioFlinger::ThreadBase::acquireWakeLock_l()
1172{
1173 if (mPowerManager == 0) {
1174 // use checkService() to avoid blocking if power service is not up yet
1175 sp<IBinder> binder =
1176 defaultServiceManager()->checkService(String16("power"));
1177 if (binder == 0) {
1178 LOGW("Thread %s cannot connect to the power manager service", mName);
1179 } else {
1180 mPowerManager = interface_cast<IPowerManager>(binder);
1181 binder->linkToDeath(mDeathRecipient);
1182 }
1183 }
1184 if (mPowerManager != 0) {
1185 sp<IBinder> binder = new BBinder();
1186 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1187 binder,
1188 String16(mName));
1189 if (status == NO_ERROR) {
1190 mWakeLockToken = binder;
1191 }
1192 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1193 }
1194}
1195
1196void AudioFlinger::ThreadBase::releaseWakeLock()
1197{
1198 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001199 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001200}
1201
1202void AudioFlinger::ThreadBase::releaseWakeLock_l()
1203{
1204 if (mWakeLockToken != 0) {
1205 LOGV("releaseWakeLock_l() %s", mName);
1206 if (mPowerManager != 0) {
1207 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1208 }
1209 mWakeLockToken.clear();
1210 }
1211}
1212
1213void AudioFlinger::ThreadBase::clearPowerManager()
1214{
1215 Mutex::Autolock _l(mLock);
1216 releaseWakeLock_l();
1217 mPowerManager.clear();
1218}
1219
1220void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1221{
1222 sp<ThreadBase> thread = mThread.promote();
1223 if (thread != 0) {
1224 thread->clearPowerManager();
1225 }
1226 LOGW("power manager service died !!!");
1227}
Eric Laurent1345d332011-07-24 17:49:51 -07001228
Eric Laurentf82fccd2011-07-27 19:49:51 -07001229void AudioFlinger::ThreadBase::setEffectSuspended(
1230 const effect_uuid_t *type, bool suspend, int sessionId)
1231{
1232 Mutex::Autolock _l(mLock);
1233 setEffectSuspended_l(type, suspend, sessionId);
1234}
1235
1236void AudioFlinger::ThreadBase::setEffectSuspended_l(
1237 const effect_uuid_t *type, bool suspend, int sessionId)
1238{
1239 sp<EffectChain> chain;
1240 chain = getEffectChain_l(sessionId);
1241 if (chain != 0) {
1242 if (type != NULL) {
1243 chain->setEffectSuspended_l(type, suspend);
1244 } else {
1245 chain->setEffectSuspendedAll_l(suspend);
1246 }
1247 }
1248
1249 updateSuspendedSessions_l(type, suspend, sessionId);
1250}
1251
1252void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1253{
1254 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1255 if (index < 0) {
1256 return;
1257 }
1258
1259 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1260 mSuspendedSessions.editValueAt(index);
1261
1262 for (size_t i = 0; i < sessionEffects.size(); i++) {
1263 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1264 for (int j = 0; j < desc->mRefCount; j++) {
1265 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1266 chain->setEffectSuspendedAll_l(true);
1267 } else {
1268 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1269 desc->mType.timeLow);
1270 chain->setEffectSuspended_l(&desc->mType, true);
1271 }
1272 }
1273 }
1274}
1275
Eric Laurentf82fccd2011-07-27 19:49:51 -07001276void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1277 bool suspend,
1278 int sessionId)
1279{
1280 int index = mSuspendedSessions.indexOfKey(sessionId);
1281
1282 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1283
1284 if (suspend) {
1285 if (index >= 0) {
1286 sessionEffects = mSuspendedSessions.editValueAt(index);
1287 } else {
1288 mSuspendedSessions.add(sessionId, sessionEffects);
1289 }
1290 } else {
1291 if (index < 0) {
1292 return;
1293 }
1294 sessionEffects = mSuspendedSessions.editValueAt(index);
1295 }
1296
1297
1298 int key = EffectChain::kKeyForSuspendAll;
1299 if (type != NULL) {
1300 key = type->timeLow;
1301 }
1302 index = sessionEffects.indexOfKey(key);
1303
1304 sp <SuspendedSessionDesc> desc;
1305 if (suspend) {
1306 if (index >= 0) {
1307 desc = sessionEffects.valueAt(index);
1308 } else {
1309 desc = new SuspendedSessionDesc();
1310 if (type != NULL) {
1311 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1312 }
1313 sessionEffects.add(key, desc);
1314 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1315 }
1316 desc->mRefCount++;
1317 } else {
1318 if (index < 0) {
1319 return;
1320 }
1321 desc = sessionEffects.valueAt(index);
1322 if (--desc->mRefCount == 0) {
1323 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1324 sessionEffects.removeItemsAt(index);
1325 if (sessionEffects.isEmpty()) {
1326 LOGV("updateSuspendedSessions_l() restore removing session %d",
1327 sessionId);
1328 mSuspendedSessions.removeItem(sessionId);
1329 }
1330 }
1331 }
1332 if (!sessionEffects.isEmpty()) {
1333 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1334 }
1335}
1336
1337void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1338 bool enabled,
1339 int sessionId)
1340{
1341 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001342 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1343}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001344
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001345void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1346 bool enabled,
1347 int sessionId)
1348{
Eric Laurent6752ec82011-08-10 10:37:50 -07001349 if (mType != RECORD) {
1350 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1351 // another session. This gives the priority to well behaved effect control panels
1352 // and applications not using global effects.
1353 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1354 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1355 }
1356 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001357
1358 sp<EffectChain> chain = getEffectChain_l(sessionId);
1359 if (chain != 0) {
1360 chain->checkSuspendOnEffectEnabled(effect, enabled);
1361 }
1362}
1363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364// ----------------------------------------------------------------------------
1365
Eric Laurent464d5b32011-06-17 21:29:58 -07001366AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1367 AudioStreamOut* output,
1368 int id,
1369 uint32_t device)
1370 : ThreadBase(audioFlinger, id, device),
Eric Laurentd5603c12009-08-06 08:49:39 -07001371 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001372 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001374 snprintf(mName, kNameLength, "AudioOut_%d", id);
1375
Eric Laurenta553c252009-07-17 12:17:14 -07001376 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377
Eric Laurenta553c252009-07-17 12:17:14 -07001378 mMasterVolume = mAudioFlinger->masterVolume();
1379 mMasterMute = mAudioFlinger->masterMute();
1380
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001381 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001382 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1383 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001384 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386}
1387
Eric Laurenta553c252009-07-17 12:17:14 -07001388AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389{
1390 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391}
1392
Eric Laurenta553c252009-07-17 12:17:14 -07001393status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394{
1395 dumpInternals(fd, args);
1396 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001397 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 return NO_ERROR;
1399}
1400
Eric Laurenta553c252009-07-17 12:17:14 -07001401status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402{
1403 const size_t SIZE = 256;
1404 char buffer[SIZE];
1405 String8 result;
1406
Eric Laurenta553c252009-07-17 12:17:14 -07001407 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001409 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 -08001410 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001411 sp<Track> track = mTracks[i];
1412 if (track != 0) {
1413 track->dump(buffer, SIZE);
1414 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
1416 }
1417
Eric Laurenta553c252009-07-17 12:17:14 -07001418 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001420 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 -08001421 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001422 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 if (wTrack != 0) {
1424 sp<Track> track = wTrack.promote();
1425 if (track != 0) {
1426 track->dump(buffer, SIZE);
1427 result.append(buffer);
1428 }
1429 }
1430 }
1431 write(fd, result.string(), result.size());
1432 return NO_ERROR;
1433}
1434
Eric Laurenta553c252009-07-17 12:17:14 -07001435status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436{
1437 const size_t SIZE = 256;
1438 char buffer[SIZE];
1439 String8 result;
1440
Eric Laurent3fdb1262009-11-07 00:01:32 -08001441 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 result.append(buffer);
1443 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1444 result.append(buffer);
1445 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1450 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001451 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1452 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001453 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1454 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001456
1457 dumpBase(fd, args);
1458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 return NO_ERROR;
1460}
1461
1462// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001463status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464{
Eric Laurent828b9772011-08-07 16:32:26 -07001465 status_t status = initCheck();
1466 if (status == NO_ERROR) {
1467 LOGI("AudioFlinger's thread %p ready to run", this);
1468 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 LOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
Eric Laurent828b9772011-08-07 16:32:26 -07001471 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472}
1473
Eric Laurenta553c252009-07-17 12:17:14 -07001474void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001476 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477}
1478
Eric Laurenta553c252009-07-17 12:17:14 -07001479// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1480sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 const sp<AudioFlinger::Client>& client,
1482 int streamType,
1483 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001484 uint32_t format,
1485 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 int frameCount,
1487 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001488 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 status_t *status)
1490{
1491 sp<Track> track;
1492 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001493
1494 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001495 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1496 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1497 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1498 "for output %p with format %d",
1499 sampleRate, format, channelMask, mOutput, mFormat);
1500 lStatus = BAD_VALUE;
1501 goto Exit;
1502 }
Eric Laurenta553c252009-07-17 12:17:14 -07001503 }
1504 } else {
1505 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1506 if (sampleRate > mSampleRate*2) {
1507 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1508 lStatus = BAD_VALUE;
1509 goto Exit;
1510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512
Eric Laurent464d5b32011-06-17 21:29:58 -07001513 lStatus = initCheck();
1514 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001515 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001516 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518
Eric Laurenta553c252009-07-17 12:17:14 -07001519 { // scope for mLock
1520 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001521
1522 // all tracks in same audio session must share the same routing strategy otherwise
1523 // conflicts will happen when tracks are moved from one output to another by audio policy
1524 // manager
1525 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001526 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001527 for (size_t i = 0; i < mTracks.size(); ++i) {
1528 sp<Track> t = mTracks[i];
1529 if (t != 0) {
1530 if (sessionId == t->sessionId() &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001531 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001532 lStatus = BAD_VALUE;
1533 goto Exit;
1534 }
1535 }
1536 }
1537
Eric Laurenta553c252009-07-17 12:17:14 -07001538 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001539 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001540 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001541 lStatus = NO_MEMORY;
1542 goto Exit;
1543 }
1544 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001545
1546 sp<EffectChain> chain = getEffectChain_l(sessionId);
1547 if (chain != 0) {
1548 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1549 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001550 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001551 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001552 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001553
1554 // invalidate track immediately if the stream type was moved to another thread since
1555 // createTrack() was called by the client process.
1556 if (!mStreamTypes[streamType].valid) {
1557 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1558 this, streamType);
1559 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1560 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001561 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001562 lStatus = NO_ERROR;
1563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564Exit:
1565 if(status) {
1566 *status = lStatus;
1567 }
1568 return track;
1569}
1570
Eric Laurenta553c252009-07-17 12:17:14 -07001571uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572{
Eric Laurent828b9772011-08-07 16:32:26 -07001573 Mutex::Autolock _l(mLock);
1574 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001575 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001576 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 return 0;
1578 }
1579}
1580
Eric Laurenta553c252009-07-17 12:17:14 -07001581status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582{
1583 mMasterVolume = value;
1584 return NO_ERROR;
1585}
1586
Eric Laurenta553c252009-07-17 12:17:14 -07001587status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588{
1589 mMasterMute = muted;
1590 return NO_ERROR;
1591}
1592
Eric Laurenta553c252009-07-17 12:17:14 -07001593float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594{
1595 return mMasterVolume;
1596}
1597
Eric Laurenta553c252009-07-17 12:17:14 -07001598bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599{
1600 return mMasterMute;
1601}
1602
Eric Laurenta553c252009-07-17 12:17:14 -07001603status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604{
1605 mStreamTypes[stream].volume = value;
1606 return NO_ERROR;
1607}
1608
Eric Laurenta553c252009-07-17 12:17:14 -07001609status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610{
1611 mStreamTypes[stream].mute = muted;
1612 return NO_ERROR;
1613}
1614
Eric Laurenta553c252009-07-17 12:17:14 -07001615float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616{
1617 return mStreamTypes[stream].volume;
1618}
1619
Eric Laurenta553c252009-07-17 12:17:14 -07001620bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621{
1622 return mStreamTypes[stream].mute;
1623}
1624
Eric Laurenta553c252009-07-17 12:17:14 -07001625// addTrack_l() must be called with ThreadBase::mLock held
1626status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627{
1628 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001629
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001630 // set retry count for buffer fill
1631 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001632 if (mActiveTracks.indexOf(track) < 0) {
1633 // the track is newly added, make sure it fills up all its
1634 // buffers before playing. This is to ensure the client will
1635 // effectively get the latency it requested.
1636 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001637 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001638 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001639 if (track->mainBuffer() != mMixBuffer) {
1640 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1641 if (chain != 0) {
1642 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001643 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001644 }
1645 }
1646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001648 }
Eric Laurenta553c252009-07-17 12:17:14 -07001649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001651 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652
1653 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001654}
1655
Eric Laurenta553c252009-07-17 12:17:14 -07001656// destroyTrack_l() must be called with ThreadBase::mLock held
1657void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001658{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001659 track->mState = TrackBase::TERMINATED;
1660 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001661 removeTrack_l(track);
1662 }
1663}
1664
1665void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1666{
1667 mTracks.remove(track);
1668 deleteTrackName_l(track->name());
1669 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1670 if (chain != 0) {
1671 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001672 }
1673}
1674
Eric Laurenta553c252009-07-17 12:17:14 -07001675String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001676{
Eric Laurent828b9772011-08-07 16:32:26 -07001677 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001678 char *s;
1679
Eric Laurent828b9772011-08-07 16:32:26 -07001680 Mutex::Autolock _l(mLock);
1681 if (initCheck() != NO_ERROR) {
1682 return out_s8;
1683 }
1684
Dima Zavin31f188892011-04-18 16:57:27 -07001685 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001686 out_s8 = String8(s);
1687 free(s);
1688 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001689}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001690
Eric Laurent828b9772011-08-07 16:32:26 -07001691// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001692void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001693 AudioSystem::OutputDescriptor desc;
1694 void *param2 = 0;
1695
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001696 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001697
1698 switch (event) {
1699 case AudioSystem::OUTPUT_OPENED:
1700 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001701 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001702 desc.samplingRate = mSampleRate;
1703 desc.format = mFormat;
1704 desc.frameCount = mFrameCount;
1705 desc.latency = latency();
1706 param2 = &desc;
1707 break;
1708
1709 case AudioSystem::STREAM_CONFIG_CHANGED:
1710 param2 = &param;
1711 case AudioSystem::OUTPUT_CLOSED:
1712 default:
1713 break;
1714 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001715 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001716}
1717
1718void AudioFlinger::PlaybackThread::readOutputParameters()
1719{
Dima Zavin31f188892011-04-18 16:57:27 -07001720 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001721 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1722 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001723 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1724 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1725 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001726
Eric Laurenta553c252009-07-17 12:17:14 -07001727 // FIXME - Current mixer implementation only supports stereo output: Always
1728 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001729 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001730 mMixBuffer = new int16_t[mFrameCount * 2];
1731 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001732
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001733 // force reconfiguration of effect chains and engines to take new buffer size and audio
1734 // parameters into account
1735 // Note that mLock is not held when readOutputParameters() is called from the constructor
1736 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1737 // matter.
1738 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1739 Vector< sp<EffectChain> > effectChains = mEffectChains;
1740 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001741 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001742 }
Eric Laurenta553c252009-07-17 12:17:14 -07001743}
1744
Eric Laurent0986e792010-01-19 17:37:09 -08001745status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1746{
1747 if (halFrames == 0 || dspFrames == 0) {
1748 return BAD_VALUE;
1749 }
Eric Laurent828b9772011-08-07 16:32:26 -07001750 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001751 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001752 return INVALID_OPERATION;
1753 }
Dima Zavin31f188892011-04-18 16:57:27 -07001754 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001755
Dima Zavin31f188892011-04-18 16:57:27 -07001756 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001757}
1758
Eric Laurent493941b2010-07-28 01:32:47 -07001759uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001760{
1761 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001762 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001763 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001764 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001765 }
1766
1767 for (size_t i = 0; i < mTracks.size(); ++i) {
1768 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001769 if (sessionId == track->sessionId() &&
1770 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001771 result |= TRACK_SESSION;
1772 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001773 }
1774 }
1775
Eric Laurent493941b2010-07-28 01:32:47 -07001776 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001777}
1778
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001779uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1780{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001781 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001782 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001783 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1784 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001785 }
1786 for (size_t i = 0; i < mTracks.size(); i++) {
1787 sp<Track> track = mTracks[i];
1788 if (sessionId == track->sessionId() &&
1789 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001790 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001791 }
1792 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001793 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001794}
1795
Eric Laurent53334cd2010-06-23 17:38:20 -07001796
Eric Laurent828b9772011-08-07 16:32:26 -07001797AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1798{
1799 Mutex::Autolock _l(mLock);
1800 return mOutput;
1801}
1802
1803AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1804{
1805 Mutex::Autolock _l(mLock);
1806 AudioStreamOut *output = mOutput;
1807 mOutput = NULL;
1808 return output;
1809}
1810
1811// this method must always be called either with ThreadBase mLock held or inside the thread loop
1812audio_stream_t* AudioFlinger::PlaybackThread::stream()
1813{
1814 if (mOutput == NULL) {
1815 return NULL;
1816 }
1817 return &mOutput->stream->common;
1818}
1819
Eric Laurent44331692011-12-05 09:47:19 -08001820uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1821{
1822 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1823 // decoding and transfer time. So sleeping for half of the latency would likely cause
1824 // underruns
1825 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1826 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1827 } else {
1828 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1829 }
1830}
1831
Eric Laurenta553c252009-07-17 12:17:14 -07001832// ----------------------------------------------------------------------------
1833
Dima Zavin31f188892011-04-18 16:57:27 -07001834AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001835 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurent0b089652012-01-23 18:35:10 -08001836 mAudioMixer(0), mPrevMixerStatus(MIXER_IDLE)
Eric Laurenta553c252009-07-17 12:17:14 -07001837{
Eric Laurent464d5b32011-06-17 21:29:58 -07001838 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001839 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1840
1841 // FIXME - Current mixer implementation only supports stereo output
1842 if (mChannelCount == 1) {
1843 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001845}
1846
Eric Laurenta553c252009-07-17 12:17:14 -07001847AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001848{
Eric Laurenta553c252009-07-17 12:17:14 -07001849 delete mAudioMixer;
1850}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851
Eric Laurenta553c252009-07-17 12:17:14 -07001852bool AudioFlinger::MixerThread::threadLoop()
1853{
Eric Laurenta553c252009-07-17 12:17:14 -07001854 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001855 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001856 nsecs_t standbyTime = systemTime();
1857 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001858 // FIXME: Relaxed timing because of a certain device that can't meet latency
1859 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001860 // increase threshold again due to low power audio mode. The way this warning threshold is
1861 // calculated and its usefulness should be reconsidered anyway.
1862 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001863 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001864 bool longStandbyExit = false;
1865 uint32_t activeSleepTime = activeSleepTimeUs();
1866 uint32_t idleSleepTime = idleSleepTimeUs();
1867 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001868 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001869 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001870#ifdef DEBUG_CPU_USAGE
1871 ThreadCpuUsage cpu;
1872 const CentralTendencyStatistics& stats = cpu.statistics();
1873#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874
Eric Laurent6dbdc402011-07-22 09:04:31 -07001875 acquireWakeLock();
1876
Eric Laurenta553c252009-07-17 12:17:14 -07001877 while (!exitPending())
1878 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001879#ifdef DEBUG_CPU_USAGE
1880 cpu.sampleAndEnable();
1881 unsigned n = stats.n();
1882 // cpu.elapsed() is expensive, so don't call it every loop
1883 if ((n & 127) == 1) {
1884 long long elapsed = cpu.elapsed();
1885 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1886 double perLoop = elapsed / (double) n;
1887 double perLoop100 = perLoop * 0.01;
1888 double mean = stats.mean();
1889 double stddev = stats.stddev();
1890 double minimum = stats.minimum();
1891 double maximum = stats.maximum();
1892 cpu.resetStatistics();
1893 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",
1894 elapsed * .000000001, n, perLoop * .000001,
1895 mean * .001,
1896 stddev * .001,
1897 minimum * .001,
1898 maximum * .001,
1899 mean / perLoop100,
1900 stddev / perLoop100,
1901 minimum / perLoop100,
1902 maximum / perLoop100);
1903 }
1904 }
1905#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001906 processConfigEvents();
1907
Eric Laurent059b4be2009-11-09 23:32:22 -08001908 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001909 { // scope for mLock
1910
1911 Mutex::Autolock _l(mLock);
1912
1913 if (checkForNewParameters_l()) {
1914 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001915 // FIXME: Relaxed timing because of a certain device that can't meet latency
1916 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001917 // increase threshold again due to low power audio mode. The way this warning
1918 // threshold is calculated and its usefulness should be reconsidered anyway.
1919 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001920 activeSleepTime = activeSleepTimeUs();
1921 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001922 }
1923
1924 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1925
1926 // put audio hardware into standby after short delay
1927 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1928 mSuspended) {
1929 if (!mStandby) {
1930 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001931 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001932 mStandby = true;
1933 mBytesWritten = 0;
1934 }
1935
1936 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1937 // we're about to wait, flush the binder command buffer
1938 IPCThreadState::self()->flushCommands();
1939
1940 if (exitPending()) break;
1941
Eric Laurent6dbdc402011-07-22 09:04:31 -07001942 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001943 // wait until we have something to do...
1944 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1945 mWaitWorkCV.wait(mLock);
1946 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001947 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001948
Eric Laurent0b089652012-01-23 18:35:10 -08001949 mPrevMixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001950 if (mMasterMute == false) {
1951 char value[PROPERTY_VALUE_MAX];
1952 property_get("ro.audio.silent", value, "0");
1953 if (atoi(value)) {
1954 LOGD("Silence is golden");
1955 setMasterMute(true);
1956 }
1957 }
1958
1959 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001960 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001961 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001962 continue;
1963 }
1964 }
1965
Eric Laurent059b4be2009-11-09 23:32:22 -08001966 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001967
1968 // prevent any changes in effect chain list and in each effect chain
1969 // during mixing and effect process as the audio buffers could be deleted
1970 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001971 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001972 }
1973
Eric Laurent059b4be2009-11-09 23:32:22 -08001974 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001975 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001976 mAudioMixer->process();
Eric Laurent06092312012-01-23 18:56:59 -08001977 // increase sleep time progressively when application underrun condition clears.
1978 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1979 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1980 // such that we would underrun the audio HAL.
1981 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001982 sleepTimeShift--;
1983 }
Eric Laurent06092312012-01-23 18:56:59 -08001984 sleepTime = 0;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001985 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001986 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001987 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001988 // If no tracks are ready, sleep once for the duration of an output
1989 // buffer size, then write 0s to the output
1990 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001991 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001992 sleepTime = activeSleepTime >> sleepTimeShift;
1993 if (sleepTime < kMinThreadSleepTimeUs) {
1994 sleepTime = kMinThreadSleepTimeUs;
1995 }
1996 // reduce sleep time in case of consecutive application underruns to avoid
1997 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1998 // duration we would end up writing less data than needed by the audio HAL if
1999 // the condition persists.
2000 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2001 sleepTimeShift++;
2002 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002003 } else {
2004 sleepTime = idleSleepTime;
2005 }
2006 } else if (mBytesWritten != 0 ||
2007 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002008 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002009 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002010 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002011 }
Eric Laurent65b65452010-06-01 23:49:17 -07002012 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002013 }
2014
2015 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002016 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002017 }
2018 // sleepTime == 0 means we must write to audio hardware
2019 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002020 for (size_t i = 0; i < effectChains.size(); i ++) {
2021 effectChains[i]->process_l();
2022 }
2023 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002024 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002025 mLastWriteTime = systemTime();
2026 mInWrite = true;
2027 mBytesWritten += mixBufferSize;
2028
Dima Zavin31f188892011-04-18 16:57:27 -07002029 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002030 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002031 mNumWrites++;
2032 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002033 nsecs_t now = systemTime();
2034 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002035 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002036 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002037 if ((now - lastWarning) > kWarningThrottle) {
2038 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2039 ns2ms(delta), mNumDelayedWrites, this);
2040 lastWarning = now;
2041 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002042 if (mStandby) {
2043 longStandbyExit = true;
2044 }
Eric Laurenta553c252009-07-17 12:17:14 -07002045 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002046 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002047 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002048 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002049 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002050 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002051 }
2052
2053 // finally let go of all our tracks, without the lock held
2054 // since we can't guarantee the destructors won't acquire that
2055 // same lock.
2056 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002057
2058 // Effect chains will be actually deleted here if they were removed from
2059 // mEffectChains list during mixing or effects processing
2060 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002061 }
2062
2063 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002064 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002065 }
Eric Laurenta553c252009-07-17 12:17:14 -07002066
Eric Laurent6dbdc402011-07-22 09:04:31 -07002067 releaseWakeLock();
2068
Eric Laurenta553c252009-07-17 12:17:14 -07002069 LOGV("MixerThread %p exiting", this);
2070 return false;
2071}
2072
2073// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002074uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002075{
2076
Eric Laurent059b4be2009-11-09 23:32:22 -08002077 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002078 // find out which tracks need to be processed
2079 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002080 size_t mixedTracks = 0;
2081 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002082
2083 float masterVolume = mMasterVolume;
2084 bool masterMute = mMasterMute;
2085
Eric Laurent8cc93b92010-08-11 05:20:11 -07002086 if (masterMute) {
2087 masterVolume = 0;
2088 }
Eric Laurent65b65452010-06-01 23:49:17 -07002089 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002090 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002091 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002092 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002093 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002094 masterVolume = (float)((v + (1 << 23)) >> 24);
2095 chain.clear();
2096 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002097
Eric Laurenta553c252009-07-17 12:17:14 -07002098 for (size_t i=0 ; i<count ; i++) {
2099 sp<Track> t = activeTracks[i].promote();
2100 if (t == 0) continue;
2101
2102 Track* const track = t.get();
2103 audio_track_cblk_t* cblk = track->cblk();
2104
2105 // The first time a track is added we wait
2106 // for all its buffers to be filled before processing it
2107 mAudioMixer->setActiveTrack(track->name());
Eric Laurent8a04fe02011-11-08 18:10:16 -08002108 // make sure that we have enough frames to mix one full buffer.
2109 // enforce this condition only once to enable draining the buffer in case the client
2110 // app does not call stop() and relies on underrun to stop:
Eric Laurent0b089652012-01-23 18:35:10 -08002111 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002112 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002113 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002114 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent0b089652012-01-23 18:35:10 -08002115 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002116 if (t->sampleRate() == (int)mSampleRate) {
2117 minFrames = mFrameCount;
2118 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002119 // +1 for rounding and +1 for additional sample needed for interpolation
2120 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2121 // add frames already consumed but not yet released by the resampler
2122 // because cblk->framesReady() will include these frames
2123 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2124 // the minimum track buffer size is normally twice the number of frames necessary
2125 // to fill one buffer and the resampler should not leave more than one buffer worth
2126 // of unreleased frames after each pass, but just in case...
2127 LOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002128 }
2129 }
2130 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002131 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002132 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002133 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002134
Eric Laurent65b65452010-06-01 23:49:17 -07002135 mixedTracks++;
2136
2137 // track->mainBuffer() != mMixBuffer means there is an effect chain
2138 // connected to the track
2139 chain.clear();
2140 if (track->mainBuffer() != mMixBuffer) {
2141 chain = getEffectChain_l(track->sessionId());
2142 // Delegate volume control to effect in track effect chain if needed
2143 if (chain != 0) {
2144 tracksWithEffect++;
2145 } else {
2146 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2147 track->name(), track->sessionId());
2148 }
2149 }
2150
2151
2152 int param = AudioMixer::VOLUME;
2153 if (track->mFillingUpStatus == Track::FS_FILLED) {
2154 // no ramp for the first volume setting
2155 track->mFillingUpStatus = Track::FS_ACTIVE;
2156 if (track->mState == TrackBase::RESUMING) {
2157 track->mState = TrackBase::ACTIVE;
2158 param = AudioMixer::RAMP_VOLUME;
2159 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08002160 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002161 } else if (cblk->server != 0) {
2162 // If the track is stopped before the first frame was mixed,
2163 // do not apply ramp
2164 param = AudioMixer::RAMP_VOLUME;
2165 }
2166
Eric Laurenta553c252009-07-17 12:17:14 -07002167 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002168 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002169 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002170 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002171 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002172 if (track->isPausing()) {
2173 track->setPaused();
2174 }
2175 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002176
Glenn Kasten871c16c2010-03-05 12:18:01 -08002177 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002178 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002179 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002180 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2181 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002182
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002183 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002184 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002185 // Delegate volume control to effect in track effect chain if needed
2186 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2187 // Do not ramp volume if volume is controlled by effect
2188 param = AudioMixer::VOLUME;
2189 track->mHasVolumeController = true;
2190 } else {
2191 // force no volume ramp when volume controller was just disabled or removed
2192 // from effect chain to avoid volume spike
2193 if (track->mHasVolumeController) {
2194 param = AudioMixer::VOLUME;
2195 }
2196 track->mHasVolumeController = false;
2197 }
2198
2199 // Convert volumes from 8.24 to 4.12 format
2200 int16_t left, right, aux;
2201 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2202 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2203 left = int16_t(v_clamped);
2204 v_clamped = (vr + (1 << 11)) >> 12;
2205 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2206 right = int16_t(v_clamped);
2207
2208 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2209 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002210
Eric Laurent65b65452010-06-01 23:49:17 -07002211 // XXX: these things DON'T need to be done each time
2212 mAudioMixer->setBufferProvider(track);
2213 mAudioMixer->enable(AudioMixer::MIXING);
2214
2215 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2216 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2217 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002218 mAudioMixer->setParameter(
2219 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002220 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002221 mAudioMixer->setParameter(
2222 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002223 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002224 mAudioMixer->setParameter(
2225 AudioMixer::RESAMPLE,
2226 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002227 (void *)(cblk->sampleRate));
2228 mAudioMixer->setParameter(
2229 AudioMixer::TRACK,
2230 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2231 mAudioMixer->setParameter(
2232 AudioMixer::TRACK,
2233 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002234
2235 // reset retry count
2236 track->mRetryCount = kMaxTrackRetries;
Eric Laurent0b089652012-01-23 18:35:10 -08002237 // If one track is ready, set the mixer ready if:
2238 // - the mixer was not ready during previous round OR
2239 // - no other track is not ready
2240 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2241 mixerStatus != MIXER_TRACKS_ENABLED) {
2242 mixerStatus = MIXER_TRACKS_READY;
2243 }
Eric Laurenta553c252009-07-17 12:17:14 -07002244 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002245 //LOGV("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 -07002246 if (track->isStopped()) {
2247 track->reset();
2248 }
2249 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2250 // We have consumed all the buffers of this track.
2251 // Remove it from the list of active tracks.
2252 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002253 } else {
2254 // No buffers for this track. Give it a few chances to
2255 // fill a buffer, then remove it from active list.
2256 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07002257 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002258 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002259 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002260 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent0b089652012-01-23 18:35:10 -08002261 // If one track is not ready, mark the mixer also not ready if:
2262 // - the mixer was ready during previous round OR
2263 // - no other track is ready
2264 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2265 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002266 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002267 }
Eric Laurenta553c252009-07-17 12:17:14 -07002268 }
Eric Laurent65b65452010-06-01 23:49:17 -07002269 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07002270 }
2271 }
2272
2273 // remove all the tracks that need to be...
2274 count = tracksToRemove->size();
2275 if (UNLIKELY(count)) {
2276 for (size_t i=0 ; i<count ; i++) {
2277 const sp<Track>& track = tracksToRemove->itemAt(i);
2278 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002279 if (track->mainBuffer() != mMixBuffer) {
2280 chain = getEffectChain_l(track->sessionId());
2281 if (chain != 0) {
2282 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002283 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002284 }
2285 }
Eric Laurenta553c252009-07-17 12:17:14 -07002286 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002287 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002288 }
2289 }
2290 }
2291
Eric Laurent65b65452010-06-01 23:49:17 -07002292 // mix buffer must be cleared if all tracks are connected to an
2293 // effect chain as in this case the mixer will not write to
2294 // mix buffer and track effects will accumulate into it
2295 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2296 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2297 }
2298
Eric Laurent0b089652012-01-23 18:35:10 -08002299 mPrevMixerStatus = mixerStatus;
Eric Laurent059b4be2009-11-09 23:32:22 -08002300 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002301}
2302
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002303void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002304{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002305 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2306 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002307 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002308
Eric Laurenta553c252009-07-17 12:17:14 -07002309 size_t size = mTracks.size();
2310 for (size_t i = 0; i < size; i++) {
2311 sp<Track> t = mTracks[i];
2312 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002313 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002314 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002315 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002316 }
2317}
Eric Laurenta553c252009-07-17 12:17:14 -07002318
Eric Laurent05ce0942011-08-30 10:18:54 -07002319void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2320{
2321 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2322 this, streamType, valid);
2323 Mutex::Autolock _l(mLock);
2324
2325 mStreamTypes[streamType].valid = valid;
2326}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327
Eric Laurenta553c252009-07-17 12:17:14 -07002328// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002329int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330{
2331 return mAudioMixer->getTrackName();
2332}
2333
Eric Laurenta553c252009-07-17 12:17:14 -07002334// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002335void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336{
Eric Laurent0a080292009-12-07 10:53:10 -08002337 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 mAudioMixer->deleteTrackName(name);
2339}
2340
Eric Laurenta553c252009-07-17 12:17:14 -07002341// checkForNewParameters_l() must be called with ThreadBase::mLock held
2342bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343{
Eric Laurenta553c252009-07-17 12:17:14 -07002344 bool reconfig = false;
2345
Eric Laurent8fce46a2009-08-04 09:45:33 -07002346 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002347 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002348 String8 keyValuePair = mNewParameters[0];
2349 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002350 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002351
Eric Laurenta553c252009-07-17 12:17:14 -07002352 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2353 reconfig = true;
2354 }
2355 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002356 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002357 status = BAD_VALUE;
2358 } else {
2359 reconfig = true;
2360 }
2361 }
2362 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002363 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002364 status = BAD_VALUE;
2365 } else {
2366 reconfig = true;
2367 }
2368 }
2369 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2370 // do not accept frame count changes if tracks are open as the track buffer
2371 // size depends on frame count and correct behavior would not be garantied
2372 // if frame count is changed after track creation
2373 if (!mTracks.isEmpty()) {
2374 status = INVALID_OPERATION;
2375 } else {
2376 reconfig = true;
2377 }
2378 }
Eric Laurent65b65452010-06-01 23:49:17 -07002379 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002380 // when changing the audio output device, call addBatteryData to notify
2381 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002382 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002383 uint32_t params = 0;
2384 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002385 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002386 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2387 }
2388
2389 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002390 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002391 // check if any other device (except speaker) is on
2392 if (value & deviceWithoutSpeaker ) {
2393 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2394 }
2395
2396 if (params != 0) {
2397 addBatteryData(params);
2398 }
2399 }
2400
Eric Laurent65b65452010-06-01 23:49:17 -07002401 // forward device change to effects that have requested to be
2402 // aware of attached audio device.
2403 mDevice = (uint32_t)value;
2404 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002405 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002406 }
2407 }
2408
Eric Laurenta553c252009-07-17 12:17:14 -07002409 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002410 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002411 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002412 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002413 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002414 mStandby = true;
2415 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002416 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002417 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002418 }
2419 if (status == NO_ERROR && reconfig) {
2420 delete mAudioMixer;
2421 readOutputParameters();
2422 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2423 for (size_t i = 0; i < mTracks.size() ; i++) {
2424 int name = getTrackName_l();
2425 if (name < 0) break;
2426 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002427 // limit track sample rate to 2 x new output sample rate
2428 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2429 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2430 }
Eric Laurenta553c252009-07-17 12:17:14 -07002431 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002432 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002433 }
2434 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002435
2436 mNewParameters.removeAt(0);
2437
Eric Laurenta553c252009-07-17 12:17:14 -07002438 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002439 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002440 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2441 // already timed out waiting for the status and will never signal the condition.
2442 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07002443 }
2444 return reconfig;
2445}
2446
2447status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2448{
2449 const size_t SIZE = 256;
2450 char buffer[SIZE];
2451 String8 result;
2452
2453 PlaybackThread::dumpInternals(fd, args);
2454
2455 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2456 result.append(buffer);
2457 write(fd, result.string(), result.size());
2458 return NO_ERROR;
2459}
2460
Eric Laurent059b4be2009-11-09 23:32:22 -08002461uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2462{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002463 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002464}
2465
Eric Laurent8448a792010-08-18 18:13:17 -07002466uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2467{
2468 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2469}
2470
Eric Laurenta553c252009-07-17 12:17:14 -07002471// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002472AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002473 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002474{
Eric Laurent464d5b32011-06-17 21:29:58 -07002475 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002476}
2477
2478AudioFlinger::DirectOutputThread::~DirectOutputThread()
2479{
2480}
2481
2482
Eric Laurent65b65452010-06-01 23:49:17 -07002483static inline int16_t clamp16(int32_t sample)
2484{
2485 if ((sample>>15) ^ (sample>>31))
2486 sample = 0x7FFF ^ (sample>>31);
2487 return sample;
2488}
2489
2490static inline
2491int32_t mul(int16_t in, int16_t v)
2492{
2493#if defined(__arm__) && !defined(__thumb__)
2494 int32_t out;
2495 asm( "smulbb %[out], %[in], %[v] \n"
2496 : [out]"=r"(out)
2497 : [in]"%r"(in), [v]"r"(v)
2498 : );
2499 return out;
2500#else
2501 return in * int32_t(v);
2502#endif
2503}
2504
2505void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2506{
2507 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002508 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002509 return;
2510 }
2511
2512 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002513 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002514 size_t count = mFrameCount * mChannelCount;
2515 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2516 int16_t *dst = mMixBuffer + count-1;
2517 while(count--) {
2518 *dst-- = (int16_t)(*src--^0x80) << 8;
2519 }
2520 }
2521
2522 size_t frameCount = mFrameCount;
2523 int16_t *out = mMixBuffer;
2524 if (ramp) {
2525 if (mChannelCount == 1) {
2526 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2527 int32_t vlInc = d / (int32_t)frameCount;
2528 int32_t vl = ((int32_t)mLeftVolShort << 16);
2529 do {
2530 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2531 out++;
2532 vl += vlInc;
2533 } while (--frameCount);
2534
2535 } else {
2536 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2537 int32_t vlInc = d / (int32_t)frameCount;
2538 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2539 int32_t vrInc = d / (int32_t)frameCount;
2540 int32_t vl = ((int32_t)mLeftVolShort << 16);
2541 int32_t vr = ((int32_t)mRightVolShort << 16);
2542 do {
2543 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2544 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2545 out += 2;
2546 vl += vlInc;
2547 vr += vrInc;
2548 } while (--frameCount);
2549 }
2550 } else {
2551 if (mChannelCount == 1) {
2552 do {
2553 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2554 out++;
2555 } while (--frameCount);
2556 } else {
2557 do {
2558 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2559 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2560 out += 2;
2561 } while (--frameCount);
2562 }
2563 }
2564
2565 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002566 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002567 size_t count = mFrameCount * mChannelCount;
2568 int16_t *src = mMixBuffer;
2569 uint8_t *dst = (uint8_t *)mMixBuffer;
2570 while(count--) {
2571 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2572 }
2573 }
2574
2575 mLeftVolShort = leftVol;
2576 mRightVolShort = rightVol;
2577}
2578
Eric Laurenta553c252009-07-17 12:17:14 -07002579bool AudioFlinger::DirectOutputThread::threadLoop()
2580{
Eric Laurent059b4be2009-11-09 23:32:22 -08002581 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002582 sp<Track> trackToRemove;
2583 sp<Track> activeTrack;
2584 nsecs_t standbyTime = systemTime();
2585 int8_t *curBuf;
2586 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002587 uint32_t activeSleepTime = activeSleepTimeUs();
2588 uint32_t idleSleepTime = idleSleepTimeUs();
2589 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002590 // use shorter standby delay as on normal output to release
2591 // hardware resources as soon as possible
2592 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002593
Eric Laurent6dbdc402011-07-22 09:04:31 -07002594 acquireWakeLock();
2595
Eric Laurenta553c252009-07-17 12:17:14 -07002596 while (!exitPending())
2597 {
Eric Laurent65b65452010-06-01 23:49:17 -07002598 bool rampVolume;
2599 uint16_t leftVol;
2600 uint16_t rightVol;
2601 Vector< sp<EffectChain> > effectChains;
2602
Eric Laurenta553c252009-07-17 12:17:14 -07002603 processConfigEvents();
2604
Eric Laurent059b4be2009-11-09 23:32:22 -08002605 mixerStatus = MIXER_IDLE;
2606
Eric Laurenta553c252009-07-17 12:17:14 -07002607 { // scope for the mLock
2608
2609 Mutex::Autolock _l(mLock);
2610
2611 if (checkForNewParameters_l()) {
2612 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002613 activeSleepTime = activeSleepTimeUs();
2614 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002615 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002616 }
2617
2618 // put audio hardware into standby after short delay
2619 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2620 mSuspended) {
2621 // wait until we have something to do...
2622 if (!mStandby) {
2623 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002624 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002625 mStandby = true;
2626 mBytesWritten = 0;
2627 }
2628
2629 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2630 // we're about to wait, flush the binder command buffer
2631 IPCThreadState::self()->flushCommands();
2632
2633 if (exitPending()) break;
2634
Eric Laurent6dbdc402011-07-22 09:04:31 -07002635 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002636 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2637 mWaitWorkCV.wait(mLock);
2638 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002639 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002640
2641 if (mMasterMute == false) {
2642 char value[PROPERTY_VALUE_MAX];
2643 property_get("ro.audio.silent", value, "0");
2644 if (atoi(value)) {
2645 LOGD("Silence is golden");
2646 setMasterMute(true);
2647 }
2648 }
2649
Eric Laurentef9500f2010-03-11 14:47:00 -08002650 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002651 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002652 continue;
2653 }
2654 }
2655
Eric Laurent65b65452010-06-01 23:49:17 -07002656 effectChains = mEffectChains;
2657
Eric Laurenta553c252009-07-17 12:17:14 -07002658 // find out which tracks need to be processed
2659 if (mActiveTracks.size() != 0) {
2660 sp<Track> t = mActiveTracks[0].promote();
2661 if (t == 0) continue;
2662
2663 Track* const track = t.get();
2664 audio_track_cblk_t* cblk = track->cblk();
2665
2666 // The first time a track is added we wait
2667 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002668 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002669 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002670 {
2671 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2672
Eric Laurent65b65452010-06-01 23:49:17 -07002673 if (track->mFillingUpStatus == Track::FS_FILLED) {
2674 track->mFillingUpStatus = Track::FS_ACTIVE;
2675 mLeftVolFloat = mRightVolFloat = 0;
2676 mLeftVolShort = mRightVolShort = 0;
2677 if (track->mState == TrackBase::RESUMING) {
2678 track->mState = TrackBase::ACTIVE;
2679 rampVolume = true;
2680 }
2681 } else if (cblk->server != 0) {
2682 // If the track is stopped before the first frame was mixed,
2683 // do not apply ramp
2684 rampVolume = true;
2685 }
Eric Laurenta553c252009-07-17 12:17:14 -07002686 // compute volume for this track
2687 float left, right;
2688 if (track->isMuted() || mMasterMute || track->isPausing() ||
2689 mStreamTypes[track->type()].mute) {
2690 left = right = 0;
2691 if (track->isPausing()) {
2692 track->setPaused();
2693 }
2694 } else {
2695 float typeVolume = mStreamTypes[track->type()].volume;
2696 float v = mMasterVolume * typeVolume;
2697 float v_clamped = v * cblk->volume[0];
2698 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2699 left = v_clamped/MAX_GAIN;
2700 v_clamped = v * cblk->volume[1];
2701 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2702 right = v_clamped/MAX_GAIN;
2703 }
2704
Eric Laurent65b65452010-06-01 23:49:17 -07002705 if (left != mLeftVolFloat || right != mRightVolFloat) {
2706 mLeftVolFloat = left;
2707 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002708
Eric Laurent65b65452010-06-01 23:49:17 -07002709 // If audio HAL implements volume control,
2710 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002711 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002712 left = 1.0f;
2713 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002714 }
Eric Laurent65b65452010-06-01 23:49:17 -07002715
2716 // Convert volumes from float to 8.24
2717 uint32_t vl = (uint32_t)(left * (1 << 24));
2718 uint32_t vr = (uint32_t)(right * (1 << 24));
2719
2720 // Delegate volume control to effect in track effect chain if needed
2721 // only one effect chain can be present on DirectOutputThread, so if
2722 // there is one, the track is connected to it
2723 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002724 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002725 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002726 rampVolume = false;
2727 }
2728 }
2729
2730 // Convert volumes from 8.24 to 4.12 format
2731 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2732 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2733 leftVol = (uint16_t)v_clamped;
2734 v_clamped = (vr + (1 << 11)) >> 12;
2735 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2736 rightVol = (uint16_t)v_clamped;
2737 } else {
2738 leftVol = mLeftVolShort;
2739 rightVol = mRightVolShort;
2740 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002741 }
2742
2743 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002744 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002745 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002746 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002747 } else {
2748 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2749 if (track->isStopped()) {
2750 track->reset();
2751 }
2752 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2753 // We have consumed all the buffers of this track.
2754 // Remove it from the list of active tracks.
2755 trackToRemove = track;
2756 } else {
2757 // No buffers for this track. Give it a few chances to
2758 // fill a buffer, then remove it from active list.
2759 if (--(track->mRetryCount) <= 0) {
2760 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2761 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002762 } else {
2763 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002764 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002765 }
Eric Laurenta553c252009-07-17 12:17:14 -07002766 }
2767 }
2768
2769 // remove all the tracks that need to be...
2770 if (UNLIKELY(trackToRemove != 0)) {
2771 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002772 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002773 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2774 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002775 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002776 }
Eric Laurenta553c252009-07-17 12:17:14 -07002777 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002778 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002779 }
2780 }
Eric Laurent65b65452010-06-01 23:49:17 -07002781
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002782 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002783 }
2784
Eric Laurent059b4be2009-11-09 23:32:22 -08002785 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002786 AudioBufferProvider::Buffer buffer;
2787 size_t frameCount = mFrameCount;
2788 curBuf = (int8_t *)mMixBuffer;
2789 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002790 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002791 buffer.frameCount = frameCount;
2792 activeTrack->getNextBuffer(&buffer);
2793 if (UNLIKELY(buffer.raw == 0)) {
2794 memset(curBuf, 0, frameCount * mFrameSize);
2795 break;
2796 }
2797 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2798 frameCount -= buffer.frameCount;
2799 curBuf += buffer.frameCount * mFrameSize;
2800 activeTrack->releaseBuffer(&buffer);
2801 }
2802 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002803 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002804 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002805 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002806 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2807 sleepTime = activeSleepTime;
2808 } else {
2809 sleepTime = idleSleepTime;
2810 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002811 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002812 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002813 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002814 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002815 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002816
Eric Laurentf69a3f82009-09-22 00:35:48 -07002817 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002818 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002819 }
2820 // sleepTime == 0 means we must write to audio hardware
2821 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002822 if (mixerStatus == MIXER_TRACKS_READY) {
2823 applyVolume(leftVol, rightVol, rampVolume);
2824 }
2825 for (size_t i = 0; i < effectChains.size(); i ++) {
2826 effectChains[i]->process_l();
2827 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002828 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002829
Eric Laurentf69a3f82009-09-22 00:35:48 -07002830 mLastWriteTime = systemTime();
2831 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002832 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002833 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002834 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002835 mNumWrites++;
2836 mInWrite = false;
2837 mStandby = false;
2838 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002839 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002840 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002841 }
2842
2843 // finally let go of removed track, without the lock held
2844 // since we can't guarantee the destructors won't acquire that
2845 // same lock.
2846 trackToRemove.clear();
2847 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002848
2849 // Effect chains will be actually deleted here if they were removed from
2850 // mEffectChains list during mixing or effects processing
2851 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002852 }
2853
2854 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002855 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002856 }
Eric Laurenta553c252009-07-17 12:17:14 -07002857
Eric Laurent6dbdc402011-07-22 09:04:31 -07002858 releaseWakeLock();
2859
Eric Laurenta553c252009-07-17 12:17:14 -07002860 LOGV("DirectOutputThread %p exiting", this);
2861 return false;
2862}
2863
2864// getTrackName_l() must be called with ThreadBase::mLock held
2865int AudioFlinger::DirectOutputThread::getTrackName_l()
2866{
2867 return 0;
2868}
2869
2870// deleteTrackName_l() must be called with ThreadBase::mLock held
2871void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2872{
2873}
2874
2875// checkForNewParameters_l() must be called with ThreadBase::mLock held
2876bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2877{
2878 bool reconfig = false;
2879
Eric Laurent8fce46a2009-08-04 09:45:33 -07002880 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002881 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002882 String8 keyValuePair = mNewParameters[0];
2883 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002884 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002885
Eric Laurenta553c252009-07-17 12:17:14 -07002886 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2887 // do not accept frame count changes if tracks are open as the track buffer
2888 // size depends on frame count and correct behavior would not be garantied
2889 // if frame count is changed after track creation
2890 if (!mTracks.isEmpty()) {
2891 status = INVALID_OPERATION;
2892 } else {
2893 reconfig = true;
2894 }
2895 }
2896 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002897 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002898 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002899 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002900 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002901 mStandby = true;
2902 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002903 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002904 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002905 }
2906 if (status == NO_ERROR && reconfig) {
2907 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002908 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002909 }
2910 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002911
2912 mNewParameters.removeAt(0);
2913
Eric Laurenta553c252009-07-17 12:17:14 -07002914 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002915 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002916 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2917 // already timed out waiting for the status and will never signal the condition.
2918 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07002919 }
2920 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002921}
2922
Eric Laurent059b4be2009-11-09 23:32:22 -08002923uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002924{
2925 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002926 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002927 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002928 } else {
2929 time = 10000;
2930 }
2931 return time;
2932}
2933
2934uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2935{
2936 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002937 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002938 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002939 } else {
2940 time = 10000;
2941 }
2942 return time;
2943}
2944
Eric Laurent8448a792010-08-18 18:13:17 -07002945uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2946{
2947 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002948 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002949 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2950 } else {
2951 time = 10000;
2952 }
2953 return time;
2954}
2955
2956
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002957// ----------------------------------------------------------------------------
2958
Eric Laurent49f02be2009-11-19 09:00:56 -08002959AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002960 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002961{
Eric Laurent464d5b32011-06-17 21:29:58 -07002962 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002963 addOutputTrack(mainThread);
2964}
2965
2966AudioFlinger::DuplicatingThread::~DuplicatingThread()
2967{
Eric Laurent0a080292009-12-07 10:53:10 -08002968 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2969 mOutputTracks[i]->destroy();
2970 }
Eric Laurenta553c252009-07-17 12:17:14 -07002971 mOutputTracks.clear();
2972}
2973
2974bool AudioFlinger::DuplicatingThread::threadLoop()
2975{
Eric Laurenta553c252009-07-17 12:17:14 -07002976 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002977 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002978 nsecs_t standbyTime = systemTime();
2979 size_t mixBufferSize = mFrameCount*mFrameSize;
2980 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002981 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002982 uint32_t activeSleepTime = activeSleepTimeUs();
2983 uint32_t idleSleepTime = idleSleepTimeUs();
2984 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002985 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002986
Eric Laurent6dbdc402011-07-22 09:04:31 -07002987 acquireWakeLock();
2988
Eric Laurenta553c252009-07-17 12:17:14 -07002989 while (!exitPending())
2990 {
2991 processConfigEvents();
2992
Eric Laurent059b4be2009-11-09 23:32:22 -08002993 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002994 { // scope for the mLock
2995
2996 Mutex::Autolock _l(mLock);
2997
2998 if (checkForNewParameters_l()) {
2999 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003000 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08003001 activeSleepTime = activeSleepTimeUs();
3002 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07003003 }
3004
3005 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3006
3007 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3008 outputTracks.add(mOutputTracks[i]);
3009 }
3010
3011 // put audio hardware into standby after short delay
3012 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3013 mSuspended) {
3014 if (!mStandby) {
3015 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003016 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003017 }
3018 mStandby = true;
3019 mBytesWritten = 0;
3020 }
3021
3022 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3023 // we're about to wait, flush the binder command buffer
3024 IPCThreadState::self()->flushCommands();
3025 outputTracks.clear();
3026
3027 if (exitPending()) break;
3028
Eric Laurent6dbdc402011-07-22 09:04:31 -07003029 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07003030 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
3031 mWaitWorkCV.wait(mLock);
3032 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003033 acquireWakeLock_l();
3034
Eric Laurent0b089652012-01-23 18:35:10 -08003035 mPrevMixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003036 if (mMasterMute == false) {
3037 char value[PROPERTY_VALUE_MAX];
3038 property_get("ro.audio.silent", value, "0");
3039 if (atoi(value)) {
3040 LOGD("Silence is golden");
3041 setMasterMute(true);
3042 }
3043 }
3044
3045 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003046 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003047 continue;
3048 }
3049 }
3050
Eric Laurent059b4be2009-11-09 23:32:22 -08003051 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003052
3053 // prevent any changes in effect chain list and in each effect chain
3054 // during mixing and effect process as the audio buffers could be deleted
3055 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003056 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003057 }
Eric Laurenta553c252009-07-17 12:17:14 -07003058
Eric Laurent059b4be2009-11-09 23:32:22 -08003059 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003060 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003061 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003062 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003063 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003064 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003065 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003066 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003067 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003068 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003069 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003070 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3071 sleepTime = activeSleepTime;
3072 } else {
3073 sleepTime = idleSleepTime;
3074 }
Eric Laurent62443f52009-10-05 20:29:18 -07003075 } else if (mBytesWritten != 0) {
3076 // flush remaining overflow buffers in output tracks
3077 for (size_t i = 0; i < outputTracks.size(); i++) {
3078 if (outputTracks[i]->isActive()) {
3079 sleepTime = 0;
3080 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003081 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003082 break;
3083 }
3084 }
Eric Laurenta553c252009-07-17 12:17:14 -07003085 }
3086 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003087
3088 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003089 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003090 }
3091 // sleepTime == 0 means we must write to audio hardware
3092 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003093 for (size_t i = 0; i < effectChains.size(); i ++) {
3094 effectChains[i]->process_l();
3095 }
3096 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003097 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003098
Eric Laurent62443f52009-10-05 20:29:18 -07003099 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003100 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003101 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003102 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003103 mStandby = false;
3104 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003105 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003106 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003107 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003108 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003109 }
3110
3111 // finally let go of all our tracks, without the lock held
3112 // since we can't guarantee the destructors won't acquire that
3113 // same lock.
3114 tracksToRemove.clear();
3115 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003116
3117 // Effect chains will be actually deleted here if they were removed from
3118 // mEffectChains list during mixing or effects processing
3119 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003120 }
3121
Eric Laurent6dbdc402011-07-22 09:04:31 -07003122 releaseWakeLock();
3123
Eric Laurenta553c252009-07-17 12:17:14 -07003124 return false;
3125}
3126
3127void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3128{
3129 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3130 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003131 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003132 mSampleRate,
3133 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003134 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003135 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003136 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003137 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003138 mOutputTracks.add(outputTrack);
3139 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003140 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003141 }
Eric Laurenta553c252009-07-17 12:17:14 -07003142}
3143
3144void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3145{
3146 Mutex::Autolock _l(mLock);
3147 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3148 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003149 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003150 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003151 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003152 return;
3153 }
3154 }
3155 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3156}
3157
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003158void AudioFlinger::DuplicatingThread::updateWaitTime()
3159{
3160 mWaitTimeMs = UINT_MAX;
3161 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3162 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3163 if (strong != NULL) {
3164 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3165 if (waitTimeMs < mWaitTimeMs) {
3166 mWaitTimeMs = waitTimeMs;
3167 }
3168 }
3169 }
3170}
3171
3172
3173bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3174{
3175 for (size_t i = 0; i < outputTracks.size(); i++) {
3176 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3177 if (thread == 0) {
3178 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3179 return false;
3180 }
3181 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3182 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3183 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3184 return false;
3185 }
3186 }
3187 return true;
3188}
3189
3190uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3191{
3192 return (mWaitTimeMs * 1000) / 2;
3193}
3194
Eric Laurenta553c252009-07-17 12:17:14 -07003195// ----------------------------------------------------------------------------
3196
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003197// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003198AudioFlinger::ThreadBase::TrackBase::TrackBase(
3199 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003200 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003201 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003202 uint32_t format,
3203 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003204 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003206 const sp<IMemory>& sharedBuffer,
3207 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003208 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003209 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003210 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003211 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003212 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003213 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003214 mClientTid(-1),
3215 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003216 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3217 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003218{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003219 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3220
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003221 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003222 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003223 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003224 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3225 if (sharedBuffer == 0) {
3226 size += bufferSize;
3227 }
3228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 if (client != NULL) {
3230 mCblkMemory = client->heap()->allocate(size);
3231 if (mCblkMemory != 0) {
3232 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3233 if (mCblk) { // construct the shared structure in-place.
3234 new(mCblk) audio_track_cblk_t();
3235 // clear all buffers
3236 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003237 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003238 mChannelCount = channelCount;
3239 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 if (sharedBuffer == 0) {
3241 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3242 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3243 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003244 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003245 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 } else {
3247 mBuffer = sharedBuffer->pointer();
3248 }
3249 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 } else {
3252 LOGE("not enough memory for AudioTrack size=%u", size);
3253 client->heap()->dump("AudioTrack");
3254 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 } else {
3257 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3258 if (mCblk) { // construct the shared structure in-place.
3259 new(mCblk) audio_track_cblk_t();
3260 // clear all buffers
3261 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003262 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003263 mChannelCount = channelCount;
3264 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3266 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3267 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003268 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003269 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3271 }
3272 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003273}
3274
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003275AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003276{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003278 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3279 if (mClient == NULL) {
3280 delete mCblk;
3281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003283 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003284 if (mClient != NULL) {
3285 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3286 mClient.clear();
3287 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003288}
3289
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003290void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003291{
3292 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003293 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003294 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003295 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003296}
3297
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003298bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003299 bool result;
3300 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003301
3302 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003303 if (!result) {
3304 LOGV("stepServer failed acquiring cblk mutex");
3305 mFlags |= STEPSERVER_FAILED;
3306 }
3307 return result;
3308}
3309
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003310void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003311 audio_track_cblk_t* cblk = this->cblk();
3312
3313 cblk->user = 0;
3314 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003315 cblk->userBase = 0;
3316 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003318 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003319}
3320
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003321sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003322{
3323 return mCblkMemory;
3324}
3325
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003326int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003327 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003328}
3329
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003330int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003331 return (const int)mChannelCount;
3332}
3333
3334uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3335 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003336}
3337
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003338void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003339 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003340 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3341 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003342
3343 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003344 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3345 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003346 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 -07003347 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003348 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003349 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003350 return 0;
3351 }
3352
3353 return bufferStart;
3354}
3355
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003356// ----------------------------------------------------------------------------
3357
Eric Laurenta553c252009-07-17 12:17:14 -07003358// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3359AudioFlinger::PlaybackThread::Track::Track(
3360 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003361 const sp<Client>& client,
3362 int streamType,
3363 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003364 uint32_t format,
3365 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003366 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003367 const sp<IMemory>& sharedBuffer,
3368 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003369 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003370 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3371 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003372{
Eric Laurent8a77a992009-09-09 05:16:08 -07003373 if (mCblk != NULL) {
3374 sp<ThreadBase> baseThread = thread.promote();
3375 if (baseThread != 0) {
3376 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3377 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003378 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003379 }
3380 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3381 if (mName < 0) {
3382 LOGE("no more track names available");
3383 }
3384 mVolume[0] = 1.0f;
3385 mVolume[1] = 1.0f;
3386 mStreamType = streamType;
3387 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3388 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003389 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003390 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003391}
3392
Eric Laurenta553c252009-07-17 12:17:14 -07003393AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003394{
Eric Laurenta553c252009-07-17 12:17:14 -07003395 LOGV("PlaybackThread::Track destructor");
3396 sp<ThreadBase> thread = mThread.promote();
3397 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003398 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003399 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003400 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003401}
3402
Eric Laurenta553c252009-07-17 12:17:14 -07003403void AudioFlinger::PlaybackThread::Track::destroy()
3404{
3405 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3406 // by removing it from mTracks vector, so there is a risk that this Tracks's
3407 // desctructor is called. As the destructor needs to lock mLock,
3408 // we must acquire a strong reference on this Track before locking mLock
3409 // here so that the destructor is called only when exiting this function.
3410 // On the other hand, as long as Track::destroy() is only called by
3411 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3412 // this Track with its member mTrack.
3413 sp<Track> keep(this);
3414 { // scope for mLock
3415 sp<ThreadBase> thread = mThread.promote();
3416 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003417 if (!isOutputTrack()) {
3418 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003419 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003420 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003421 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003422
3423 // to track the speaker usage
3424 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003425 }
3426 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003427 }
Eric Laurenta553c252009-07-17 12:17:14 -07003428 Mutex::Autolock _l(thread->mLock);
3429 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3430 playbackThread->destroyTrack_l(this);
3431 }
3432 }
3433}
3434
3435void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003436{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003437 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 -07003438 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003440 mStreamType,
3441 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003442 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003443 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003444 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003445 mState,
3446 mMute,
3447 mFillingUpStatus,
3448 mCblk->sampleRate,
3449 mCblk->volume[0],
3450 mCblk->volume[1],
3451 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003452 mCblk->user,
3453 (int)mMainBuffer,
3454 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003455}
3456
Eric Laurenta553c252009-07-17 12:17:14 -07003457status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003458{
3459 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003460 uint32_t framesReady;
3461 uint32_t framesReq = buffer->frameCount;
3462
3463 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003464 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3465 if (!step()) goto getNextBuffer_exit;
3466 LOGV("stepServer recovered");
3467 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3468 }
3469
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003470 framesReady = cblk->framesReady();
3471
3472 if (LIKELY(framesReady)) {
3473 uint32_t s = cblk->server;
3474 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3475
3476 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3477 if (framesReq > framesReady) {
3478 framesReq = framesReady;
3479 }
3480 if (s + framesReq > bufferEnd) {
3481 framesReq = bufferEnd - s;
3482 }
3483
3484 buffer->raw = getBuffer(s, framesReq);
3485 if (buffer->raw == 0) goto getNextBuffer_exit;
3486
3487 buffer->frameCount = framesReq;
3488 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003489 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003490
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003491getNextBuffer_exit:
3492 buffer->raw = 0;
3493 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003494 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003495 return NOT_ENOUGH_DATA;
3496}
3497
Eric Laurenta553c252009-07-17 12:17:14 -07003498bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003499 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003500
3501 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003502 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003503 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003504 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003505 return true;
3506 }
3507 return false;
3508}
3509
Eric Laurenta553c252009-07-17 12:17:14 -07003510status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003511{
Eric Laurent49f02be2009-11-19 09:00:56 -08003512 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003513 LOGV("start(%d), calling thread %d session %d",
3514 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003515 sp<ThreadBase> thread = mThread.promote();
3516 if (thread != 0) {
3517 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003518 int state = mState;
3519 // here the track could be either new, or restarted
3520 // in both cases "unstop" the track
3521 if (mState == PAUSED) {
3522 mState = TrackBase::RESUMING;
3523 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3524 } else {
3525 mState = TrackBase::ACTIVE;
3526 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3527 }
3528
3529 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3530 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003531 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003532 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003533 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003534 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003535
3536 // to track the speaker usage
3537 if (status == NO_ERROR) {
3538 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3539 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003540 }
3541 if (status == NO_ERROR) {
3542 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3543 playbackThread->addTrack_l(this);
3544 } else {
3545 mState = state;
3546 }
3547 } else {
3548 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003549 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003550 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003551}
3552
Eric Laurenta553c252009-07-17 12:17:14 -07003553void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003554{
Eric Laurenta553c252009-07-17 12:17:14 -07003555 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3556 sp<ThreadBase> thread = mThread.promote();
3557 if (thread != 0) {
3558 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003559 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003560 if (mState > STOPPED) {
3561 mState = STOPPED;
3562 // If the track is not active (PAUSED and buffers full), flush buffers
3563 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3564 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3565 reset();
3566 }
Eric Laurent62443f52009-10-05 20:29:18 -07003567 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003568 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003569 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3570 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003571 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003572 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003573 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003574 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003575
3576 // to track the speaker usage
3577 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003578 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003579 }
3580}
3581
Eric Laurenta553c252009-07-17 12:17:14 -07003582void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003583{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003585 sp<ThreadBase> thread = mThread.promote();
3586 if (thread != 0) {
3587 Mutex::Autolock _l(thread->mLock);
3588 if (mState == ACTIVE || mState == RESUMING) {
3589 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003590 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003591 if (!isOutputTrack()) {
3592 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003593 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003594 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003595 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003596 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003597
3598 // to track the speaker usage
3599 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003600 }
Eric Laurenta553c252009-07-17 12:17:14 -07003601 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003602 }
3603}
3604
Eric Laurenta553c252009-07-17 12:17:14 -07003605void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003606{
3607 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003608 sp<ThreadBase> thread = mThread.promote();
3609 if (thread != 0) {
3610 Mutex::Autolock _l(thread->mLock);
3611 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3612 return;
3613 }
3614 // No point remaining in PAUSED state after a flush => go to
3615 // STOPPED state
3616 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003617
Eric Laurentae29b762011-03-28 18:37:07 -07003618 // do not reset the track if it is still in the process of being stopped or paused.
3619 // this will be done by prepareTracks_l() when the track is stopped.
3620 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3621 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3622 reset();
3623 }
Eric Laurenta553c252009-07-17 12:17:14 -07003624 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003625}
3626
Eric Laurenta553c252009-07-17 12:17:14 -07003627void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003628{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003629 // Do not reset twice to avoid discarding data written just after a flush and before
3630 // the audioflinger thread detects the track is stopped.
3631 if (!mResetDone) {
3632 TrackBase::reset();
3633 // Force underrun condition to avoid false underrun callback until first data is
3634 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003635 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3636 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003637 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003638 mResetDone = true;
3639 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003640}
3641
Eric Laurenta553c252009-07-17 12:17:14 -07003642void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003643{
3644 mMute = muted;
3645}
3646
Eric Laurenta553c252009-07-17 12:17:14 -07003647void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003648{
3649 mVolume[0] = left;
3650 mVolume[1] = right;
3651}
3652
Eric Laurent65b65452010-06-01 23:49:17 -07003653status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3654{
3655 status_t status = DEAD_OBJECT;
3656 sp<ThreadBase> thread = mThread.promote();
3657 if (thread != 0) {
3658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3659 status = playbackThread->attachAuxEffect(this, EffectId);
3660 }
3661 return status;
3662}
3663
3664void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3665{
3666 mAuxEffectId = EffectId;
3667 mAuxBuffer = buffer;
3668}
3669
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003670// ----------------------------------------------------------------------------
3671
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003672// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003673AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3674 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003677 uint32_t format,
3678 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003680 uint32_t flags,
3681 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003682 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003683 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003684 mOverflow(false)
3685{
Eric Laurent8a77a992009-09-09 05:16:08 -07003686 if (mCblk != NULL) {
3687 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003688 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003689 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003690 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003691 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003692 } else {
3693 mCblk->frameSize = sizeof(int8_t);
3694 }
3695 }
Eric Laurenta553c252009-07-17 12:17:14 -07003696}
3697
3698AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699{
Eric Laurent49f02be2009-11-19 09:00:56 -08003700 sp<ThreadBase> thread = mThread.promote();
3701 if (thread != 0) {
3702 AudioSystem::releaseInput(thread->id());
3703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704}
3705
Eric Laurenta553c252009-07-17 12:17:14 -07003706status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707{
3708 audio_track_cblk_t* cblk = this->cblk();
3709 uint32_t framesAvail;
3710 uint32_t framesReq = buffer->frameCount;
3711
3712 // Check if last stepServer failed, try to step now
3713 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3714 if (!step()) goto getNextBuffer_exit;
3715 LOGV("stepServer recovered");
3716 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3717 }
3718
3719 framesAvail = cblk->framesAvailable_l();
3720
3721 if (LIKELY(framesAvail)) {
3722 uint32_t s = cblk->server;
3723 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3724
3725 if (framesReq > framesAvail) {
3726 framesReq = framesAvail;
3727 }
3728 if (s + framesReq > bufferEnd) {
3729 framesReq = bufferEnd - s;
3730 }
3731
3732 buffer->raw = getBuffer(s, framesReq);
3733 if (buffer->raw == 0) goto getNextBuffer_exit;
3734
3735 buffer->frameCount = framesReq;
3736 return NO_ERROR;
3737 }
3738
3739getNextBuffer_exit:
3740 buffer->raw = 0;
3741 buffer->frameCount = 0;
3742 return NOT_ENOUGH_DATA;
3743}
3744
Eric Laurenta553c252009-07-17 12:17:14 -07003745status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746{
Eric Laurenta553c252009-07-17 12:17:14 -07003747 sp<ThreadBase> thread = mThread.promote();
3748 if (thread != 0) {
3749 RecordThread *recordThread = (RecordThread *)thread.get();
3750 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003751 } else {
3752 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754}
3755
Eric Laurenta553c252009-07-17 12:17:14 -07003756void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757{
Eric Laurenta553c252009-07-17 12:17:14 -07003758 sp<ThreadBase> thread = mThread.promote();
3759 if (thread != 0) {
3760 RecordThread *recordThread = (RecordThread *)thread.get();
3761 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003762 TrackBase::reset();
3763 // Force overerrun condition to avoid false overrun callback until first data is
3764 // read from buffer
3765 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767}
3768
Eric Laurent3fdb1262009-11-07 00:01:32 -08003769void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3770{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003771 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003772 (mClient == NULL) ? getpid() : mClient->pid(),
3773 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003774 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003775 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003776 mFrameCount,
3777 mState,
3778 mCblk->sampleRate,
3779 mCblk->server,
3780 mCblk->user);
3781}
3782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783
3784// ----------------------------------------------------------------------------
3785
Eric Laurenta553c252009-07-17 12:17:14 -07003786AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3787 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003788 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003790 uint32_t format,
3791 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003793 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003794 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795{
Eric Laurenta553c252009-07-17 12:17:14 -07003796
3797 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003798 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003799 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003800 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3801 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3802 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003803 playbackThread->mTracks.add(this);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003804 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3805 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3806 mCblk, mBuffer, mCblk->buffers,
3807 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003808 } else {
3809 LOGW("Error creating output track on thread %p", playbackThread);
3810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811}
3812
Eric Laurenta553c252009-07-17 12:17:14 -07003813AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814{
Eric Laurent6c30a712009-08-10 23:22:32 -07003815 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816}
3817
Eric Laurenta553c252009-07-17 12:17:14 -07003818status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819{
3820 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003821 if (status != NO_ERROR) {
3822 return status;
3823 }
3824
3825 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 mRetryCount = 127;
3827 return status;
3828}
3829
Eric Laurenta553c252009-07-17 12:17:14 -07003830void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831{
3832 Track::stop();
3833 clearBufferQueue();
3834 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003835 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836}
3837
Eric Laurenta553c252009-07-17 12:17:14 -07003838bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839{
3840 Buffer *pInBuffer;
3841 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003842 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003843 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 inBuffer.frameCount = frames;
3845 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003846
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003847 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003848
Eric Laurent62443f52009-10-05 20:29:18 -07003849 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003850 start();
3851 sp<ThreadBase> thread = mThread.promote();
3852 if (thread != 0) {
3853 MixerThread *mixerThread = (MixerThread *)thread.get();
3854 if (mCblk->frameCount > frames){
3855 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3856 uint32_t startFrames = (mCblk->frameCount - frames);
3857 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003858 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003859 pInBuffer->frameCount = startFrames;
3860 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003861 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003862 mBufferQueue.add(pInBuffer);
3863 } else {
3864 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
Eric Laurenta553c252009-07-17 12:17:14 -07003867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 }
3869
Eric Laurenta553c252009-07-17 12:17:14 -07003870 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 // First write pending buffers, then new data
3872 if (mBufferQueue.size()) {
3873 pInBuffer = mBufferQueue.itemAt(0);
3874 } else {
3875 pInBuffer = &inBuffer;
3876 }
Eric Laurenta553c252009-07-17 12:17:14 -07003877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 if (pInBuffer->frameCount == 0) {
3879 break;
3880 }
Eric Laurenta553c252009-07-17 12:17:14 -07003881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if (mOutBuffer.frameCount == 0) {
3883 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003884 nsecs_t startTime = systemTime();
3885 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003886 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003887 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 break;
3889 }
Eric Laurenta553c252009-07-17 12:17:14 -07003890 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003891 if (waitTimeLeftMs >= waitTimeMs) {
3892 waitTimeLeftMs -= waitTimeMs;
3893 } else {
3894 waitTimeLeftMs = 0;
3895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 }
Eric Laurenta553c252009-07-17 12:17:14 -07003897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003899 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 mCblk->stepUser(outFrames);
3901 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003902 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003904 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 if (pInBuffer->frameCount == 0) {
3907 if (mBufferQueue.size()) {
3908 mBufferQueue.removeAt(0);
3909 delete [] pInBuffer->mBuffer;
3910 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003911 LOGV("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 -08003912 } else {
3913 break;
3914 }
3915 }
3916 }
Eric Laurenta553c252009-07-17 12:17:14 -07003917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 // If we could not write all frames, allocate a buffer and queue it for next time.
3919 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003920 sp<ThreadBase> thread = mThread.promote();
3921 if (thread != 0 && !thread->standby()) {
3922 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3923 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003924 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003925 pInBuffer->frameCount = inBuffer.frameCount;
3926 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003927 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003928 mBufferQueue.add(pInBuffer);
3929 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3930 } else {
3931 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
3934 }
Eric Laurenta553c252009-07-17 12:17:14 -07003935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003937 // 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 -08003938 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003939 if (frames == 0 && mBufferQueue.size() == 0) {
3940 if (mCblk->user < mCblk->frameCount) {
3941 frames = mCblk->frameCount - mCblk->user;
3942 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003943 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003944 pInBuffer->frameCount = frames;
3945 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003946 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003947 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003948 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003949 stop();
3950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 }
3952
Eric Laurenta553c252009-07-17 12:17:14 -07003953 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954}
3955
Eric Laurenta553c252009-07-17 12:17:14 -07003956status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957{
3958 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 status_t result;
3960 audio_track_cblk_t* cblk = mCblk;
3961 uint32_t framesReq = buffer->frameCount;
3962
Eric Laurenta553c252009-07-17 12:17:14 -07003963// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 uint32_t framesAvail = cblk->framesAvailable();
3967
Eric Laurenta553c252009-07-17 12:17:14 -07003968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003970 Mutex::Autolock _l(cblk->lock);
3971 goto start_loop_here;
3972 while (framesAvail == 0) {
3973 active = mActive;
3974 if (UNLIKELY(!active)) {
3975 LOGV("Not active and NO_MORE_BUFFERS");
3976 return AudioTrack::NO_MORE_BUFFERS;
3977 }
3978 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3979 if (result != NO_ERROR) {
3980 return AudioTrack::NO_MORE_BUFFERS;
3981 }
3982 // read the server count again
3983 start_loop_here:
3984 framesAvail = cblk->framesAvailable_l();
3985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 }
3987
Eric Laurenta553c252009-07-17 12:17:14 -07003988// if (framesAvail < framesReq) {
3989// return AudioTrack::NO_MORE_BUFFERS;
3990// }
3991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 if (framesReq > framesAvail) {
3993 framesReq = framesAvail;
3994 }
3995
3996 uint32_t u = cblk->user;
3997 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3998
3999 if (u + framesReq > bufferEnd) {
4000 framesReq = bufferEnd - u;
4001 }
4002
4003 buffer->frameCount = framesReq;
4004 buffer->raw = (void *)cblk->buffer(u);
4005 return NO_ERROR;
4006}
4007
4008
Eric Laurenta553c252009-07-17 12:17:14 -07004009void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010{
4011 size_t size = mBufferQueue.size();
4012 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 for (size_t i = 0; i < size; i++) {
4015 pBuffer = mBufferQueue.itemAt(i);
4016 delete [] pBuffer->mBuffer;
4017 delete pBuffer;
4018 }
4019 mBufferQueue.clear();
4020}
4021
4022// ----------------------------------------------------------------------------
4023
4024AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4025 : RefBase(),
4026 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004027 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 mPid(pid)
4029{
4030 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4031}
4032
Eric Laurentb9481d82009-09-17 05:12:56 -07004033// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034AudioFlinger::Client::~Client()
4035{
Eric Laurentb9481d82009-09-17 05:12:56 -07004036 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037}
4038
4039const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4040{
4041 return mMemoryDealer;
4042}
4043
4044// ----------------------------------------------------------------------------
4045
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004046AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4047 const sp<IAudioFlingerClient>& client,
4048 pid_t pid)
4049 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4050{
4051}
4052
4053AudioFlinger::NotificationClient::~NotificationClient()
4054{
4055 mClient.clear();
4056}
4057
4058void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4059{
4060 sp<NotificationClient> keep(this);
4061 {
4062 mAudioFlinger->removeNotificationClient(mPid);
4063 }
4064}
4065
4066// ----------------------------------------------------------------------------
4067
Eric Laurenta553c252009-07-17 12:17:14 -07004068AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004069 : BnAudioTrack(),
4070 mTrack(track)
4071{
4072}
4073
4074AudioFlinger::TrackHandle::~TrackHandle() {
4075 // just stop the track on deletion, associated resources
4076 // will be freed from the main thread once all pending buffers have
4077 // been played. Unless it's not in the active track list, in which
4078 // case we free everything now...
4079 mTrack->destroy();
4080}
4081
4082status_t AudioFlinger::TrackHandle::start() {
4083 return mTrack->start();
4084}
4085
4086void AudioFlinger::TrackHandle::stop() {
4087 mTrack->stop();
4088}
4089
4090void AudioFlinger::TrackHandle::flush() {
4091 mTrack->flush();
4092}
4093
4094void AudioFlinger::TrackHandle::mute(bool e) {
4095 mTrack->mute(e);
4096}
4097
4098void AudioFlinger::TrackHandle::pause() {
4099 mTrack->pause();
4100}
4101
4102void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4103 mTrack->setVolume(left, right);
4104}
4105
4106sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4107 return mTrack->getCblk();
4108}
4109
Eric Laurent65b65452010-06-01 23:49:17 -07004110status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4111{
4112 return mTrack->attachAuxEffect(EffectId);
4113}
4114
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004115status_t AudioFlinger::TrackHandle::onTransact(
4116 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4117{
4118 return BnAudioTrack::onTransact(code, data, reply, flags);
4119}
4120
4121// ----------------------------------------------------------------------------
4122
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004123sp<IAudioRecord> AudioFlinger::openRecord(
4124 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004125 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004126 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004127 uint32_t format,
4128 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004129 int frameCount,
4130 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004131 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004132 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004133{
Eric Laurenta553c252009-07-17 12:17:14 -07004134 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004135 sp<RecordHandle> recordHandle;
4136 sp<Client> client;
4137 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004138 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004139 RecordThread *thread;
4140 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004141 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004142
4143 // check calling permissions
4144 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004145 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004146 goto Exit;
4147 }
4148
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004149 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004150 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004151 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004152 thread = checkRecordThread_l(input);
4153 if (thread == NULL) {
4154 lStatus = BAD_VALUE;
4155 goto Exit;
4156 }
4157
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004158 wclient = mClients.valueFor(pid);
4159 if (wclient != NULL) {
4160 client = wclient.promote();
4161 } else {
4162 client = new Client(this, pid);
4163 mClients.add(pid, client);
4164 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004165
Eric Laurent65b65452010-06-01 23:49:17 -07004166 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004167 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004168 lSessionId = *sessionId;
4169 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004170 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004171 if (sessionId != NULL) {
4172 *sessionId = lSessionId;
4173 }
4174 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004175 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004176 recordTrack = thread->createRecordTrack_l(client,
4177 sampleRate,
4178 format,
4179 channelMask,
4180 frameCount,
4181 flags,
4182 lSessionId,
4183 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004184 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004185 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004186 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4187 // destructor is called by the TrackBase destructor with mLock held
4188 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 goto Exit;
4191 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004192
4193 // return to handle to client
4194 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004195 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004196
4197Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004198 if (status) {
4199 *status = lStatus;
4200 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004201 return recordHandle;
4202}
4203
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004204// ----------------------------------------------------------------------------
4205
Eric Laurenta553c252009-07-17 12:17:14 -07004206AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004207 : BnAudioRecord(),
4208 mRecordTrack(recordTrack)
4209{
4210}
4211
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004212AudioFlinger::RecordHandle::~RecordHandle() {
4213 stop();
4214}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004215
4216status_t AudioFlinger::RecordHandle::start() {
4217 LOGV("RecordHandle::start()");
4218 return mRecordTrack->start();
4219}
4220
4221void AudioFlinger::RecordHandle::stop() {
4222 LOGV("RecordHandle::stop()");
4223 mRecordTrack->stop();
4224}
4225
4226sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4227 return mRecordTrack->getCblk();
4228}
4229
4230status_t AudioFlinger::RecordHandle::onTransact(
4231 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4232{
4233 return BnAudioRecord::onTransact(code, data, reply, flags);
4234}
4235
4236// ----------------------------------------------------------------------------
4237
Eric Laurent464d5b32011-06-17 21:29:58 -07004238AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4239 AudioStreamIn *input,
4240 uint32_t sampleRate,
4241 uint32_t channels,
4242 int id,
4243 uint32_t device) :
4244 ThreadBase(audioFlinger, id, device),
4245 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004246{
Eric Laurent464d5b32011-06-17 21:29:58 -07004247 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004248
4249 snprintf(mName, kNameLength, "AudioIn_%d", id);
4250
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004251 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004252 mReqSampleRate = sampleRate;
4253 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004254}
4255
Eric Laurenta553c252009-07-17 12:17:14 -07004256
4257AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004258{
Eric Laurenta553c252009-07-17 12:17:14 -07004259 delete[] mRsmpInBuffer;
4260 if (mResampler != 0) {
4261 delete mResampler;
4262 delete[] mRsmpOutBuffer;
4263 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004264}
4265
Eric Laurenta553c252009-07-17 12:17:14 -07004266void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004267{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004268 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004269}
Eric Laurent49f02be2009-11-19 09:00:56 -08004270
Eric Laurent828b9772011-08-07 16:32:26 -07004271status_t AudioFlinger::RecordThread::readyToRun()
4272{
4273 status_t status = initCheck();
4274 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4275 return status;
4276}
4277
Eric Laurenta553c252009-07-17 12:17:14 -07004278bool AudioFlinger::RecordThread::threadLoop()
4279{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004280 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004281 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004282 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004283
Eric Laurent4712baa2010-09-30 16:12:31 -07004284 nsecs_t lastWarning = 0;
4285
Eric Laurent6dbdc402011-07-22 09:04:31 -07004286 acquireWakeLock();
4287
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004288 // start recording
4289 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004290
Eric Laurenta553c252009-07-17 12:17:14 -07004291 processConfigEvents();
4292
4293 { // scope for mLock
4294 Mutex::Autolock _l(mLock);
4295 checkForNewParameters_l();
4296 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4297 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004298 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004299 mStandby = true;
4300 }
4301
4302 if (exitPending()) break;
4303
Eric Laurent6dbdc402011-07-22 09:04:31 -07004304 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004305 LOGV("RecordThread: loop stopping");
4306 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004307 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004308 LOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004309 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004310 continue;
4311 }
4312 if (mActiveTrack != 0) {
4313 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004314 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004315 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004316 mStandby = true;
4317 }
Eric Laurenta553c252009-07-17 12:17:14 -07004318 mActiveTrack.clear();
4319 mStartStopCond.broadcast();
4320 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004321 if (mReqChannelCount != mActiveTrack->channelCount()) {
4322 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004323 mStartStopCond.broadcast();
4324 } else if (mBytesRead != 0) {
4325 // record start succeeds only if first read from audio input
4326 // succeeds
4327 if (mBytesRead > 0) {
4328 mActiveTrack->mState = TrackBase::ACTIVE;
4329 } else {
4330 mActiveTrack.clear();
4331 }
4332 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004333 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004334 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004335 }
Eric Laurenta553c252009-07-17 12:17:14 -07004336 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004337 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004338 }
4339
4340 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004341 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4342 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004343 unlockEffectChains(effectChains);
4344 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004345 continue;
4346 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004347 for (size_t i = 0; i < effectChains.size(); i ++) {
4348 effectChains[i]->process_l();
4349 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004350
Eric Laurenta553c252009-07-17 12:17:14 -07004351 buffer.frameCount = mFrameCount;
4352 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4353 size_t framesOut = buffer.frameCount;
4354 if (mResampler == 0) {
4355 // no resampling
4356 while (framesOut) {
4357 size_t framesIn = mFrameCount - mRsmpInIndex;
4358 if (framesIn) {
4359 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4360 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4361 if (framesIn > framesOut)
4362 framesIn = framesOut;
4363 mRsmpInIndex += framesIn;
4364 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004365 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004366 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004367 memcpy(dst, src, framesIn * mFrameSize);
4368 } else {
4369 int16_t *src16 = (int16_t *)src;
4370 int16_t *dst16 = (int16_t *)dst;
4371 if (mChannelCount == 1) {
4372 while (framesIn--) {
4373 *dst16++ = *src16;
4374 *dst16++ = *src16++;
4375 }
4376 } else {
4377 while (framesIn--) {
4378 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4379 src16 += 2;
4380 }
4381 }
4382 }
4383 }
4384 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004385 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004386 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004387 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004388 framesOut = 0;
4389 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004390 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004391 mRsmpInIndex = 0;
4392 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004393 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004394 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004395 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004396 // Force input into standby so that it tries to
4397 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004398 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004399 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004400 }
Eric Laurenta553c252009-07-17 12:17:14 -07004401 mRsmpInIndex = mFrameCount;
4402 framesOut = 0;
4403 buffer.frameCount = 0;
4404 }
4405 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004406 }
4407 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004408 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004409
Eric Laurenta553c252009-07-17 12:17:14 -07004410 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4411 // alter output frame count as if we were expecting stereo samples
4412 if (mChannelCount == 1 && mReqChannelCount == 1) {
4413 framesOut >>= 1;
4414 }
4415 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4416 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4417 // are 32 bit aligned which should be always true.
4418 if (mChannelCount == 2 && mReqChannelCount == 1) {
4419 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4420 // the resampler always outputs stereo samples: do post stereo to mono conversion
4421 int16_t *src = (int16_t *)mRsmpOutBuffer;
4422 int16_t *dst = buffer.i16;
4423 while (framesOut--) {
4424 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4425 src += 2;
4426 }
4427 } else {
4428 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4429 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004430
Eric Laurenta553c252009-07-17 12:17:14 -07004431 }
4432 mActiveTrack->releaseBuffer(&buffer);
4433 mActiveTrack->overflow();
4434 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004435 // client isn't retrieving buffers fast enough
4436 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004437 if (!mActiveTrack->setOverflow()) {
4438 nsecs_t now = systemTime();
4439 if ((now - lastWarning) > kWarningThrottle) {
4440 LOGW("RecordThread: buffer overflow");
4441 lastWarning = now;
4442 }
4443 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004444 // Release the processor for a while before asking for a new buffer.
4445 // This will give the application more chance to read from the buffer and
4446 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004447 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004448 }
4449 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004450 // enable changes in effect chain
4451 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004452 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004453 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004454
Eric Laurenta553c252009-07-17 12:17:14 -07004455 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004456 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004457 }
Eric Laurenta553c252009-07-17 12:17:14 -07004458 mActiveTrack.clear();
4459
Eric Laurent49f02be2009-11-19 09:00:56 -08004460 mStartStopCond.broadcast();
4461
Eric Laurent6dbdc402011-07-22 09:04:31 -07004462 releaseWakeLock();
4463
Eric Laurenta553c252009-07-17 12:17:14 -07004464 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004465 return false;
4466}
4467
Eric Laurent464d5b32011-06-17 21:29:58 -07004468
4469sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4470 const sp<AudioFlinger::Client>& client,
4471 uint32_t sampleRate,
4472 int format,
4473 int channelMask,
4474 int frameCount,
4475 uint32_t flags,
4476 int sessionId,
4477 status_t *status)
4478{
4479 sp<RecordTrack> track;
4480 status_t lStatus;
4481
4482 lStatus = initCheck();
4483 if (lStatus != NO_ERROR) {
4484 LOGE("Audio driver not initialized.");
4485 goto Exit;
4486 }
4487
4488 { // scope for mLock
4489 Mutex::Autolock _l(mLock);
4490
4491 track = new RecordTrack(this, client, sampleRate,
4492 format, channelMask, frameCount, flags, sessionId);
4493
4494 if (track->getCblk() == NULL) {
4495 lStatus = NO_MEMORY;
4496 goto Exit;
4497 }
4498
4499 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004500 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4501 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004502 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004503 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4504 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004505 }
4506 lStatus = NO_ERROR;
4507
4508Exit:
4509 if (status) {
4510 *status = lStatus;
4511 }
4512 return track;
4513}
4514
Eric Laurenta553c252009-07-17 12:17:14 -07004515status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004516{
Eric Laurenta553c252009-07-17 12:17:14 -07004517 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004518 sp <ThreadBase> strongMe = this;
4519 status_t status = NO_ERROR;
4520 {
4521 AutoMutex lock(&mLock);
4522 if (mActiveTrack != 0) {
4523 if (recordTrack != mActiveTrack.get()) {
4524 status = -EBUSY;
4525 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004526 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004527 }
4528 return status;
4529 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004530
Eric Laurent49f02be2009-11-19 09:00:56 -08004531 recordTrack->mState = TrackBase::IDLE;
4532 mActiveTrack = recordTrack;
4533 mLock.unlock();
4534 status_t status = AudioSystem::startInput(mId);
4535 mLock.lock();
4536 if (status != NO_ERROR) {
4537 mActiveTrack.clear();
4538 return status;
4539 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004540 mRsmpInIndex = mFrameCount;
4541 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004542 if (mResampler != NULL) {
4543 mResampler->reset();
4544 }
4545 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004546 // signal thread to start
4547 LOGV("Signal record thread");
4548 mWaitWorkCV.signal();
4549 // do not wait for mStartStopCond if exiting
4550 if (mExiting) {
4551 mActiveTrack.clear();
4552 status = INVALID_OPERATION;
4553 goto startError;
4554 }
4555 mStartStopCond.wait(mLock);
4556 if (mActiveTrack == 0) {
4557 LOGV("Record failed to start");
4558 status = BAD_VALUE;
4559 goto startError;
4560 }
Eric Laurenta553c252009-07-17 12:17:14 -07004561 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004562 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004563 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004564startError:
4565 AudioSystem::stopInput(mId);
4566 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004567}
4568
Eric Laurenta553c252009-07-17 12:17:14 -07004569void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4570 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004571 sp <ThreadBase> strongMe = this;
4572 {
4573 AutoMutex lock(&mLock);
4574 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4575 mActiveTrack->mState = TrackBase::PAUSING;
4576 // do not wait for mStartStopCond if exiting
4577 if (mExiting) {
4578 return;
4579 }
4580 mStartStopCond.wait(mLock);
4581 // if we have been restarted, recordTrack == mActiveTrack.get() here
4582 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4583 mLock.unlock();
4584 AudioSystem::stopInput(mId);
4585 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004586 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004587 }
4588 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004589 }
4590}
4591
Eric Laurenta553c252009-07-17 12:17:14 -07004592status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593{
4594 const size_t SIZE = 256;
4595 char buffer[SIZE];
4596 String8 result;
4597 pid_t pid = 0;
4598
Eric Laurent3fdb1262009-11-07 00:01:32 -08004599 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4600 result.append(buffer);
4601
4602 if (mActiveTrack != 0) {
4603 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004604 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004605 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004607
4608 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4609 result.append(buffer);
4610 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4611 result.append(buffer);
4612 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4613 result.append(buffer);
4614 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4615 result.append(buffer);
4616 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4617 result.append(buffer);
4618
4619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 } else {
4621 result.append("No record client\n");
4622 }
4623 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004624
4625 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004626 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 return NO_ERROR;
4629}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004630
Eric Laurenta553c252009-07-17 12:17:14 -07004631status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4632{
4633 size_t framesReq = buffer->frameCount;
4634 size_t framesReady = mFrameCount - mRsmpInIndex;
4635 int channelCount;
4636
4637 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004638 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004639 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004640 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004641 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004642 // Force input into standby so that it tries to
4643 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004644 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004645 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004646 }
Eric Laurenta553c252009-07-17 12:17:14 -07004647 buffer->raw = 0;
4648 buffer->frameCount = 0;
4649 return NOT_ENOUGH_DATA;
4650 }
4651 mRsmpInIndex = 0;
4652 framesReady = mFrameCount;
4653 }
4654
4655 if (framesReq > framesReady) {
4656 framesReq = framesReady;
4657 }
4658
4659 if (mChannelCount == 1 && mReqChannelCount == 2) {
4660 channelCount = 1;
4661 } else {
4662 channelCount = 2;
4663 }
4664 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4665 buffer->frameCount = framesReq;
4666 return NO_ERROR;
4667}
4668
4669void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4670{
4671 mRsmpInIndex += buffer->frameCount;
4672 buffer->frameCount = 0;
4673}
4674
4675bool AudioFlinger::RecordThread::checkForNewParameters_l()
4676{
4677 bool reconfig = false;
4678
Eric Laurent8fce46a2009-08-04 09:45:33 -07004679 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004680 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004681 String8 keyValuePair = mNewParameters[0];
4682 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004683 int value;
4684 int reqFormat = mFormat;
4685 int reqSamplingRate = mReqSampleRate;
4686 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004687
Eric Laurenta553c252009-07-17 12:17:14 -07004688 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4689 reqSamplingRate = value;
4690 reconfig = true;
4691 }
4692 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4693 reqFormat = value;
4694 reconfig = true;
4695 }
4696 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004697 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004698 reconfig = true;
4699 }
4700 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4701 // do not accept frame count changes if tracks are open as the track buffer
4702 // size depends on frame count and correct behavior would not be garantied
4703 // if frame count is changed after track creation
4704 if (mActiveTrack != 0) {
4705 status = INVALID_OPERATION;
4706 } else {
4707 reconfig = true;
4708 }
4709 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004710 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4711 // forward device change to effects that have requested to be
4712 // aware of attached audio device.
4713 for (size_t i = 0; i < mEffectChains.size(); i++) {
4714 mEffectChains[i]->setDevice_l(value);
4715 }
4716 // store input device and output device but do not forward output device to audio HAL.
4717 // Note that status is ignored by the caller for output device
4718 // (see AudioFlinger::setParameters()
4719 if (value & AUDIO_DEVICE_OUT_ALL) {
4720 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4721 status = BAD_VALUE;
4722 } else {
4723 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004724 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4725 if (mTrack != NULL) {
4726 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004727 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004728 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4729 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4730 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004731 }
4732 mDevice |= (uint32_t)value;
4733 }
Eric Laurenta553c252009-07-17 12:17:14 -07004734 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004735 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004736 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004737 mInput->stream->common.standby(&mInput->stream->common);
4738 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004739 }
4740 if (reconfig) {
4741 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004742 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004743 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004744 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4745 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004746 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004747 status = NO_ERROR;
4748 }
4749 if (status == NO_ERROR) {
4750 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004751 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004752 }
4753 }
4754 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004755
4756 mNewParameters.removeAt(0);
4757
Eric Laurenta553c252009-07-17 12:17:14 -07004758 mParamStatus = status;
4759 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004760 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4761 // already timed out waiting for the status and will never signal the condition.
4762 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07004763 }
4764 return reconfig;
4765}
4766
4767String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4768{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004769 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004770 String8 out_s8 = String8();
4771
4772 Mutex::Autolock _l(mLock);
4773 if (initCheck() != NO_ERROR) {
4774 return out_s8;
4775 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004776
Dima Zavin31f188892011-04-18 16:57:27 -07004777 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004778 out_s8 = String8(s);
4779 free(s);
4780 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004781}
4782
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004783void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004784 AudioSystem::OutputDescriptor desc;
4785 void *param2 = 0;
4786
4787 switch (event) {
4788 case AudioSystem::INPUT_OPENED:
4789 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004790 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004791 desc.samplingRate = mSampleRate;
4792 desc.format = mFormat;
4793 desc.frameCount = mFrameCount;
4794 desc.latency = 0;
4795 param2 = &desc;
4796 break;
4797
4798 case AudioSystem::INPUT_CLOSED:
4799 default:
4800 break;
4801 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004802 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004803}
4804
4805void AudioFlinger::RecordThread::readInputParameters()
4806{
4807 if (mRsmpInBuffer) delete mRsmpInBuffer;
4808 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4809 if (mResampler) delete mResampler;
4810 mResampler = 0;
4811
Dima Zavin31f188892011-04-18 16:57:27 -07004812 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004813 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4814 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004815 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4816 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4817 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004818 mFrameCount = mInputBytes / mFrameSize;
4819 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4820
4821 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4822 {
4823 int channelCount;
4824 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4825 // stereo to mono post process as the resampler always outputs stereo.
4826 if (mChannelCount == 1 && mReqChannelCount == 2) {
4827 channelCount = 1;
4828 } else {
4829 channelCount = 2;
4830 }
4831 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4832 mResampler->setSampleRate(mSampleRate);
4833 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4834 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4835
4836 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4837 if (mChannelCount == 1 && mReqChannelCount == 1) {
4838 mFrameCount >>= 1;
4839 }
4840
4841 }
4842 mRsmpInIndex = mFrameCount;
4843}
4844
Eric Laurent47d0a922010-02-26 02:47:27 -08004845unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4846{
Eric Laurent828b9772011-08-07 16:32:26 -07004847 Mutex::Autolock _l(mLock);
4848 if (initCheck() != NO_ERROR) {
4849 return 0;
4850 }
4851
Dima Zavin31f188892011-04-18 16:57:27 -07004852 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004853}
4854
Eric Laurent464d5b32011-06-17 21:29:58 -07004855uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4856{
4857 Mutex::Autolock _l(mLock);
4858 uint32_t result = 0;
4859 if (getEffectChain_l(sessionId) != 0) {
4860 result = EFFECT_SESSION;
4861 }
4862
4863 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4864 result |= TRACK_SESSION;
4865 }
4866
4867 return result;
4868}
4869
Eric Laurent6639b552011-08-01 09:52:20 -07004870AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4871{
4872 Mutex::Autolock _l(mLock);
4873 return mTrack;
4874}
4875
Eric Laurent828b9772011-08-07 16:32:26 -07004876AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4877{
4878 Mutex::Autolock _l(mLock);
4879 return mInput;
4880}
4881
4882AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4883{
4884 Mutex::Autolock _l(mLock);
4885 AudioStreamIn *input = mInput;
4886 mInput = NULL;
4887 return input;
4888}
4889
4890// this method must always be called either with ThreadBase mLock held or inside the thread loop
4891audio_stream_t* AudioFlinger::RecordThread::stream()
4892{
4893 if (mInput == NULL) {
4894 return NULL;
4895 }
4896 return &mInput->stream->common;
4897}
4898
4899
Eric Laurenta553c252009-07-17 12:17:14 -07004900// ----------------------------------------------------------------------------
4901
Eric Laurentddb78e72009-07-28 08:44:33 -07004902int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004903 uint32_t *pSamplingRate,
4904 uint32_t *pFormat,
4905 uint32_t *pChannels,
4906 uint32_t *pLatencyMs,
4907 uint32_t flags)
4908{
4909 status_t status;
4910 PlaybackThread *thread = NULL;
4911 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4912 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4913 uint32_t format = pFormat ? *pFormat : 0;
4914 uint32_t channels = pChannels ? *pChannels : 0;
4915 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004916 audio_stream_out_t *outStream;
4917 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004918
4919 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4920 pDevices ? *pDevices : 0,
4921 samplingRate,
4922 format,
4923 channels,
4924 flags);
4925
4926 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004927 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004928 }
Dima Zavin31f188892011-04-18 16:57:27 -07004929
Eric Laurenta553c252009-07-17 12:17:14 -07004930 Mutex::Autolock _l(mLock);
4931
Dima Zavin31f188892011-04-18 16:57:27 -07004932 outHwDev = findSuitableHwDev_l(*pDevices);
4933 if (outHwDev == NULL)
4934 return 0;
4935
4936 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4937 &channels, &samplingRate, &outStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004938 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004939 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004940 samplingRate,
4941 format,
4942 channels,
4943 status);
4944
4945 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004946 if (outStream != NULL) {
4947 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004948 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004949
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004950 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4951 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4952 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004953 thread = new DirectOutputThread(this, output, id, *pDevices);
4954 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004955 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004956 thread = new MixerThread(this, output, id, *pDevices);
4957 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004958 }
Eric Laurent65b65452010-06-01 23:49:17 -07004959 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004960
4961 if (pSamplingRate) *pSamplingRate = samplingRate;
4962 if (pFormat) *pFormat = format;
4963 if (pChannels) *pChannels = channels;
4964 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004965
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004966 // notify client processes of the new output creation
4967 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004968 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004969 }
4970
Eric Laurent9cc489a22009-12-05 05:20:01 -08004971 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004972}
4973
Eric Laurentddb78e72009-07-28 08:44:33 -07004974int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004975{
4976 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004977 MixerThread *thread1 = checkMixerThread_l(output1);
4978 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004979
Eric Laurentddb78e72009-07-28 08:44:33 -07004980 if (thread1 == NULL || thread2 == NULL) {
4981 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4982 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004983 }
4984
Eric Laurent464d5b32011-06-17 21:29:58 -07004985 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004986 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004987 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004988 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004989 // notify client processes of the new output creation
4990 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004991 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004992}
4993
Eric Laurentddb78e72009-07-28 08:44:33 -07004994status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004995{
Eric Laurent49018a52009-08-04 08:37:05 -07004996 // keep strong reference on the playback thread so that
4997 // it is not destroyed while exit() is executed
4998 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004999 {
5000 Mutex::Autolock _l(mLock);
5001 thread = checkPlaybackThread_l(output);
5002 if (thread == NULL) {
5003 return BAD_VALUE;
5004 }
5005
Eric Laurentddb78e72009-07-28 08:44:33 -07005006 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005007
Eric Laurent464d5b32011-06-17 21:29:58 -07005008 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07005009 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005010 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005011 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005012 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005013 }
5014 }
5015 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07005016 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005017 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005018 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005019 }
5020 thread->exit();
5021
Eric Laurent464d5b32011-06-17 21:29:58 -07005022 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005023 AudioStreamOut *out = thread->clearOutput();
5024 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005025 out->hwDev->close_output_stream(out->hwDev, out->stream);
5026 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005027 }
Eric Laurenta553c252009-07-17 12:17:14 -07005028 return NO_ERROR;
5029}
5030
Eric Laurentddb78e72009-07-28 08:44:33 -07005031status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005032{
5033 Mutex::Autolock _l(mLock);
5034 PlaybackThread *thread = checkPlaybackThread_l(output);
5035
5036 if (thread == NULL) {
5037 return BAD_VALUE;
5038 }
5039
Eric Laurentddb78e72009-07-28 08:44:33 -07005040 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005041 thread->suspend();
5042
5043 return NO_ERROR;
5044}
5045
Eric Laurentddb78e72009-07-28 08:44:33 -07005046status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005047{
5048 Mutex::Autolock _l(mLock);
5049 PlaybackThread *thread = checkPlaybackThread_l(output);
5050
5051 if (thread == NULL) {
5052 return BAD_VALUE;
5053 }
5054
Eric Laurentddb78e72009-07-28 08:44:33 -07005055 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005056
5057 thread->restore();
5058
5059 return NO_ERROR;
5060}
5061
Eric Laurentddb78e72009-07-28 08:44:33 -07005062int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005063 uint32_t *pSamplingRate,
5064 uint32_t *pFormat,
5065 uint32_t *pChannels,
5066 uint32_t acoustics)
5067{
5068 status_t status;
5069 RecordThread *thread = NULL;
5070 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5071 uint32_t format = pFormat ? *pFormat : 0;
5072 uint32_t channels = pChannels ? *pChannels : 0;
5073 uint32_t reqSamplingRate = samplingRate;
5074 uint32_t reqFormat = format;
5075 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005076 audio_stream_in_t *inStream;
5077 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005078
5079 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005080 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005081 }
Dima Zavin31f188892011-04-18 16:57:27 -07005082
Eric Laurenta553c252009-07-17 12:17:14 -07005083 Mutex::Autolock _l(mLock);
5084
Dima Zavin31f188892011-04-18 16:57:27 -07005085 inHwDev = findSuitableHwDev_l(*pDevices);
5086 if (inHwDev == NULL)
5087 return 0;
5088
5089 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5090 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005091 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005092 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005093 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005094 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005095 samplingRate,
5096 format,
5097 channels,
5098 acoustics,
5099 status);
5100
5101 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5102 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5103 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005104 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005105 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005106 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005107 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07005108 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005109 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5110 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005111 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005112 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005113 }
5114
Dima Zavin31f188892011-04-18 16:57:27 -07005115 if (inStream != NULL) {
5116 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5117
Eric Laurent464d5b32011-06-17 21:29:58 -07005118 int id = nextUniqueId();
5119 // Start record thread
5120 // RecorThread require both input and output device indication to forward to audio
5121 // pre processing modules
5122 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5123 thread = new RecordThread(this,
5124 input,
5125 reqSamplingRate,
5126 reqChannels,
5127 id,
5128 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005129 mRecordThreads.add(id, thread);
5130 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005131 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5132 if (pFormat) *pFormat = format;
5133 if (pChannels) *pChannels = reqChannels;
5134
Dima Zavin31f188892011-04-18 16:57:27 -07005135 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005136
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005137 // notify client processes of the new input creation
5138 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005139 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005140 }
5141
Eric Laurent9cc489a22009-12-05 05:20:01 -08005142 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005143}
5144
Eric Laurentddb78e72009-07-28 08:44:33 -07005145status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005146{
Eric Laurent49018a52009-08-04 08:37:05 -07005147 // keep strong reference on the record thread so that
5148 // it is not destroyed while exit() is executed
5149 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005150 {
5151 Mutex::Autolock _l(mLock);
5152 thread = checkRecordThread_l(input);
5153 if (thread == NULL) {
5154 return BAD_VALUE;
5155 }
5156
Eric Laurentddb78e72009-07-28 08:44:33 -07005157 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005158 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005159 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005160 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005161 }
5162 thread->exit();
5163
Eric Laurent828b9772011-08-07 16:32:26 -07005164 AudioStreamIn *in = thread->clearInput();
5165 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005166 in->hwDev->close_input_stream(in->hwDev, in->stream);
5167 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005168
Eric Laurenta553c252009-07-17 12:17:14 -07005169 return NO_ERROR;
5170}
5171
Eric Laurentddb78e72009-07-28 08:44:33 -07005172status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005173{
5174 Mutex::Autolock _l(mLock);
5175 MixerThread *dstThread = checkMixerThread_l(output);
5176 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005177 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005178 return BAD_VALUE;
5179 }
5180
Eric Laurentddb78e72009-07-28 08:44:33 -07005181 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005182 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005183
Eric Laurent05ce0942011-08-30 10:18:54 -07005184 dstThread->setStreamValid(stream, true);
5185
Eric Laurenta553c252009-07-17 12:17:14 -07005186 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005187 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005188 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005189 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005190 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005191 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005192 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005193 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005194 }
Eric Laurentd069f322009-09-01 05:56:26 -07005195
Eric Laurenta553c252009-07-17 12:17:14 -07005196 return NO_ERROR;
5197}
5198
Eric Laurent65b65452010-06-01 23:49:17 -07005199
5200int AudioFlinger::newAudioSessionId()
5201{
Eric Laurent464d5b32011-06-17 21:29:58 -07005202 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005203}
5204
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005205void AudioFlinger::acquireAudioSessionId(int audioSession)
5206{
5207 Mutex::Autolock _l(mLock);
5208 int caller = IPCThreadState::self()->getCallingPid();
5209 LOGV("acquiring %d from %d", audioSession, caller);
5210 int num = mAudioSessionRefs.size();
5211 for (int i = 0; i< num; i++) {
5212 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5213 if (ref->sessionid == audioSession && ref->pid == caller) {
5214 ref->cnt++;
5215 LOGV(" incremented refcount to %d", ref->cnt);
5216 return;
5217 }
5218 }
5219 AudioSessionRef *ref = new AudioSessionRef();
5220 ref->sessionid = audioSession;
5221 ref->pid = caller;
5222 ref->cnt = 1;
5223 mAudioSessionRefs.push(ref);
5224 LOGV(" added new entry for %d", ref->sessionid);
5225}
5226
5227void AudioFlinger::releaseAudioSessionId(int audioSession)
5228{
5229 Mutex::Autolock _l(mLock);
5230 int caller = IPCThreadState::self()->getCallingPid();
5231 LOGV("releasing %d from %d", audioSession, caller);
5232 int num = mAudioSessionRefs.size();
5233 for (int i = 0; i< num; i++) {
5234 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5235 if (ref->sessionid == audioSession && ref->pid == caller) {
5236 ref->cnt--;
5237 LOGV(" decremented refcount to %d", ref->cnt);
5238 if (ref->cnt == 0) {
5239 mAudioSessionRefs.removeAt(i);
5240 delete ref;
5241 purgeStaleEffects_l();
5242 }
5243 return;
5244 }
5245 }
5246 LOGW("session id %d not found for pid %d", audioSession, caller);
5247}
5248
5249void AudioFlinger::purgeStaleEffects_l() {
5250
5251 LOGV("purging stale effects");
5252
5253 Vector< sp<EffectChain> > chains;
5254
5255 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5256 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5257 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5258 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005259 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5260 chains.push(ec);
5261 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005262 }
5263 }
5264 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5265 sp<RecordThread> t = mRecordThreads.valueAt(i);
5266 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5267 sp<EffectChain> ec = t->mEffectChains[j];
5268 chains.push(ec);
5269 }
5270 }
5271
5272 for (size_t i = 0; i < chains.size(); i++) {
5273 sp<EffectChain> ec = chains[i];
5274 int sessionid = ec->sessionId();
5275 sp<ThreadBase> t = ec->mThread.promote();
5276 if (t == 0) {
5277 continue;
5278 }
5279 size_t numsessionrefs = mAudioSessionRefs.size();
5280 bool found = false;
5281 for (size_t k = 0; k < numsessionrefs; k++) {
5282 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5283 if (ref->sessionid == sessionid) {
5284 LOGV(" session %d still exists for %d with %d refs",
5285 sessionid, ref->pid, ref->cnt);
5286 found = true;
5287 break;
5288 }
5289 }
5290 if (!found) {
5291 // remove all effects from the chain
5292 while (ec->mEffects.size()) {
5293 sp<EffectModule> effect = ec->mEffects[0];
5294 effect->unPin();
5295 Mutex::Autolock _l (t->mLock);
5296 t->removeEffect_l(effect);
5297 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5298 sp<EffectHandle> handle = effect->mHandles[j].promote();
5299 if (handle != 0) {
5300 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005301 if (handle->mHasControl && handle->mEnabled) {
5302 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5303 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005304 }
5305 }
5306 AudioSystem::unregisterEffect(effect->id());
5307 }
5308 }
5309 }
5310 return;
5311}
5312
Eric Laurenta553c252009-07-17 12:17:14 -07005313// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005314AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005315{
5316 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005317 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5318 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005319 }
Eric Laurenta553c252009-07-17 12:17:14 -07005320 return thread;
5321}
5322
5323// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005324AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005325{
5326 PlaybackThread *thread = checkPlaybackThread_l(output);
5327 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005328 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005329 thread = NULL;
5330 }
5331 }
5332 return (MixerThread *)thread;
5333}
5334
5335// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005336AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005337{
5338 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005339 if (mRecordThreads.indexOfKey(input) >= 0) {
5340 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005341 }
Eric Laurenta553c252009-07-17 12:17:14 -07005342 return thread;
5343}
5344
Eric Laurent464d5b32011-06-17 21:29:58 -07005345uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005346{
Eric Laurent464d5b32011-06-17 21:29:58 -07005347 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005348}
5349
Eric Laurent464d5b32011-06-17 21:29:58 -07005350AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5351{
5352 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5353 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005354 AudioStreamOut *output = thread->getOutput();
5355 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005356 return thread;
5357 }
5358 }
5359 return NULL;
5360}
5361
5362uint32_t AudioFlinger::primaryOutputDevice_l()
5363{
5364 PlaybackThread *thread = primaryPlaybackThread_l();
5365
5366 if (thread == NULL) {
5367 return 0;
5368 }
5369
5370 return thread->device();
5371}
5372
5373
Eric Laurent65b65452010-06-01 23:49:17 -07005374// ----------------------------------------------------------------------------
5375// Effect management
5376// ----------------------------------------------------------------------------
5377
5378
Eric Laurent65b65452010-06-01 23:49:17 -07005379status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5380{
5381 Mutex::Autolock _l(mLock);
5382 return EffectQueryNumberEffects(numEffects);
5383}
5384
Eric Laurent53334cd2010-06-23 17:38:20 -07005385status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005386{
5387 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005388 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005389}
5390
5391status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5392{
5393 Mutex::Autolock _l(mLock);
5394 return EffectGetDescriptor(pUuid, descriptor);
5395}
5396
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005397
Eric Laurent65b65452010-06-01 23:49:17 -07005398sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5399 effect_descriptor_t *pDesc,
5400 const sp<IEffectClient>& effectClient,
5401 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005402 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005403 int sessionId,
5404 status_t *status,
5405 int *id,
5406 int *enabled)
5407{
5408 status_t lStatus = NO_ERROR;
5409 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005410 effect_descriptor_t desc;
5411 sp<Client> client;
5412 wp<Client> wclient;
5413
Eric Laurent464d5b32011-06-17 21:29:58 -07005414 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5415 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005416
5417 if (pDesc == NULL) {
5418 lStatus = BAD_VALUE;
5419 goto Exit;
5420 }
5421
Eric Laurent98c92592010-09-23 16:10:16 -07005422 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005423 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005424 lStatus = PERMISSION_DENIED;
5425 goto Exit;
5426 }
5427
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005428 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005429 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005430 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005431 lStatus = PERMISSION_DENIED;
5432 goto Exit;
5433 }
5434
Eric Laurent464d5b32011-06-17 21:29:58 -07005435 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005436 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005437 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005438 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005439 lStatus = BAD_VALUE;
5440 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005441 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005442 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005443 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005444 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005445 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005446 }
5447 }
5448
Eric Laurent65b65452010-06-01 23:49:17 -07005449 {
5450 Mutex::Autolock _l(mLock);
5451
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005452
Eric Laurent65b65452010-06-01 23:49:17 -07005453 if (!EffectIsNullUuid(&pDesc->uuid)) {
5454 // if uuid is specified, request effect descriptor
5455 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5456 if (lStatus < 0) {
5457 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5458 goto Exit;
5459 }
5460 } else {
5461 // if uuid is not specified, look for an available implementation
5462 // of the required type in effect factory
5463 if (EffectIsNullUuid(&pDesc->type)) {
5464 LOGW("createEffect() no effect type");
5465 lStatus = BAD_VALUE;
5466 goto Exit;
5467 }
5468 uint32_t numEffects = 0;
5469 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005470 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005471 bool found = false;
5472
5473 lStatus = EffectQueryNumberEffects(&numEffects);
5474 if (lStatus < 0) {
5475 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5476 goto Exit;
5477 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005478 for (uint32_t i = 0; i < numEffects; i++) {
5479 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005480 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005481 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005482 continue;
5483 }
5484 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5485 // If matching type found save effect descriptor. If the session is
5486 // 0 and the effect is not auxiliary, continue enumeration in case
5487 // an auxiliary version of this effect type is available
5488 found = true;
5489 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005490 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005491 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5492 break;
5493 }
5494 }
5495 }
5496 if (!found) {
5497 lStatus = BAD_VALUE;
5498 LOGW("createEffect() effect not found");
5499 goto Exit;
5500 }
5501 // For same effect type, chose auxiliary version over insert version if
5502 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005503 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005504 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5505 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5506 }
5507 }
5508
5509 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005510 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005511 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5512 lStatus = INVALID_OPERATION;
5513 goto Exit;
5514 }
5515
Eric Laurentf82fccd2011-07-27 19:49:51 -07005516 // check recording permission for visualizer
5517 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5518 !recordingAllowed()) {
5519 lStatus = PERMISSION_DENIED;
5520 goto Exit;
5521 }
5522
Eric Laurent65b65452010-06-01 23:49:17 -07005523 // return effect descriptor
5524 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5525
5526 // If output is not specified try to find a matching audio session ID in one of the
5527 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005528 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5529 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005530 // Note: io is never 0 when creating an effect on an input
5531 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005532 // look for the thread where the specified audio session is present
5533 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5534 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005535 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005536 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005537 }
Eric Laurent65b65452010-06-01 23:49:17 -07005538 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005539 if (io == 0) {
5540 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5541 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5542 io = mRecordThreads.keyAt(i);
5543 break;
5544 }
5545 }
5546 }
Eric Laurent98c92592010-09-23 16:10:16 -07005547 // If no output thread contains the requested session ID, default to
5548 // first output. The effect chain will be moved to the correct output
5549 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005550 if (io == 0 && mPlaybackThreads.size()) {
5551 io = mPlaybackThreads.keyAt(0);
5552 }
5553 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5554 }
5555 ThreadBase *thread = checkRecordThread_l(io);
5556 if (thread == NULL) {
5557 thread = checkPlaybackThread_l(io);
5558 if (thread == NULL) {
5559 LOGE("createEffect() unknown output thread");
5560 lStatus = BAD_VALUE;
5561 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005562 }
Eric Laurent65b65452010-06-01 23:49:17 -07005563 }
Eric Laurent98c92592010-09-23 16:10:16 -07005564
Eric Laurent65b65452010-06-01 23:49:17 -07005565 wclient = mClients.valueFor(pid);
5566
5567 if (wclient != NULL) {
5568 client = wclient.promote();
5569 } else {
5570 client = new Client(this, pid);
5571 mClients.add(pid, client);
5572 }
5573
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005574 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005575 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5576 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005577 if (handle != 0 && id != NULL) {
5578 *id = handle->id();
5579 }
5580 }
5581
5582Exit:
5583 if(status) {
5584 *status = lStatus;
5585 }
5586 return handle;
5587}
5588
Eric Laurentf82fccd2011-07-27 19:49:51 -07005589status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005590{
5591 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005592 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005593 Mutex::Autolock _l(mLock);
5594 if (srcOutput == dstOutput) {
5595 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5596 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005597 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005598 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5599 if (srcThread == NULL) {
5600 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5601 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005602 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005603 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5604 if (dstThread == NULL) {
5605 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5606 return BAD_VALUE;
5607 }
5608
5609 Mutex::Autolock _dl(dstThread->mLock);
5610 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005611 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612
Eric Laurent53334cd2010-06-23 17:38:20 -07005613 return NO_ERROR;
5614}
5615
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005616// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005617status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005618 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005619 AudioFlinger::PlaybackThread *dstThread,
5620 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005621{
5622 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005623 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005624
Eric Laurentf82fccd2011-07-27 19:49:51 -07005625 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005626 if (chain == 0) {
5627 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005628 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005629 return INVALID_OPERATION;
5630 }
5631
Eric Laurent493941b2010-07-28 01:32:47 -07005632 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005633 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005634 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005635 // removed.
5636 srcThread->removeEffectChain_l(chain);
5637
5638 // transfer all effects one by one so that new effect chain is created on new thread with
5639 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005640 int dstOutput = dstThread->id();
5641 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005642 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005643 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5644 while (effect != 0) {
5645 srcThread->removeEffect_l(effect);
5646 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005647 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5648 if (effect->state() == EffectModule::ACTIVE ||
5649 effect->state() == EffectModule::STOPPING) {
5650 effect->start();
5651 }
Eric Laurent493941b2010-07-28 01:32:47 -07005652 // if the move request is not received from audio policy manager, the effect must be
5653 // re-registered with the new strategy and output
5654 if (dstChain == 0) {
5655 dstChain = effect->chain().promote();
5656 if (dstChain == 0) {
5657 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5658 srcThread->addEffect_l(effect);
5659 return NO_INIT;
5660 }
5661 strategy = dstChain->strategy();
5662 }
5663 if (reRegister) {
5664 AudioSystem::unregisterEffect(effect->id());
5665 AudioSystem::registerEffect(&effect->desc(),
5666 dstOutput,
5667 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005668 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005669 effect->id());
5670 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005671 effect = chain->getEffectFromId_l(0);
5672 }
5673
5674 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005675}
5676
Eric Laurent464d5b32011-06-17 21:29:58 -07005677
Eric Laurent65b65452010-06-01 23:49:17 -07005678// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005679sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005680 const sp<AudioFlinger::Client>& client,
5681 const sp<IEffectClient>& effectClient,
5682 int32_t priority,
5683 int sessionId,
5684 effect_descriptor_t *desc,
5685 int *enabled,
5686 status_t *status
5687 )
5688{
5689 sp<EffectModule> effect;
5690 sp<EffectHandle> handle;
5691 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005692 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005693 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005694 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005695 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005696
Eric Laurent464d5b32011-06-17 21:29:58 -07005697 lStatus = initCheck();
5698 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005699 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005700 goto Exit;
5701 }
5702
5703 // Do not allow effects with session ID 0 on direct output or duplicating threads
5704 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005705 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005706 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5707 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005708 lStatus = BAD_VALUE;
5709 goto Exit;
5710 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005711 // Only Pre processor effects are allowed on input threads and only on input threads
5712 if ((mType == RECORD &&
5713 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5714 (mType != RECORD &&
5715 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5716 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5717 desc->name, desc->flags, mType);
5718 lStatus = BAD_VALUE;
5719 goto Exit;
5720 }
Eric Laurent65b65452010-06-01 23:49:17 -07005721
5722 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5723
5724 { // scope for mLock
5725 Mutex::Autolock _l(mLock);
5726
5727 // check for existing effect chain with the requested audio session
5728 chain = getEffectChain_l(sessionId);
5729 if (chain == 0) {
5730 // create a new chain for this session
5731 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5732 chain = new EffectChain(this, sessionId);
5733 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005734 chain->setStrategy(getStrategyForSession_l(sessionId));
5735 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005736 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005737 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005738 }
5739
5740 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5741
5742 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005743 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005744 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005745 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005746 if (lStatus != NO_ERROR) {
5747 goto Exit;
5748 }
5749 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005750 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005751 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005752 lStatus = effect->status();
5753 if (lStatus != NO_ERROR) {
5754 goto Exit;
5755 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005756 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005757 if (lStatus != NO_ERROR) {
5758 goto Exit;
5759 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005760 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005761
5762 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005763 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005764 }
5765 // create effect handle and connect it to effect module
5766 handle = new EffectHandle(effect, client, effectClient, priority);
5767 lStatus = effect->addHandle(handle);
5768 if (enabled) {
5769 *enabled = (int)effect->isEnabled();
5770 }
5771 }
5772
5773Exit:
5774 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005775 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005776 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005777 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005778 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005779 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005780 AudioSystem::unregisterEffect(effect->id());
5781 }
5782 if (chainCreated) {
5783 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005784 }
Eric Laurent65b65452010-06-01 23:49:17 -07005785 handle.clear();
5786 }
5787
5788 if(status) {
5789 *status = lStatus;
5790 }
5791 return handle;
5792}
5793
Eric Laurent464d5b32011-06-17 21:29:58 -07005794sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5795{
5796 sp<EffectModule> effect;
5797
5798 sp<EffectChain> chain = getEffectChain_l(sessionId);
5799 if (chain != 0) {
5800 effect = chain->getEffectFromId_l(effectId);
5801 }
5802 return effect;
5803}
5804
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005805// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5806// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005807status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005808{
5809 // check for existing effect chain with the requested audio session
5810 int sessionId = effect->sessionId();
5811 sp<EffectChain> chain = getEffectChain_l(sessionId);
5812 bool chainCreated = false;
5813
5814 if (chain == 0) {
5815 // create a new chain for this session
5816 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5817 chain = new EffectChain(this, sessionId);
5818 addEffectChain_l(chain);
5819 chain->setStrategy(getStrategyForSession_l(sessionId));
5820 chainCreated = true;
5821 }
5822 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5823
5824 if (chain->getEffectFromId_l(effect->id()) != 0) {
5825 LOGW("addEffect_l() %p effect %s already present in chain %p",
5826 this, effect->desc().name, chain.get());
5827 return BAD_VALUE;
5828 }
5829
5830 status_t status = chain->addEffect_l(effect);
5831 if (status != NO_ERROR) {
5832 if (chainCreated) {
5833 removeEffectChain_l(chain);
5834 }
5835 return status;
5836 }
5837
5838 effect->setDevice(mDevice);
5839 effect->setMode(mAudioFlinger->getMode());
5840 return NO_ERROR;
5841}
5842
Eric Laurent464d5b32011-06-17 21:29:58 -07005843void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005844
5845 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005846 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005847 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5848 detachAuxEffect_l(effect->id());
5849 }
5850
5851 sp<EffectChain> chain = effect->chain().promote();
5852 if (chain != 0) {
5853 // remove effect chain if removing last effect
5854 if (chain->removeEffect_l(effect) == 0) {
5855 removeEffectChain_l(chain);
5856 }
5857 } else {
5858 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5859 }
5860}
5861
Eric Laurent464d5b32011-06-17 21:29:58 -07005862void AudioFlinger::ThreadBase::lockEffectChains_l(
5863 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5864{
5865 effectChains = mEffectChains;
5866 for (size_t i = 0; i < mEffectChains.size(); i++) {
5867 mEffectChains[i]->lock();
5868 }
5869}
5870
5871void AudioFlinger::ThreadBase::unlockEffectChains(
5872 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5873{
5874 for (size_t i = 0; i < effectChains.size(); i++) {
5875 effectChains[i]->unlock();
5876 }
5877}
5878
5879sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5880{
5881 Mutex::Autolock _l(mLock);
5882 return getEffectChain_l(sessionId);
5883}
5884
5885sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5886{
5887 sp<EffectChain> chain;
5888
5889 size_t size = mEffectChains.size();
5890 for (size_t i = 0; i < size; i++) {
5891 if (mEffectChains[i]->sessionId() == sessionId) {
5892 chain = mEffectChains[i];
5893 break;
5894 }
5895 }
5896 return chain;
5897}
5898
5899void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5900{
5901 Mutex::Autolock _l(mLock);
5902 size_t size = mEffectChains.size();
5903 for (size_t i = 0; i < size; i++) {
5904 mEffectChains[i]->setMode_l(mode);
5905 }
5906}
5907
5908void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005909 const wp<EffectHandle>& handle,
5910 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005911
Eric Laurent53334cd2010-06-23 17:38:20 -07005912 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005913 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005914 // delete the effect module if removing last handle on it
5915 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005916 if (!effect->isPinned() || unpiniflast) {
5917 removeEffect_l(effect);
5918 AudioSystem::unregisterEffect(effect->id());
5919 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005920 }
5921}
5922
Eric Laurent65b65452010-06-01 23:49:17 -07005923status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5924{
5925 int session = chain->sessionId();
5926 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005927 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005928
5929 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005930 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005931 // Only one effect chain can be present in direct output thread and it uses
5932 // the mix buffer as input
5933 if (mType != DIRECT) {
5934 size_t numSamples = mFrameCount * mChannelCount;
5935 buffer = new int16_t[numSamples];
5936 memset(buffer, 0, numSamples * sizeof(int16_t));
5937 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5938 ownsBuffer = true;
5939 }
Eric Laurent65b65452010-06-01 23:49:17 -07005940
Eric Laurent53334cd2010-06-23 17:38:20 -07005941 // Attach all tracks with same session ID to this chain.
5942 for (size_t i = 0; i < mTracks.size(); ++i) {
5943 sp<Track> track = mTracks[i];
5944 if (session == track->sessionId()) {
5945 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5946 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005947 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005948 }
5949 }
5950
5951 // indicate all active tracks in the chain
5952 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5953 sp<Track> track = mActiveTracks[i].promote();
5954 if (track == 0) continue;
5955 if (session == track->sessionId()) {
5956 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005957 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005958 }
Eric Laurent65b65452010-06-01 23:49:17 -07005959 }
5960 }
5961
Eric Laurent53334cd2010-06-23 17:38:20 -07005962 chain->setInBuffer(buffer, ownsBuffer);
5963 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005964 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005965 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005966 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5967 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005968 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005969 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5970 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005971 // Effect chain for other sessions are inserted at beginning of effect
5972 // chains list to be processed before output mix effects. Relative order between other
5973 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005974 size_t size = mEffectChains.size();
5975 size_t i = 0;
5976 for (i = 0; i < size; i++) {
5977 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005978 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005979 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005980 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005981
5982 return NO_ERROR;
5983}
5984
5985size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5986{
5987 int session = chain->sessionId();
5988
5989 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5990
5991 for (size_t i = 0; i < mEffectChains.size(); i++) {
5992 if (chain == mEffectChains[i]) {
5993 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005994 // detach all active tracks from the chain
5995 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5996 sp<Track> track = mActiveTracks[i].promote();
5997 if (track == 0) continue;
5998 if (session == track->sessionId()) {
5999 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6000 chain.get(), session);
6001 chain->decActiveTrackCnt();
6002 }
6003 }
6004
Eric Laurent65b65452010-06-01 23:49:17 -07006005 // detach all tracks with same session ID from this chain
6006 for (size_t i = 0; i < mTracks.size(); ++i) {
6007 sp<Track> track = mTracks[i];
6008 if (session == track->sessionId()) {
6009 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07006010 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07006011 }
6012 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006013 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006014 }
6015 }
6016 return mEffectChains.size();
6017}
6018
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006019status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6020 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006021{
6022 Mutex::Autolock _l(mLock);
6023 return attachAuxEffect_l(track, EffectId);
6024}
6025
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006026status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6027 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006028{
6029 status_t status = NO_ERROR;
6030
6031 if (EffectId == 0) {
6032 track->setAuxBuffer(0, NULL);
6033 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006034 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6035 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006036 if (effect != 0) {
6037 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6038 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6039 } else {
6040 status = INVALID_OPERATION;
6041 }
6042 } else {
6043 status = BAD_VALUE;
6044 }
6045 }
6046 return status;
6047}
6048
6049void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6050{
6051 for (size_t i = 0; i < mTracks.size(); ++i) {
6052 sp<Track> track = mTracks[i];
6053 if (track->auxEffectId() == effectId) {
6054 attachAuxEffect_l(track, 0);
6055 }
6056 }
6057}
6058
Eric Laurent464d5b32011-06-17 21:29:58 -07006059status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6060{
6061 // only one chain per input thread
6062 if (mEffectChains.size() != 0) {
6063 return INVALID_OPERATION;
6064 }
6065 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6066
6067 chain->setInBuffer(NULL);
6068 chain->setOutBuffer(NULL);
6069
Eric Laurentf82fccd2011-07-27 19:49:51 -07006070 checkSuspendOnAddEffectChain_l(chain);
6071
Eric Laurent464d5b32011-06-17 21:29:58 -07006072 mEffectChains.add(chain);
6073
6074 return NO_ERROR;
6075}
6076
6077size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6078{
6079 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6080 LOGW_IF(mEffectChains.size() != 1,
6081 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6082 chain.get(), mEffectChains.size(), this);
6083 if (mEffectChains.size() == 1) {
6084 mEffectChains.removeAt(0);
6085 }
6086 return 0;
6087}
6088
Eric Laurent65b65452010-06-01 23:49:17 -07006089// ----------------------------------------------------------------------------
6090// EffectModule implementation
6091// ----------------------------------------------------------------------------
6092
6093#undef LOG_TAG
6094#define LOG_TAG "AudioFlinger::EffectModule"
6095
6096AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6097 const wp<AudioFlinger::EffectChain>& chain,
6098 effect_descriptor_t *desc,
6099 int id,
6100 int sessionId)
6101 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006102 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006103{
6104 LOGV("Constructor %p", this);
6105 int lStatus;
6106 sp<ThreadBase> thread = mThread.promote();
6107 if (thread == 0) {
6108 return;
6109 }
Eric Laurent65b65452010-06-01 23:49:17 -07006110
6111 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6112
6113 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006114 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006115
Eric Laurent65b65452010-06-01 23:49:17 -07006116 if (mStatus != NO_ERROR) {
6117 return;
6118 }
6119 lStatus = init();
6120 if (lStatus < 0) {
6121 mStatus = lStatus;
6122 goto Error;
6123 }
6124
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006125 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6126 mPinned = true;
6127 }
Eric Laurent65b65452010-06-01 23:49:17 -07006128 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6129 return;
6130Error:
6131 EffectRelease(mEffectInterface);
6132 mEffectInterface = NULL;
6133 LOGV("Constructor Error %d", mStatus);
6134}
6135
6136AudioFlinger::EffectModule::~EffectModule()
6137{
6138 LOGV("Destructor %p", this);
6139 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006140 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6141 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6142 sp<ThreadBase> thread = mThread.promote();
6143 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006144 audio_stream_t *stream = thread->stream();
6145 if (stream != NULL) {
6146 stream->remove_audio_effect(stream, mEffectInterface);
6147 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006148 }
6149 }
Eric Laurent65b65452010-06-01 23:49:17 -07006150 // release effect engine
6151 EffectRelease(mEffectInterface);
6152 }
6153}
6154
6155status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6156{
6157 status_t status;
6158
6159 Mutex::Autolock _l(mLock);
6160 // First handle in mHandles has highest priority and controls the effect module
6161 int priority = handle->priority();
6162 size_t size = mHandles.size();
6163 sp<EffectHandle> h;
6164 size_t i;
6165 for (i = 0; i < size; i++) {
6166 h = mHandles[i].promote();
6167 if (h == 0) continue;
6168 if (h->priority() <= priority) break;
6169 }
6170 // if inserted in first place, move effect control from previous owner to this handle
6171 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006172 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006173 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006174 enabled = h->enabled();
6175 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006176 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006177 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006178 status = NO_ERROR;
6179 } else {
6180 status = ALREADY_EXISTS;
6181 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006182 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006183 mHandles.insertAt(handle, i);
6184 return status;
6185}
6186
6187size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6188{
6189 Mutex::Autolock _l(mLock);
6190 size_t size = mHandles.size();
6191 size_t i;
6192 for (i = 0; i < size; i++) {
6193 if (mHandles[i] == handle) break;
6194 }
6195 if (i == size) {
6196 return size;
6197 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006198 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6199
6200 bool enabled = false;
6201 EffectHandle *hdl = handle.unsafe_get();
6202 if (hdl) {
6203 LOGV("removeHandle() unsafe_get OK");
6204 enabled = hdl->enabled();
6205 }
Eric Laurent65b65452010-06-01 23:49:17 -07006206 mHandles.removeAt(i);
6207 size = mHandles.size();
6208 // if removed from first place, move effect control from this handle to next in line
6209 if (i == 0 && size != 0) {
6210 sp<EffectHandle> h = mHandles[0].promote();
6211 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006212 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006213 }
6214 }
6215
Eric Laurent21b5c472011-07-26 20:54:46 -07006216 // Prevent calls to process() and other functions on effect interface from now on.
6217 // The effect engine will be released by the destructor when the last strong reference on
6218 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006219 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006220 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006221 }
6222
Eric Laurent65b65452010-06-01 23:49:17 -07006223 return size;
6224}
6225
Eric Laurentf82fccd2011-07-27 19:49:51 -07006226sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6227{
6228 Mutex::Autolock _l(mLock);
6229 sp<EffectHandle> handle;
6230 if (mHandles.size() != 0) {
6231 handle = mHandles[0].promote();
6232 }
6233 return handle;
6234}
6235
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006236void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006237{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006238 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006239 // keep a strong reference on this EffectModule to avoid calling the
6240 // destructor before we exit
6241 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006242 {
6243 sp<ThreadBase> thread = mThread.promote();
6244 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006245 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006246 }
6247 }
6248}
6249
Eric Laurent7d850f22010-07-09 13:34:17 -07006250void AudioFlinger::EffectModule::updateState() {
6251 Mutex::Autolock _l(mLock);
6252
6253 switch (mState) {
6254 case RESTART:
6255 reset_l();
6256 // FALL THROUGH
6257
6258 case STARTING:
6259 // clear auxiliary effect input buffer for next accumulation
6260 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6261 memset(mConfig.inputCfg.buffer.raw,
6262 0,
6263 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6264 }
6265 start_l();
6266 mState = ACTIVE;
6267 break;
6268 case STOPPING:
6269 stop_l();
6270 mDisableWaitCnt = mMaxDisableWaitCnt;
6271 mState = STOPPED;
6272 break;
6273 case STOPPED:
6274 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6275 // turn off sequence.
6276 if (--mDisableWaitCnt == 0) {
6277 reset_l();
6278 mState = IDLE;
6279 }
6280 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006281 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006282 break;
6283 }
6284}
6285
Eric Laurent65b65452010-06-01 23:49:17 -07006286void AudioFlinger::EffectModule::process()
6287{
6288 Mutex::Autolock _l(mLock);
6289
Eric Laurent21b5c472011-07-26 20:54:46 -07006290 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006291 mConfig.inputCfg.buffer.raw == NULL ||
6292 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006293 return;
6294 }
6295
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006296 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006297 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6298 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6299 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6300 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006301 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006302 }
6303
Eric Laurent65b65452010-06-01 23:49:17 -07006304 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006305 int ret = (*mEffectInterface)->process(mEffectInterface,
6306 &mConfig.inputCfg.buffer,
6307 &mConfig.outputCfg.buffer);
6308
6309 // force transition to IDLE state when engine is ready
6310 if (mState == STOPPED && ret == -ENODATA) {
6311 mDisableWaitCnt = 1;
6312 }
Eric Laurent65b65452010-06-01 23:49:17 -07006313
6314 // clear auxiliary effect input buffer for next accumulation
6315 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006316 memset(mConfig.inputCfg.buffer.raw, 0,
6317 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006318 }
6319 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006320 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6321 // If an insert effect is idle and input buffer is different from output buffer,
6322 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006323 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006324 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006325 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6326 int16_t *in = mConfig.inputCfg.buffer.s16;
6327 int16_t *out = mConfig.outputCfg.buffer.s16;
6328 for (size_t i = 0; i < frameCnt; i++) {
6329 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006330 }
Eric Laurent65b65452010-06-01 23:49:17 -07006331 }
6332 }
6333}
6334
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006335void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006336{
6337 if (mEffectInterface == NULL) {
6338 return;
6339 }
6340 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6341}
6342
6343status_t AudioFlinger::EffectModule::configure()
6344{
6345 uint32_t channels;
6346 if (mEffectInterface == NULL) {
6347 return NO_INIT;
6348 }
6349
6350 sp<ThreadBase> thread = mThread.promote();
6351 if (thread == 0) {
6352 return DEAD_OBJECT;
6353 }
6354
6355 // TODO: handle configuration of effects replacing track process
6356 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006357 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006358 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006359 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006360 }
6361
6362 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006363 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006364 } else {
6365 mConfig.inputCfg.channels = channels;
6366 }
6367 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006368 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6369 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006370 mConfig.inputCfg.samplingRate = thread->sampleRate();
6371 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6372 mConfig.inputCfg.bufferProvider.cookie = NULL;
6373 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6374 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6375 mConfig.outputCfg.bufferProvider.cookie = NULL;
6376 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6377 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6378 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6379 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006380 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006381 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006382 // - in other sessions:
6383 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6384 // other effect: overwrites output buffer: input buffer == output buffer
6385 // Auxiliary effect:
6386 // accumulates in output buffer: input buffer != output buffer
6387 // Therefore: accumulate <=> input buffer != output buffer
6388 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6389 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6390 } else {
6391 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6392 }
6393 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6394 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6395 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6396 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6397
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006398 LOGV("configure() %p thread %p buffer %p framecount %d",
6399 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6400
Eric Laurent65b65452010-06-01 23:49:17 -07006401 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006402 uint32_t size = sizeof(int);
6403 status_t status = (*mEffectInterface)->command(mEffectInterface,
6404 EFFECT_CMD_CONFIGURE,
6405 sizeof(effect_config_t),
6406 &mConfig,
6407 &size,
6408 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006409 if (status == 0) {
6410 status = cmdStatus;
6411 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006412
6413 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6414 (1000 * mConfig.outputCfg.buffer.frameCount);
6415
Eric Laurent65b65452010-06-01 23:49:17 -07006416 return status;
6417}
6418
6419status_t AudioFlinger::EffectModule::init()
6420{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006421 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006422 if (mEffectInterface == NULL) {
6423 return NO_INIT;
6424 }
6425 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006426 uint32_t size = sizeof(status_t);
6427 status_t status = (*mEffectInterface)->command(mEffectInterface,
6428 EFFECT_CMD_INIT,
6429 0,
6430 NULL,
6431 &size,
6432 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006433 if (status == 0) {
6434 status = cmdStatus;
6435 }
6436 return status;
6437}
6438
Eric Laurent6fccbd02011-10-05 17:42:25 -07006439status_t AudioFlinger::EffectModule::start()
6440{
6441 Mutex::Autolock _l(mLock);
6442 return start_l();
6443}
6444
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006445status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006446{
6447 if (mEffectInterface == NULL) {
6448 return NO_INIT;
6449 }
6450 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006451 uint32_t size = sizeof(status_t);
6452 status_t status = (*mEffectInterface)->command(mEffectInterface,
6453 EFFECT_CMD_ENABLE,
6454 0,
6455 NULL,
6456 &size,
6457 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006458 if (status == 0) {
6459 status = cmdStatus;
6460 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006461 if (status == 0 &&
6462 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6463 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6464 sp<ThreadBase> thread = mThread.promote();
6465 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006466 audio_stream_t *stream = thread->stream();
6467 if (stream != NULL) {
6468 stream->add_audio_effect(stream, mEffectInterface);
6469 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006470 }
6471 }
Eric Laurent65b65452010-06-01 23:49:17 -07006472 return status;
6473}
6474
Eric Laurent21b5c472011-07-26 20:54:46 -07006475status_t AudioFlinger::EffectModule::stop()
6476{
6477 Mutex::Autolock _l(mLock);
6478 return stop_l();
6479}
6480
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006481status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006482{
6483 if (mEffectInterface == NULL) {
6484 return NO_INIT;
6485 }
6486 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006487 uint32_t size = sizeof(status_t);
6488 status_t status = (*mEffectInterface)->command(mEffectInterface,
6489 EFFECT_CMD_DISABLE,
6490 0,
6491 NULL,
6492 &size,
6493 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006494 if (status == 0) {
6495 status = cmdStatus;
6496 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006497 if (status == 0 &&
6498 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6499 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6500 sp<ThreadBase> thread = mThread.promote();
6501 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006502 audio_stream_t *stream = thread->stream();
6503 if (stream != NULL) {
6504 stream->remove_audio_effect(stream, mEffectInterface);
6505 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006506 }
6507 }
Eric Laurent65b65452010-06-01 23:49:17 -07006508 return status;
6509}
6510
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006511status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6512 uint32_t cmdSize,
6513 void *pCmdData,
6514 uint32_t *replySize,
6515 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006516{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006517 Mutex::Autolock _l(mLock);
6518// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006519
Eric Laurent21b5c472011-07-26 20:54:46 -07006520 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006521 return NO_INIT;
6522 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006523 status_t status = (*mEffectInterface)->command(mEffectInterface,
6524 cmdCode,
6525 cmdSize,
6526 pCmdData,
6527 replySize,
6528 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006529 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006530 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006531 for (size_t i = 1; i < mHandles.size(); i++) {
6532 sp<EffectHandle> h = mHandles[i].promote();
6533 if (h != 0) {
6534 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6535 }
6536 }
6537 }
6538 return status;
6539}
6540
6541status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6542{
Eric Laurent6752ec82011-08-10 10:37:50 -07006543
Eric Laurent65b65452010-06-01 23:49:17 -07006544 Mutex::Autolock _l(mLock);
6545 LOGV("setEnabled %p enabled %d", this, enabled);
6546
6547 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006548 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6549 if (enabled && status != NO_ERROR) {
6550 return status;
6551 }
6552
Eric Laurent65b65452010-06-01 23:49:17 -07006553 switch (mState) {
6554 // going from disabled to enabled
6555 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006556 mState = STARTING;
6557 break;
6558 case STOPPED:
6559 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006560 break;
6561 case STOPPING:
6562 mState = ACTIVE;
6563 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006564
6565 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006566 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006567 mState = STOPPED;
6568 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006569 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006570 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006571 break;
6572 case ACTIVE:
6573 mState = STOPPING;
6574 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006575 case DESTROYED:
6576 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006577 }
6578 for (size_t i = 1; i < mHandles.size(); i++) {
6579 sp<EffectHandle> h = mHandles[i].promote();
6580 if (h != 0) {
6581 h->setEnabled(enabled);
6582 }
6583 }
6584 }
6585 return NO_ERROR;
6586}
6587
6588bool AudioFlinger::EffectModule::isEnabled()
6589{
6590 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006591 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006592 case STARTING:
6593 case ACTIVE:
6594 return true;
6595 case IDLE:
6596 case STOPPING:
6597 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006598 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006599 default:
6600 return false;
6601 }
6602}
6603
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006604bool AudioFlinger::EffectModule::isProcessEnabled()
6605{
6606 switch (mState) {
6607 case RESTART:
6608 case ACTIVE:
6609 case STOPPING:
6610 case STOPPED:
6611 return true;
6612 case IDLE:
6613 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006614 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006615 default:
6616 return false;
6617 }
6618}
6619
Eric Laurent65b65452010-06-01 23:49:17 -07006620status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6621{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006622 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006623 status_t status = NO_ERROR;
6624
6625 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6626 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006627 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006628 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6629 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006630 status_t cmdStatus;
6631 uint32_t volume[2];
6632 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006633 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006634 volume[0] = *left;
6635 volume[1] = *right;
6636 if (controller) {
6637 pVolume = volume;
6638 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006639 status = (*mEffectInterface)->command(mEffectInterface,
6640 EFFECT_CMD_SET_VOLUME,
6641 size,
6642 volume,
6643 &size,
6644 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006645 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6646 *left = volume[0];
6647 *right = volume[1];
6648 }
6649 }
6650 return status;
6651}
6652
6653status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6654{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006655 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006656 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006657 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6658 // audio pre processing modules on RecordThread can receive both output and
6659 // input device indication in the same call
6660 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6661 if (dev) {
6662 status_t cmdStatus;
6663 uint32_t size = sizeof(status_t);
6664
6665 status = (*mEffectInterface)->command(mEffectInterface,
6666 EFFECT_CMD_SET_DEVICE,
6667 sizeof(uint32_t),
6668 &dev,
6669 &size,
6670 &cmdStatus);
6671 if (status == NO_ERROR) {
6672 status = cmdStatus;
6673 }
6674 }
6675 dev = device & AUDIO_DEVICE_IN_ALL;
6676 if (dev) {
6677 status_t cmdStatus;
6678 uint32_t size = sizeof(status_t);
6679
6680 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6681 EFFECT_CMD_SET_INPUT_DEVICE,
6682 sizeof(uint32_t),
6683 &dev,
6684 &size,
6685 &cmdStatus);
6686 if (status2 == NO_ERROR) {
6687 status2 = cmdStatus;
6688 }
6689 if (status == NO_ERROR) {
6690 status = status2;
6691 }
Eric Laurent65b65452010-06-01 23:49:17 -07006692 }
6693 }
6694 return status;
6695}
6696
Eric Laurent53334cd2010-06-23 17:38:20 -07006697status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6698{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006699 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006700 status_t status = NO_ERROR;
6701 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006702 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006703 uint32_t size = sizeof(status_t);
6704 status = (*mEffectInterface)->command(mEffectInterface,
6705 EFFECT_CMD_SET_AUDIO_MODE,
6706 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006707 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006708 &size,
6709 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006710 if (status == NO_ERROR) {
6711 status = cmdStatus;
6712 }
6713 }
6714 return status;
6715}
6716
Eric Laurentf82fccd2011-07-27 19:49:51 -07006717void AudioFlinger::EffectModule::setSuspended(bool suspended)
6718{
6719 Mutex::Autolock _l(mLock);
6720 mSuspended = suspended;
6721}
6722bool AudioFlinger::EffectModule::suspended()
6723{
6724 Mutex::Autolock _l(mLock);
6725 return mSuspended;
6726}
6727
Eric Laurent65b65452010-06-01 23:49:17 -07006728status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6729{
6730 const size_t SIZE = 256;
6731 char buffer[SIZE];
6732 String8 result;
6733
6734 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6735 result.append(buffer);
6736
6737 bool locked = tryLock(mLock);
6738 // failed to lock - AudioFlinger is probably deadlocked
6739 if (!locked) {
6740 result.append("\t\tCould not lock Fx mutex:\n");
6741 }
6742
6743 result.append("\t\tSession Status State Engine:\n");
6744 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6745 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6746 result.append(buffer);
6747
6748 result.append("\t\tDescriptor:\n");
6749 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6750 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6751 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6752 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6753 result.append(buffer);
6754 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6755 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6756 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6757 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6758 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006759 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006760 mDescriptor.apiVersion,
6761 mDescriptor.flags);
6762 result.append(buffer);
6763 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6764 mDescriptor.name);
6765 result.append(buffer);
6766 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6767 mDescriptor.implementor);
6768 result.append(buffer);
6769
6770 result.append("\t\t- Input configuration:\n");
6771 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6772 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6773 (uint32_t)mConfig.inputCfg.buffer.raw,
6774 mConfig.inputCfg.buffer.frameCount,
6775 mConfig.inputCfg.samplingRate,
6776 mConfig.inputCfg.channels,
6777 mConfig.inputCfg.format);
6778 result.append(buffer);
6779
6780 result.append("\t\t- Output configuration:\n");
6781 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6782 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6783 (uint32_t)mConfig.outputCfg.buffer.raw,
6784 mConfig.outputCfg.buffer.frameCount,
6785 mConfig.outputCfg.samplingRate,
6786 mConfig.outputCfg.channels,
6787 mConfig.outputCfg.format);
6788 result.append(buffer);
6789
6790 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6791 result.append(buffer);
6792 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6793 for (size_t i = 0; i < mHandles.size(); ++i) {
6794 sp<EffectHandle> handle = mHandles[i].promote();
6795 if (handle != 0) {
6796 handle->dump(buffer, SIZE);
6797 result.append(buffer);
6798 }
6799 }
6800
6801 result.append("\n");
6802
6803 write(fd, result.string(), result.length());
6804
6805 if (locked) {
6806 mLock.unlock();
6807 }
6808
6809 return NO_ERROR;
6810}
6811
6812// ----------------------------------------------------------------------------
6813// EffectHandle implementation
6814// ----------------------------------------------------------------------------
6815
6816#undef LOG_TAG
6817#define LOG_TAG "AudioFlinger::EffectHandle"
6818
6819AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6820 const sp<AudioFlinger::Client>& client,
6821 const sp<IEffectClient>& effectClient,
6822 int32_t priority)
6823 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006824 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006825 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006826{
6827 LOGV("constructor %p", this);
6828
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006829 if (client == 0) {
6830 return;
6831 }
Eric Laurent65b65452010-06-01 23:49:17 -07006832 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6833 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6834 if (mCblkMemory != 0) {
6835 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6836
6837 if (mCblk) {
6838 new(mCblk) effect_param_cblk_t();
6839 mBuffer = (uint8_t *)mCblk + bufOffset;
6840 }
6841 } else {
6842 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6843 return;
6844 }
6845}
6846
6847AudioFlinger::EffectHandle::~EffectHandle()
6848{
6849 LOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006850 disconnect(false);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006851 LOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006852}
6853
6854status_t AudioFlinger::EffectHandle::enable()
6855{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006856 LOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006857 if (!mHasControl) return INVALID_OPERATION;
6858 if (mEffect == 0) return DEAD_OBJECT;
6859
Eric Laurent6752ec82011-08-10 10:37:50 -07006860 if (mEnabled) {
6861 return NO_ERROR;
6862 }
6863
Eric Laurentf82fccd2011-07-27 19:49:51 -07006864 mEnabled = true;
6865
6866 sp<ThreadBase> thread = mEffect->thread().promote();
6867 if (thread != 0) {
6868 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6869 }
6870
6871 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6872 if (mEffect->suspended()) {
6873 return NO_ERROR;
6874 }
6875
Eric Laurent6752ec82011-08-10 10:37:50 -07006876 status_t status = mEffect->setEnabled(true);
6877 if (status != NO_ERROR) {
6878 if (thread != 0) {
6879 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6880 }
6881 mEnabled = false;
6882 }
6883 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006884}
6885
6886status_t AudioFlinger::EffectHandle::disable()
6887{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006888 LOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006889 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006890 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006891
Eric Laurent6752ec82011-08-10 10:37:50 -07006892 if (!mEnabled) {
6893 return NO_ERROR;
6894 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006895 mEnabled = false;
6896
6897 if (mEffect->suspended()) {
6898 return NO_ERROR;
6899 }
6900
6901 status_t status = mEffect->setEnabled(false);
6902
6903 sp<ThreadBase> thread = mEffect->thread().promote();
6904 if (thread != 0) {
6905 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6906 }
6907
6908 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006909}
6910
6911void AudioFlinger::EffectHandle::disconnect()
6912{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006913 disconnect(true);
6914}
6915
6916void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6917{
6918 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006919 if (mEffect == 0) {
6920 return;
6921 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006922 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006923
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006924 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006925 sp<ThreadBase> thread = mEffect->thread().promote();
6926 if (thread != 0) {
6927 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6928 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006929 }
6930
Eric Laurent65b65452010-06-01 23:49:17 -07006931 // release sp on module => module destructor can be called now
6932 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006933 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006934 if (mCblk) {
6935 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6936 }
6937 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006938 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6939 mClient.clear();
6940 }
6941}
6942
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006943status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6944 uint32_t cmdSize,
6945 void *pCmdData,
6946 uint32_t *replySize,
6947 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006948{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006949// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6950// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006951
6952 // only get parameter command is permitted for applications not controlling the effect
6953 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6954 return INVALID_OPERATION;
6955 }
6956 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006957 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006958
6959 // handle commands that are not forwarded transparently to effect engine
6960 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6961 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6962 // no risk to block the whole media server process or mixer threads is we are stuck here
6963 Mutex::Autolock _l(mCblk->lock);
6964 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6965 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6966 mCblk->serverIndex = 0;
6967 mCblk->clientIndex = 0;
6968 return BAD_VALUE;
6969 }
6970 status_t status = NO_ERROR;
6971 while (mCblk->serverIndex < mCblk->clientIndex) {
6972 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006973 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006974 int *p = (int *)(mBuffer + mCblk->serverIndex);
6975 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006976 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6977 LOGW("command(): invalid parameter block size");
6978 break;
6979 }
Eric Laurent65b65452010-06-01 23:49:17 -07006980 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006981 if (param->psize == 0 || param->vsize == 0) {
6982 LOGW("command(): null parameter or value size");
6983 mCblk->serverIndex += size;
6984 continue;
6985 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006986 uint32_t psize = sizeof(effect_param_t) +
6987 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6988 param->vsize;
6989 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6990 psize,
6991 p,
6992 &rsize,
6993 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006994 // stop at first error encountered
6995 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006996 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006997 *(int *)pReplyData = reply;
6998 break;
6999 } else if (reply != NO_ERROR) {
7000 *(int *)pReplyData = reply;
7001 break;
Eric Laurent65b65452010-06-01 23:49:17 -07007002 }
7003 mCblk->serverIndex += size;
7004 }
7005 mCblk->serverIndex = 0;
7006 mCblk->clientIndex = 0;
7007 return status;
7008 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007009 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007010 return enable();
7011 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007012 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007013 return disable();
7014 }
7015
7016 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7017}
7018
7019sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7020 return mCblkMemory;
7021}
7022
Eric Laurentf82fccd2011-07-27 19:49:51 -07007023void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007024{
7025 LOGV("setControl %p control %d", this, hasControl);
7026
7027 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007028 mEnabled = enabled;
7029
Eric Laurent65b65452010-06-01 23:49:17 -07007030 if (signal && mEffectClient != 0) {
7031 mEffectClient->controlStatusChanged(hasControl);
7032 }
7033}
7034
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007035void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7036 uint32_t cmdSize,
7037 void *pCmdData,
7038 uint32_t replySize,
7039 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007040{
7041 if (mEffectClient != 0) {
7042 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7043 }
7044}
7045
7046
7047
7048void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7049{
7050 if (mEffectClient != 0) {
7051 mEffectClient->enableStatusChanged(enabled);
7052 }
7053}
7054
7055status_t AudioFlinger::EffectHandle::onTransact(
7056 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7057{
7058 return BnEffect::onTransact(code, data, reply, flags);
7059}
7060
7061
7062void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7063{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007064 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007065
7066 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7067 (mClient == NULL) ? getpid() : mClient->pid(),
7068 mPriority,
7069 mHasControl,
7070 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007071 mCblk ? mCblk->clientIndex : 0,
7072 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007073 );
7074
7075 if (locked) {
7076 mCblk->lock.unlock();
7077 }
7078}
7079
7080#undef LOG_TAG
7081#define LOG_TAG "AudioFlinger::EffectChain"
7082
7083AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7084 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007085 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007086 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7087 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007088{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007089 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007090 sp<ThreadBase> thread = mThread.promote();
7091 if (thread == 0) {
7092 return;
7093 }
7094 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7095 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007096}
7097
7098AudioFlinger::EffectChain::~EffectChain()
7099{
7100 if (mOwnInBuffer) {
7101 delete mInBuffer;
7102 }
7103
7104}
7105
Eric Laurentf82fccd2011-07-27 19:49:51 -07007106// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007107sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007108{
7109 sp<EffectModule> effect;
7110 size_t size = mEffects.size();
7111
7112 for (size_t i = 0; i < size; i++) {
7113 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7114 effect = mEffects[i];
7115 break;
7116 }
7117 }
7118 return effect;
7119}
7120
Eric Laurentf82fccd2011-07-27 19:49:51 -07007121// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007122sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007123{
7124 sp<EffectModule> effect;
7125 size_t size = mEffects.size();
7126
7127 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007128 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7129 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007130 effect = mEffects[i];
7131 break;
7132 }
7133 }
7134 return effect;
7135}
7136
Eric Laurentf82fccd2011-07-27 19:49:51 -07007137// getEffectFromType_l() must be called with ThreadBase::mLock held
7138sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7139 const effect_uuid_t *type)
7140{
7141 sp<EffectModule> effect;
7142 size_t size = mEffects.size();
7143
7144 for (size_t i = 0; i < size; i++) {
7145 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7146 effect = mEffects[i];
7147 break;
7148 }
7149 }
7150 return effect;
7151}
7152
Eric Laurent65b65452010-06-01 23:49:17 -07007153// Must be called with EffectChain::mLock locked
7154void AudioFlinger::EffectChain::process_l()
7155{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007156 sp<ThreadBase> thread = mThread.promote();
7157 if (thread == 0) {
7158 LOGW("process_l(): cannot promote mixer thread");
7159 return;
7160 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007161 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7162 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007163 // always process effects unless no more tracks are on the session and the effect tail
7164 // has been rendered
7165 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007166 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007167 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007168
Eric Laurentf9c361d2011-11-11 15:42:52 -08007169 if (!tracksOnSession && mTailBufferCount == 0) {
7170 doProcess = false;
7171 }
7172
7173 if (activeTrackCnt() == 0) {
7174 // if no track is active and the effect tail has not been rendered,
7175 // the input buffer must be cleared here as the mixer process will not do it
7176 if (tracksOnSession || mTailBufferCount > 0) {
7177 size_t numSamples = thread->frameCount() * thread->channelCount();
7178 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7179 if (mTailBufferCount > 0) {
7180 mTailBufferCount--;
7181 }
7182 }
7183 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007184 }
7185
Eric Laurent65b65452010-06-01 23:49:17 -07007186 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007187 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007188 for (size_t i = 0; i < size; i++) {
7189 mEffects[i]->process();
7190 }
Eric Laurent65b65452010-06-01 23:49:17 -07007191 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007192 for (size_t i = 0; i < size; i++) {
7193 mEffects[i]->updateState();
7194 }
Eric Laurent65b65452010-06-01 23:49:17 -07007195}
7196
Eric Laurent76c40f72010-07-15 12:50:15 -07007197// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007198status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007199{
7200 effect_descriptor_t desc = effect->desc();
7201 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7202
7203 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007204 effect->setChain(this);
7205 sp<ThreadBase> thread = mThread.promote();
7206 if (thread == 0) {
7207 return NO_INIT;
7208 }
7209 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007210
7211 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7212 // Auxiliary effects are inserted at the beginning of mEffects vector as
7213 // they are processed first and accumulated in chain input buffer
7214 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007215
Eric Laurent65b65452010-06-01 23:49:17 -07007216 // the input buffer for auxiliary effect contains mono samples in
7217 // 32 bit format. This is to avoid saturation in AudoMixer
7218 // accumulation stage. Saturation is done in EffectModule::process() before
7219 // calling the process in effect engine
7220 size_t numSamples = thread->frameCount();
7221 int32_t *buffer = new int32_t[numSamples];
7222 memset(buffer, 0, numSamples * sizeof(int32_t));
7223 effect->setInBuffer((int16_t *)buffer);
7224 // auxiliary effects output samples to chain input buffer for further processing
7225 // by insert effects
7226 effect->setOutBuffer(mInBuffer);
7227 } else {
7228 // Insert effects are inserted at the end of mEffects vector as they are processed
7229 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007230 // Insert effect order as a function of indicated preference:
7231 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7232 // another effect is present
7233 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7234 // last effect claiming first position
7235 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7236 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007237 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007238 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7239 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007240
7241 int size = (int)mEffects.size();
7242 int idx_insert = size;
7243 int idx_insert_first = -1;
7244 int idx_insert_last = -1;
7245
7246 for (int i = 0; i < size; i++) {
7247 effect_descriptor_t d = mEffects[i]->desc();
7248 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7249 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7250 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7251 // check invalid effect chaining combinations
7252 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007253 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007254 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007255 return INVALID_OPERATION;
7256 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007257 // remember position of first insert effect and by default
7258 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007259 if (idx_insert == size) {
7260 idx_insert = i;
7261 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007262 // remember position of last insert effect claiming
7263 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007264 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7265 idx_insert_first = i;
7266 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007267 // remember position of first insert effect claiming
7268 // last position
7269 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7270 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007271 idx_insert_last = i;
7272 }
7273 }
7274 }
7275
Eric Laurent53334cd2010-06-23 17:38:20 -07007276 // modify idx_insert from first position if needed
7277 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7278 if (idx_insert_last != -1) {
7279 idx_insert = idx_insert_last;
7280 } else {
7281 idx_insert = size;
7282 }
7283 } else {
7284 if (idx_insert_first != -1) {
7285 idx_insert = idx_insert_first + 1;
7286 }
Eric Laurent65b65452010-06-01 23:49:17 -07007287 }
7288
7289 // always read samples from chain input buffer
7290 effect->setInBuffer(mInBuffer);
7291
7292 // if last effect in the chain, output samples to chain
7293 // output buffer, otherwise to chain input buffer
7294 if (idx_insert == size) {
7295 if (idx_insert != 0) {
7296 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7297 mEffects[idx_insert-1]->configure();
7298 }
7299 effect->setOutBuffer(mOutBuffer);
7300 } else {
7301 effect->setOutBuffer(mInBuffer);
7302 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007303 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007304
Eric Laurent76c40f72010-07-15 12:50:15 -07007305 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007306 }
7307 effect->configure();
7308 return NO_ERROR;
7309}
7310
Eric Laurent76c40f72010-07-15 12:50:15 -07007311// removeEffect_l() must be called with PlaybackThread::mLock held
7312size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007313{
7314 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007315 int size = (int)mEffects.size();
7316 int i;
7317 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7318
7319 for (i = 0; i < size; i++) {
7320 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007321 // calling stop here will remove pre-processing effect from the audio HAL.
7322 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7323 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007324 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7325 mEffects[i]->state() == EffectModule::STOPPING) {
7326 mEffects[i]->stop();
7327 }
Eric Laurent65b65452010-06-01 23:49:17 -07007328 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7329 delete[] effect->inBuffer();
7330 } else {
7331 if (i == size - 1 && i != 0) {
7332 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7333 mEffects[i - 1]->configure();
7334 }
7335 }
7336 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07007337 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007338 break;
7339 }
7340 }
Eric Laurent65b65452010-06-01 23:49:17 -07007341
7342 return mEffects.size();
7343}
7344
Eric Laurent76c40f72010-07-15 12:50:15 -07007345// setDevice_l() must be called with PlaybackThread::mLock held
7346void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007347{
7348 size_t size = mEffects.size();
7349 for (size_t i = 0; i < size; i++) {
7350 mEffects[i]->setDevice(device);
7351 }
7352}
7353
Eric Laurent76c40f72010-07-15 12:50:15 -07007354// setMode_l() must be called with PlaybackThread::mLock held
7355void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007356{
7357 size_t size = mEffects.size();
7358 for (size_t i = 0; i < size; i++) {
7359 mEffects[i]->setMode(mode);
7360 }
7361}
7362
Eric Laurent76c40f72010-07-15 12:50:15 -07007363// setVolume_l() must be called with PlaybackThread::mLock held
7364bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007365{
7366 uint32_t newLeft = *left;
7367 uint32_t newRight = *right;
7368 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007369 int ctrlIdx = -1;
7370 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007371
Eric Laurent76c40f72010-07-15 12:50:15 -07007372 // first update volume controller
7373 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007374 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007375 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7376 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007377 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007378 break;
7379 }
7380 }
7381
7382 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007383 if (hasControl) {
7384 *left = mNewLeftVolume;
7385 *right = mNewRightVolume;
7386 }
7387 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007388 }
7389
7390 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007391 mLeftVolume = newLeft;
7392 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007393
7394 // second get volume update from volume controller
7395 if (ctrlIdx >= 0) {
7396 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007397 mNewLeftVolume = newLeft;
7398 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007399 }
7400 // then indicate volume to all other effects in chain.
7401 // Pass altered volume to effects before volume controller
7402 // and requested volume to effects after controller
7403 uint32_t lVol = newLeft;
7404 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007405
Eric Laurent65b65452010-06-01 23:49:17 -07007406 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007407 if ((int)i == ctrlIdx) continue;
7408 // this also works for ctrlIdx == -1 when there is no volume controller
7409 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007410 lVol = *left;
7411 rVol = *right;
7412 }
7413 mEffects[i]->setVolume(&lVol, &rVol, false);
7414 }
7415 *left = newLeft;
7416 *right = newRight;
7417
7418 return hasControl;
7419}
7420
Eric Laurent65b65452010-06-01 23:49:17 -07007421status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7422{
7423 const size_t SIZE = 256;
7424 char buffer[SIZE];
7425 String8 result;
7426
7427 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7428 result.append(buffer);
7429
7430 bool locked = tryLock(mLock);
7431 // failed to lock - AudioFlinger is probably deadlocked
7432 if (!locked) {
7433 result.append("\tCould not lock mutex:\n");
7434 }
7435
Eric Laurent76c40f72010-07-15 12:50:15 -07007436 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7437 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007438 mEffects.size(),
7439 (uint32_t)mInBuffer,
7440 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007441 mActiveTrackCnt);
7442 result.append(buffer);
7443 write(fd, result.string(), result.size());
7444
7445 for (size_t i = 0; i < mEffects.size(); ++i) {
7446 sp<EffectModule> effect = mEffects[i];
7447 if (effect != 0) {
7448 effect->dump(fd, args);
7449 }
7450 }
7451
7452 if (locked) {
7453 mLock.unlock();
7454 }
7455
7456 return NO_ERROR;
7457}
7458
Eric Laurentf82fccd2011-07-27 19:49:51 -07007459// must be called with ThreadBase::mLock held
7460void AudioFlinger::EffectChain::setEffectSuspended_l(
7461 const effect_uuid_t *type, bool suspend)
7462{
7463 sp<SuspendedEffectDesc> desc;
7464 // use effect type UUID timelow as key as there is no real risk of identical
7465 // timeLow fields among effect type UUIDs.
7466 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7467 if (suspend) {
7468 if (index >= 0) {
7469 desc = mSuspendedEffects.valueAt(index);
7470 } else {
7471 desc = new SuspendedEffectDesc();
7472 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7473 mSuspendedEffects.add(type->timeLow, desc);
7474 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7475 }
7476 if (desc->mRefCount++ == 0) {
7477 sp<EffectModule> effect = getEffectIfEnabled(type);
7478 if (effect != 0) {
7479 desc->mEffect = effect;
7480 effect->setSuspended(true);
7481 effect->setEnabled(false);
7482 }
7483 }
7484 } else {
7485 if (index < 0) {
7486 return;
7487 }
7488 desc = mSuspendedEffects.valueAt(index);
7489 if (desc->mRefCount <= 0) {
7490 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7491 desc->mRefCount = 1;
7492 }
7493 if (--desc->mRefCount == 0) {
7494 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7495 if (desc->mEffect != 0) {
7496 sp<EffectModule> effect = desc->mEffect.promote();
7497 if (effect != 0) {
7498 effect->setSuspended(false);
7499 sp<EffectHandle> handle = effect->controlHandle();
7500 if (handle != 0) {
7501 effect->setEnabled(handle->enabled());
7502 }
7503 }
7504 desc->mEffect.clear();
7505 }
7506 mSuspendedEffects.removeItemsAt(index);
7507 }
7508 }
7509}
7510
7511// must be called with ThreadBase::mLock held
7512void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7513{
7514 sp<SuspendedEffectDesc> desc;
7515
7516 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7517 if (suspend) {
7518 if (index >= 0) {
7519 desc = mSuspendedEffects.valueAt(index);
7520 } else {
7521 desc = new SuspendedEffectDesc();
7522 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7523 LOGV("setEffectSuspendedAll_l() add entry for 0");
7524 }
7525 if (desc->mRefCount++ == 0) {
7526 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7527 for (size_t i = 0; i < effects.size(); i++) {
7528 setEffectSuspended_l(&effects[i]->desc().type, true);
7529 }
7530 }
7531 } else {
7532 if (index < 0) {
7533 return;
7534 }
7535 desc = mSuspendedEffects.valueAt(index);
7536 if (desc->mRefCount <= 0) {
7537 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7538 desc->mRefCount = 1;
7539 }
7540 if (--desc->mRefCount == 0) {
7541 Vector<const effect_uuid_t *> types;
7542 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7543 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7544 continue;
7545 }
7546 types.add(&mSuspendedEffects.valueAt(i)->mType);
7547 }
7548 for (size_t i = 0; i < types.size(); i++) {
7549 setEffectSuspended_l(types[i], false);
7550 }
7551 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7552 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7553 }
7554 }
7555}
7556
Eric Laurent5e7acae2011-09-23 08:40:41 -07007557
7558// The volume effect is used for automated tests only
7559#ifndef OPENSL_ES_H_
7560static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7561 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7562const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7563#endif //OPENSL_ES_H_
7564
Eric Laurent6752ec82011-08-10 10:37:50 -07007565bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7566{
7567 // auxiliary effects and visualizer are never suspended on output mix
7568 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7569 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007570 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7571 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007572 return false;
7573 }
7574 return true;
7575}
7576
Eric Laurentf82fccd2011-07-27 19:49:51 -07007577Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7578{
7579 Vector< sp<EffectModule> > effects;
7580 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007581 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007582 continue;
7583 }
7584 effects.add(mEffects[i]);
7585 }
7586 return effects;
7587}
7588
7589sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7590 const effect_uuid_t *type)
7591{
7592 sp<EffectModule> effect;
7593 effect = getEffectFromType_l(type);
7594 if (effect != 0 && !effect->isEnabled()) {
7595 effect.clear();
7596 }
7597 return effect;
7598}
7599
7600void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7601 bool enabled)
7602{
7603 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7604 if (enabled) {
7605 if (index < 0) {
7606 // if the effect is not suspend check if all effects are suspended
7607 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7608 if (index < 0) {
7609 return;
7610 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007611 if (!isEffectEligibleForSuspend(effect->desc())) {
7612 return;
7613 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007614 setEffectSuspended_l(&effect->desc().type, enabled);
7615 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007616 if (index < 0) {
7617 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7618 return;
7619 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007620 }
7621 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7622 effect->desc().type.timeLow);
7623 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7624 // if effect is requested to suspended but was not yet enabled, supend it now.
7625 if (desc->mEffect == 0) {
7626 desc->mEffect = effect;
7627 effect->setEnabled(false);
7628 effect->setSuspended(true);
7629 }
7630 } else {
7631 if (index < 0) {
7632 return;
7633 }
7634 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7635 effect->desc().type.timeLow);
7636 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7637 desc->mEffect.clear();
7638 effect->setSuspended(false);
7639 }
7640}
7641
Eric Laurent65b65452010-06-01 23:49:17 -07007642#undef LOG_TAG
7643#define LOG_TAG "AudioFlinger"
7644
Eric Laurenta553c252009-07-17 12:17:14 -07007645// ----------------------------------------------------------------------------
7646
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007647status_t AudioFlinger::onTransact(
7648 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7649{
7650 return BnAudioFlinger::onTransact(code, data, reply, flags);
7651}
7652
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007653}; // namespace android