blob: 8e86eda1522c8dbd388b71f603c102d6ca55ad1a [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 Zavin24fc2fb2011-04-19 22:30:36 -070047#include <hardware/audio_hal.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 Laurentdf9b81c2010-07-02 08:12:41 -070053#include <media/EffectVisualizerApi.h>
Eric Laurent65b65452010-06-01 23:49:17 -070054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055// ----------------------------------------------------------------------------
56// the sim build doesn't have gettid
57
58#ifndef HAVE_GETTID
59# define gettid getpid
60#endif
61
62// ----------------------------------------------------------------------------
63
Eric Laurent8ed6ed02010-07-13 04:45:46 -070064extern const char * const gEffectLibPath;
65
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066namespace android {
67
The Android Open Source Project10592532009-03-18 17:39:46 -070068static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
69static const char* kHardwareLockedString = "Hardware lock is taken\n";
70
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080071//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070073static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080079// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070083
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070084static const int kDumpLockRetries = 50;
85static const int kDumpLockSleep = 20000;
86
Dave Sparksd0ac8c02009-09-30 03:09:03 -070087static const nsecs_t kWarningThrottle = seconds(5);
88
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070090// ----------------------------------------------------------------------------
91
92static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070093 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
94 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
95 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
96 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070097}
98
99static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700100 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
101 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
102 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
103 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700104}
105
Gloria Wang9b3f1522011-02-24 14:51:45 -0800106// To collect the amplifier usage
107static void addBatteryData(uint32_t params) {
108 sp<IBinder> binder =
109 defaultServiceManager()->getService(String16("media.player"));
110 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
111 if (service.get() == NULL) {
112 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
113 return;
114 }
115
116 service->addBatteryData(params);
117}
118
Dima Zavin31f188892011-04-18 16:57:27 -0700119static int load_audio_interface(const char *if_name, const hw_module_t **mod,
120 audio_hw_device_t **dev)
121{
122 int rc;
123
124 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
125 if (rc)
126 goto out;
127
128 rc = audio_hw_device_open(*mod, dev);
129 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
130 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
131 if (rc)
132 goto out;
133
134 return 0;
135
136out:
137 *mod = NULL;
138 *dev = NULL;
139 return rc;
140}
141
142static const char *audio_interfaces[] = {
143 "primary",
144 "a2dp",
145 "usb",
146};
147#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
148
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 : BnAudioFlinger(),
Dima Zavin31f188892011-04-18 16:57:27 -0700153 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700154{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700155}
156
157void AudioFlinger::onFirstRef()
158{
Dima Zavin31f188892011-04-18 16:57:27 -0700159 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700160
Eric Laurent01635942011-01-18 18:39:02 -0800161 Mutex::Autolock _l(mLock);
162
Dima Zavin31f188892011-04-18 16:57:27 -0700163 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700164 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700165
Dima Zavin31f188892011-04-18 16:57:27 -0700166 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
167 const hw_module_t *mod;
168 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700169
Dima Zavin31f188892011-04-18 16:57:27 -0700170 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
171 if (rc)
172 continue;
173
174 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
175 mod->name, mod->id);
176 mAudioHwDevs.push(dev);
177
178 if (!mPrimaryHardwareDev) {
179 mPrimaryHardwareDev = dev;
180 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700181 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700182 }
183 }
Eric Laurenta553c252009-07-17 12:17:14 -0700184
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700185 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700186
Dima Zavin31f188892011-04-18 16:57:27 -0700187 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
188 LOGE("Primary audio interface not found");
189 return;
190 }
191
192 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
193 audio_hw_device_t *dev = mAudioHwDevs[i];
194
195 mHardwareStatus = AUDIO_HW_INIT;
196 rc = dev->init_check(dev);
197 if (rc == 0) {
198 AutoMutex lock(mHardwareLock);
199
200 mMode = AUDIO_MODE_NORMAL;
201 mHardwareStatus = AUDIO_HW_SET_MODE;
202 dev->set_mode(dev, mMode);
203 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
204 dev->set_master_volume(dev, 1.0f);
205 mHardwareStatus = AUDIO_HW_IDLE;
206 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700207 }
208}
209
Dima Zavin2986f5b2011-04-19 19:04:32 -0700210status_t AudioFlinger::initCheck() const
211{
212 Mutex::Autolock _l(mLock);
213 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
214 return NO_INIT;
215 return NO_ERROR;
216}
217
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700218AudioFlinger::~AudioFlinger()
219{
Dima Zavin31f188892011-04-18 16:57:27 -0700220 int num_devs = mAudioHwDevs.size();
221
Eric Laurent7954c462009-08-28 10:39:03 -0700222 while (!mRecordThreads.isEmpty()) {
223 // closeInput() will remove first entry from mRecordThreads
224 closeInput(mRecordThreads.keyAt(0));
225 }
226 while (!mPlaybackThreads.isEmpty()) {
227 // closeOutput() will remove first entry from mPlaybackThreads
228 closeOutput(mPlaybackThreads.keyAt(0));
229 }
Dima Zavin31f188892011-04-18 16:57:27 -0700230
231 for (int i = 0; i < num_devs; i++) {
232 audio_hw_device_t *dev = mAudioHwDevs[i];
233 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700234 }
Dima Zavin31f188892011-04-18 16:57:27 -0700235 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800236}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800237
Dima Zavin31f188892011-04-18 16:57:27 -0700238audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
239{
240 /* first matching HW device is returned */
241 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
242 audio_hw_device_t *dev = mAudioHwDevs[i];
243 if ((dev->get_supported_devices(dev) & devices) == devices)
244 return dev;
245 }
246 return NULL;
247}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700248
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700249status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
250{
251 const size_t SIZE = 256;
252 char buffer[SIZE];
253 String8 result;
254
255 result.append("Clients:\n");
256 for (size_t i = 0; i < mClients.size(); ++i) {
257 wp<Client> wClient = mClients.valueAt(i);
258 if (wClient != 0) {
259 sp<Client> client = wClient.promote();
260 if (client != 0) {
261 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
262 result.append(buffer);
263 }
264 }
265 }
266 write(fd, result.string(), result.size());
267 return NO_ERROR;
268}
269
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700270
271status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
272{
273 const size_t SIZE = 256;
274 char buffer[SIZE];
275 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700276 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700277
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700278 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700279 result.append(buffer);
280 write(fd, result.string(), result.size());
281 return NO_ERROR;
282}
283
284status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
285{
286 const size_t SIZE = 256;
287 char buffer[SIZE];
288 String8 result;
289 snprintf(buffer, SIZE, "Permission Denial: "
290 "can't dump AudioFlinger from pid=%d, uid=%d\n",
291 IPCThreadState::self()->getCallingPid(),
292 IPCThreadState::self()->getCallingUid());
293 result.append(buffer);
294 write(fd, result.string(), result.size());
295 return NO_ERROR;
296}
297
The Android Open Source Project10592532009-03-18 17:39:46 -0700298static bool tryLock(Mutex& mutex)
299{
300 bool locked = false;
301 for (int i = 0; i < kDumpLockRetries; ++i) {
302 if (mutex.tryLock() == NO_ERROR) {
303 locked = true;
304 break;
305 }
306 usleep(kDumpLockSleep);
307 }
308 return locked;
309}
310
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700311status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
312{
313 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
314 dumpPermissionDenial(fd, args);
315 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700316 // get state of hardware lock
317 bool hardwareLocked = tryLock(mHardwareLock);
318 if (!hardwareLocked) {
319 String8 result(kHardwareLockedString);
320 write(fd, result.string(), result.size());
321 } else {
322 mHardwareLock.unlock();
323 }
324
325 bool locked = tryLock(mLock);
326
327 // failed to lock - AudioFlinger is probably deadlocked
328 if (!locked) {
329 String8 result(kDeadlockedString);
330 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700331 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332
333 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700334 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335
Eric Laurenta553c252009-07-17 12:17:14 -0700336 // dump playback threads
337 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700338 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700339 }
340
341 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700342 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700343 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345
Dima Zavin31f188892011-04-18 16:57:27 -0700346 // dump all hardware devs
347 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
348 audio_hw_device_t *dev = mAudioHwDevs[i];
349 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700350 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700351 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700352 }
353 return NO_ERROR;
354}
355
Eric Laurenta553c252009-07-17 12:17:14 -0700356
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700357// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358
359
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700360sp<IAudioTrack> AudioFlinger::createTrack(
361 pid_t pid,
362 int streamType,
363 uint32_t sampleRate,
364 int format,
365 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800366 int frameCount,
367 uint32_t flags,
368 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700369 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700370 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800371 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700372{
Eric Laurenta553c252009-07-17 12:17:14 -0700373 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700375 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800376 wp<Client> wclient;
377 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700378 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700380 if (streamType >= AUDIO_STREAM_CNT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800381 LOGE("invalid stream type");
382 lStatus = BAD_VALUE;
383 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384 }
385
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800386 {
387 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700388 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700389 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700390 if (thread == NULL) {
391 LOGE("unknown output thread");
392 lStatus = BAD_VALUE;
393 goto Exit;
394 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800395
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800396 wclient = mClients.valueFor(pid);
397
398 if (wclient != NULL) {
399 client = wclient.promote();
400 } else {
401 client = new Client(this, pid);
402 mClients.add(pid, client);
403 }
Eric Laurent65b65452010-06-01 23:49:17 -0700404
Eric Laurent65b65452010-06-01 23:49:17 -0700405 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700406 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700407 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700408 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
409 if (mPlaybackThreads.keyAt(i) != output) {
410 // prevent same audio session on different output threads
411 uint32_t sessions = t->hasAudioSession(*sessionId);
412 if (sessions & PlaybackThread::TRACK_SESSION) {
413 lStatus = BAD_VALUE;
414 goto Exit;
415 }
416 // check if an effect with same session ID is waiting for a track to be created
417 if (sessions & PlaybackThread::EFFECT_SESSION) {
418 effectThread = t.get();
419 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700420 }
421 }
Eric Laurent65b65452010-06-01 23:49:17 -0700422 lSessionId = *sessionId;
423 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700424 // if no audio session id is provided, create one here
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800425 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -0700426 if (sessionId != NULL) {
427 *sessionId = lSessionId;
428 }
429 }
430 LOGV("createTrack() lSessionId: %d", lSessionId);
431
Eric Laurenta553c252009-07-17 12:17:14 -0700432 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700433 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700434
435 // move effect chain to this output thread if an effect on same session was waiting
436 // for a track to be created
437 if (lStatus == NO_ERROR && effectThread != NULL) {
438 Mutex::Autolock _dl(thread->mLock);
439 Mutex::Autolock _sl(effectThread->mLock);
440 moveEffectChain_l(lSessionId, effectThread, thread, true);
441 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700442 }
443 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800444 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700445 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700446 // remove local strong reference to Client before deleting the Track so that the Client
447 // destructor is called by the TrackBase destructor with mLock held
448 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700449 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800450 }
451
452Exit:
453 if(status) {
454 *status = lStatus;
455 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700456 return trackHandle;
457}
458
Eric Laurentddb78e72009-07-28 08:44:33 -0700459uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700460{
Eric Laurenta553c252009-07-17 12:17:14 -0700461 Mutex::Autolock _l(mLock);
462 PlaybackThread *thread = checkPlaybackThread_l(output);
463 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700464 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700465 return 0;
466 }
467 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700468}
469
Eric Laurentddb78e72009-07-28 08:44:33 -0700470int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700471{
Eric Laurenta553c252009-07-17 12:17:14 -0700472 Mutex::Autolock _l(mLock);
473 PlaybackThread *thread = checkPlaybackThread_l(output);
474 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700475 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700476 return 0;
477 }
478 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479}
480
Eric Laurentddb78e72009-07-28 08:44:33 -0700481int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482{
Eric Laurenta553c252009-07-17 12:17:14 -0700483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700486 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700487 return 0;
488 }
489 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490}
491
Eric Laurentddb78e72009-07-28 08:44:33 -0700492size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700493{
Eric Laurenta553c252009-07-17 12:17:14 -0700494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700497 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700498 return 0;
499 }
500 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501}
502
Eric Laurentddb78e72009-07-28 08:44:33 -0700503uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800504{
Eric Laurenta553c252009-07-17 12:17:14 -0700505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700508 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700509 return 0;
510 }
511 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800512}
513
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514status_t AudioFlinger::setMasterVolume(float value)
515{
516 // check calling permissions
517 if (!settingsAllowed()) {
518 return PERMISSION_DENIED;
519 }
520
521 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800522 { // scope for the lock
523 AutoMutex lock(mHardwareLock);
524 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700525 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800526 value = 1.0f;
527 }
528 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700529 }
Eric Laurenta553c252009-07-17 12:17:14 -0700530
Eric Laurent01635942011-01-18 18:39:02 -0800531 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700532 mMasterVolume = value;
533 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700534 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700535
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536 return NO_ERROR;
537}
538
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700539status_t AudioFlinger::setMode(int mode)
540{
Eric Laurent53334cd2010-06-23 17:38:20 -0700541 status_t ret;
542
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700543 // check calling permissions
544 if (!settingsAllowed()) {
545 return PERMISSION_DENIED;
546 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700547 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700548 LOGW("Illegal value: setMode(%d)", mode);
549 return BAD_VALUE;
550 }
551
Eric Laurent53334cd2010-06-23 17:38:20 -0700552 { // scope for the lock
553 AutoMutex lock(mHardwareLock);
554 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700555 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700556 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800557 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700558
559 if (NO_ERROR == ret) {
560 Mutex::Autolock _l(mLock);
561 mMode = mode;
562 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
563 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700564 }
565
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700566 return ret;
567}
568
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700569status_t AudioFlinger::setMicMute(bool state)
570{
571 // check calling permissions
572 if (!settingsAllowed()) {
573 return PERMISSION_DENIED;
574 }
575
576 AutoMutex lock(mHardwareLock);
577 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700578 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 mHardwareStatus = AUDIO_HW_IDLE;
580 return ret;
581}
582
583bool AudioFlinger::getMicMute() const
584{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700585 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700587 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700588 mHardwareStatus = AUDIO_HW_IDLE;
589 return state;
590}
591
592status_t AudioFlinger::setMasterMute(bool muted)
593{
594 // check calling permissions
595 if (!settingsAllowed()) {
596 return PERMISSION_DENIED;
597 }
Eric Laurenta553c252009-07-17 12:17:14 -0700598
Eric Laurent01635942011-01-18 18:39:02 -0800599 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700600 mMasterMute = muted;
601 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700602 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700603
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700604 return NO_ERROR;
605}
606
607float AudioFlinger::masterVolume() const
608{
Eric Laurenta553c252009-07-17 12:17:14 -0700609 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700610}
611
612bool AudioFlinger::masterMute() const
613{
Eric Laurenta553c252009-07-17 12:17:14 -0700614 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700615}
616
Eric Laurentddb78e72009-07-28 08:44:33 -0700617status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700618{
619 // check calling permissions
620 if (!settingsAllowed()) {
621 return PERMISSION_DENIED;
622 }
623
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700624 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625 return BAD_VALUE;
626 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800627
Eric Laurenta553c252009-07-17 12:17:14 -0700628 AutoMutex lock(mLock);
629 PlaybackThread *thread = NULL;
630 if (output) {
631 thread = checkPlaybackThread_l(output);
632 if (thread == NULL) {
633 return BAD_VALUE;
634 }
635 }
636
Eric Laurenta553c252009-07-17 12:17:14 -0700637 mStreamTypes[stream].volume = value;
638
639 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700640 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700641 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700642 }
Eric Laurenta553c252009-07-17 12:17:14 -0700643 } else {
644 thread->setStreamVolume(stream, value);
645 }
Eric Laurentef028272009-04-21 07:56:33 -0700646
Eric Laurent415f3e22009-10-21 08:14:22 -0700647 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700648}
649
650status_t AudioFlinger::setStreamMute(int stream, bool muted)
651{
652 // check calling permissions
653 if (!settingsAllowed()) {
654 return PERMISSION_DENIED;
655 }
656
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700657 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
658 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700659 return BAD_VALUE;
660 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700661
Eric Laurent01635942011-01-18 18:39:02 -0800662 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700663 mStreamTypes[stream].mute = muted;
664 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700665 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700667 return NO_ERROR;
668}
669
Eric Laurentddb78e72009-07-28 08:44:33 -0700670float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700671{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700672 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700673 return 0.0f;
674 }
Eric Laurenta553c252009-07-17 12:17:14 -0700675
676 AutoMutex lock(mLock);
677 float volume;
678 if (output) {
679 PlaybackThread *thread = checkPlaybackThread_l(output);
680 if (thread == NULL) {
681 return 0.0f;
682 }
683 volume = thread->streamVolume(stream);
684 } else {
685 volume = mStreamTypes[stream].volume;
686 }
687
Eric Laurentef028272009-04-21 07:56:33 -0700688 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700689}
690
691bool AudioFlinger::streamMute(int stream) const
692{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700693 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700694 return true;
695 }
Eric Laurenta553c252009-07-17 12:17:14 -0700696
697 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700698}
699
Eric Laurentddb78e72009-07-28 08:44:33 -0700700status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700701{
Eric Laurenta553c252009-07-17 12:17:14 -0700702 status_t result;
703
Eric Laurentddb78e72009-07-28 08:44:33 -0700704 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700705 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
706 // check calling permissions
707 if (!settingsAllowed()) {
708 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800709 }
Eric Laurenta553c252009-07-17 12:17:14 -0700710
711 // ioHandle == 0 means the parameters are global to the audio hardware interface
712 if (ioHandle == 0) {
713 AutoMutex lock(mHardwareLock);
714 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700715 status_t final_result = NO_ERROR;
716 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
717 audio_hw_device_t *dev = mAudioHwDevs[i];
718 result = dev->set_parameters(dev, keyValuePairs.string());
719 final_result = result ?: final_result;
720 }
Eric Laurenta553c252009-07-17 12:17:14 -0700721 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -0700722 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700723 }
724
Eric Laurentb7d94602009-09-29 11:12:57 -0700725 // hold a strong ref on thread in case closeOutput() or closeInput() is called
726 // and the thread is exited once the lock is released
727 sp<ThreadBase> thread;
728 {
729 Mutex::Autolock _l(mLock);
730 thread = checkPlaybackThread_l(ioHandle);
731 if (thread == NULL) {
732 thread = checkRecordThread_l(ioHandle);
733 }
Eric Laurenta553c252009-07-17 12:17:14 -0700734 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700735 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800736 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800737 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700738 }
Eric Laurenta553c252009-07-17 12:17:14 -0700739 return BAD_VALUE;
740}
741
Eric Laurentddb78e72009-07-28 08:44:33 -0700742String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700743{
Eric Laurentddb78e72009-07-28 08:44:33 -0700744// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700745// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
746
747 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700748 String8 out_s8;
749
Dima Zavin31f188892011-04-18 16:57:27 -0700750 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
751 audio_hw_device_t *dev = mAudioHwDevs[i];
752 char *s = dev->get_parameters(dev, keys.string());
753 out_s8 += String8(s);
754 free(s);
755 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700756 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700757 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700758
759 Mutex::Autolock _l(mLock);
760
Eric Laurenta553c252009-07-17 12:17:14 -0700761 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
762 if (playbackThread != NULL) {
763 return playbackThread->getParameters(keys);
764 }
765 RecordThread *recordThread = checkRecordThread_l(ioHandle);
766 if (recordThread != NULL) {
767 return recordThread->getParameters(keys);
768 }
769 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700770}
771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
773{
Dima Zavin31f188892011-04-18 16:57:27 -0700774 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775}
776
Eric Laurent47d0a922010-02-26 02:47:27 -0800777unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
778{
779 if (ioHandle == 0) {
780 return 0;
781 }
782
783 Mutex::Autolock _l(mLock);
784
785 RecordThread *recordThread = checkRecordThread_l(ioHandle);
786 if (recordThread != NULL) {
787 return recordThread->getInputFramesLost();
788 }
789 return 0;
790}
791
Eric Laurent415f3e22009-10-21 08:14:22 -0700792status_t AudioFlinger::setVoiceVolume(float value)
793{
794 // check calling permissions
795 if (!settingsAllowed()) {
796 return PERMISSION_DENIED;
797 }
798
799 AutoMutex lock(mHardwareLock);
800 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700801 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700802 mHardwareStatus = AUDIO_HW_IDLE;
803
804 return ret;
805}
806
Eric Laurent0986e792010-01-19 17:37:09 -0800807status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
808{
809 status_t status;
810
811 Mutex::Autolock _l(mLock);
812
813 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
814 if (playbackThread != NULL) {
815 return playbackThread->getRenderPosition(halFrames, dspFrames);
816 }
817
818 return BAD_VALUE;
819}
820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
822{
Eric Laurenta553c252009-07-17 12:17:14 -0700823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 Mutex::Autolock _l(mLock);
825
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700826 int pid = IPCThreadState::self()->getCallingPid();
827 if (mNotificationClients.indexOfKey(pid) < 0) {
828 sp<NotificationClient> notificationClient = new NotificationClient(this,
829 client,
830 pid);
831 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700832
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700833 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700834
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700835 sp<IBinder> binder = client->asBinder();
836 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700838 // the config change is always sent from playback or record threads to avoid deadlock
839 // with AudioSystem::gLock
840 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
841 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
842 }
Eric Laurenta553c252009-07-17 12:17:14 -0700843
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700844 for (size_t i = 0; i < mRecordThreads.size(); i++) {
845 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
847 }
848}
849
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700850void AudioFlinger::removeNotificationClient(pid_t pid)
851{
852 Mutex::Autolock _l(mLock);
853
854 int index = mNotificationClients.indexOfKey(pid);
855 if (index >= 0) {
856 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
857 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700858 mNotificationClients.removeItem(pid);
859 }
860}
861
Eric Laurent296a0ec2009-09-15 07:10:12 -0700862// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700863void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
864{
Eric Laurent49f02be2009-11-19 09:00:56 -0800865 size_t size = mNotificationClients.size();
866 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700867 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700868 }
869}
870
Eric Laurentb9481d82009-09-17 05:12:56 -0700871// removeClient_l() must be called with AudioFlinger::mLock held
872void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700873{
Eric Laurentb9481d82009-09-17 05:12:56 -0700874 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 -0700875 mClients.removeItem(pid);
876}
877
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700878
Eric Laurenta553c252009-07-17 12:17:14 -0700879// ----------------------------------------------------------------------------
880
Eric Laurent49f02be2009-11-19 09:00:56 -0800881AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700882 : Thread(false),
883 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700884 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700885{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886}
887
Eric Laurenta553c252009-07-17 12:17:14 -0700888AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700890 mParamCond.broadcast();
891 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892}
893
Eric Laurenta553c252009-07-17 12:17:14 -0700894void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700895{
Eric Laurentb7d94602009-09-29 11:12:57 -0700896 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700897 // destroyed in the middle of requestExitAndWait()
898 sp <ThreadBase> strongMe = this;
899
900 LOGV("ThreadBase::exit");
901 {
902 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800903 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700904 requestExit();
905 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700906 }
Eric Laurenta553c252009-07-17 12:17:14 -0700907 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700908}
Eric Laurenta553c252009-07-17 12:17:14 -0700909
910uint32_t AudioFlinger::ThreadBase::sampleRate() const
911{
912 return mSampleRate;
913}
914
915int AudioFlinger::ThreadBase::channelCount() const
916{
Eric Laurentb0a01472010-05-14 05:45:46 -0700917 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700918}
919
920int AudioFlinger::ThreadBase::format() const
921{
922 return mFormat;
923}
924
925size_t AudioFlinger::ThreadBase::frameCount() const
926{
927 return mFrameCount;
928}
929
930status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
931{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700932 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700933
Eric Laurent8fce46a2009-08-04 09:45:33 -0700934 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700935 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700936
Eric Laurent8fce46a2009-08-04 09:45:33 -0700937 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700938 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700939 // wait condition with timeout in case the thread loop has exited
940 // before the request could be processed
941 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
942 status = mParamStatus;
943 mWaitWorkCV.signal();
944 } else {
945 status = TIMED_OUT;
946 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700947 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700948}
949
950void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
951{
952 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700953 sendConfigEvent_l(event, param);
954}
955
956// sendConfigEvent_l() must be called with ThreadBase::mLock held
957void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
958{
Eric Laurenta553c252009-07-17 12:17:14 -0700959 ConfigEvent *configEvent = new ConfigEvent();
960 configEvent->mEvent = event;
961 configEvent->mParam = param;
962 mConfigEvents.add(configEvent);
963 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
964 mWaitWorkCV.signal();
965}
966
967void AudioFlinger::ThreadBase::processConfigEvents()
968{
969 mLock.lock();
970 while(!mConfigEvents.isEmpty()) {
971 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
972 ConfigEvent *configEvent = mConfigEvents[0];
973 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700974 // release mLock before locking AudioFlinger mLock: lock order is always
975 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700976 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700977 mAudioFlinger->mLock.lock();
978 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
979 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700980 delete configEvent;
981 mLock.lock();
982 }
983 mLock.unlock();
984}
985
Eric Laurent3fdb1262009-11-07 00:01:32 -0800986status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
987{
988 const size_t SIZE = 256;
989 char buffer[SIZE];
990 String8 result;
991
992 bool locked = tryLock(mLock);
993 if (!locked) {
994 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
995 write(fd, buffer, strlen(buffer));
996 }
997
998 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
999 result.append(buffer);
1000 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1001 result.append(buffer);
1002 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1003 result.append(buffer);
1004 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1005 result.append(buffer);
1006 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1007 result.append(buffer);
1008 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1009 result.append(buffer);
1010
1011 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1012 result.append(buffer);
1013 result.append(" Index Command");
1014 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1015 snprintf(buffer, SIZE, "\n %02d ", i);
1016 result.append(buffer);
1017 result.append(mNewParameters[i]);
1018 }
1019
1020 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1021 result.append(buffer);
1022 snprintf(buffer, SIZE, " Index event param\n");
1023 result.append(buffer);
1024 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1025 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1026 result.append(buffer);
1027 }
1028 result.append("\n");
1029
1030 write(fd, result.string(), result.size());
1031
1032 if (locked) {
1033 mLock.unlock();
1034 }
1035 return NO_ERROR;
1036}
1037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038
1039// ----------------------------------------------------------------------------
1040
Dima Zavin31f188892011-04-18 16:57:27 -07001041AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -08001042 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -07001043 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -07001044 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1045 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046{
Eric Laurenta553c252009-07-17 12:17:14 -07001047 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048
Eric Laurenta553c252009-07-17 12:17:14 -07001049 mMasterVolume = mAudioFlinger->masterVolume();
1050 mMasterMute = mAudioFlinger->masterMute();
1051
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001052 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001053 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1054 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056}
1057
Eric Laurenta553c252009-07-17 12:17:14 -07001058AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059{
1060 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061}
1062
Eric Laurenta553c252009-07-17 12:17:14 -07001063status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064{
1065 dumpInternals(fd, args);
1066 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001067 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 return NO_ERROR;
1069}
1070
Eric Laurenta553c252009-07-17 12:17:14 -07001071status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072{
1073 const size_t SIZE = 256;
1074 char buffer[SIZE];
1075 String8 result;
1076
Eric Laurenta553c252009-07-17 12:17:14 -07001077 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001079 result.append(" Name Clien Typ Fmt Chn 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 -08001080 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001081 sp<Track> track = mTracks[i];
1082 if (track != 0) {
1083 track->dump(buffer, SIZE);
1084 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086 }
1087
Eric Laurenta553c252009-07-17 12:17:14 -07001088 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001090 result.append(" Name Clien Typ Fmt Chn 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 -08001091 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001092 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 if (wTrack != 0) {
1094 sp<Track> track = wTrack.promote();
1095 if (track != 0) {
1096 track->dump(buffer, SIZE);
1097 result.append(buffer);
1098 }
1099 }
1100 }
1101 write(fd, result.string(), result.size());
1102 return NO_ERROR;
1103}
1104
Eric Laurent65b65452010-06-01 23:49:17 -07001105status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1106{
1107 const size_t SIZE = 256;
1108 char buffer[SIZE];
1109 String8 result;
1110
1111 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1112 write(fd, buffer, strlen(buffer));
1113
1114 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1115 sp<EffectChain> chain = mEffectChains[i];
1116 if (chain != 0) {
1117 chain->dump(fd, args);
1118 }
1119 }
1120 return NO_ERROR;
1121}
1122
Eric Laurenta553c252009-07-17 12:17:14 -07001123status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124{
1125 const size_t SIZE = 256;
1126 char buffer[SIZE];
1127 String8 result;
1128
Eric Laurent3fdb1262009-11-07 00:01:32 -08001129 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 result.append(buffer);
1131 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1132 result.append(buffer);
1133 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1134 result.append(buffer);
1135 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1136 result.append(buffer);
1137 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1138 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001139 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1140 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001141 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1142 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001144
1145 dumpBase(fd, args);
1146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 return NO_ERROR;
1148}
1149
1150// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001151status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152{
1153 if (mSampleRate == 0) {
1154 LOGE("No working audio driver found.");
1155 return NO_INIT;
1156 }
Eric Laurenta553c252009-07-17 12:17:14 -07001157 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 return NO_ERROR;
1159}
1160
Eric Laurenta553c252009-07-17 12:17:14 -07001161void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162{
1163 const size_t SIZE = 256;
1164 char buffer[SIZE];
1165
Eric Laurenta553c252009-07-17 12:17:14 -07001166 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167
1168 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1169}
1170
Eric Laurenta553c252009-07-17 12:17:14 -07001171// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1172sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 const sp<AudioFlinger::Client>& client,
1174 int streamType,
1175 uint32_t sampleRate,
1176 int format,
1177 int channelCount,
1178 int frameCount,
1179 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001180 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 status_t *status)
1182{
1183 sp<Track> track;
1184 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001185
1186 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001187 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001188 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1189 sampleRate, format, channelCount, mOutput);
1190 lStatus = BAD_VALUE;
1191 goto Exit;
1192 }
1193 } else {
1194 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1195 if (sampleRate > mSampleRate*2) {
1196 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1197 lStatus = BAD_VALUE;
1198 goto Exit;
1199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201
Eric Laurenta553c252009-07-17 12:17:14 -07001202 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001203 LOGE("Audio driver not initialized.");
1204 lStatus = NO_INIT;
1205 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207
Eric Laurenta553c252009-07-17 12:17:14 -07001208 { // scope for mLock
1209 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001210
1211 // all tracks in same audio session must share the same routing strategy otherwise
1212 // conflicts will happen when tracks are moved from one output to another by audio policy
1213 // manager
1214 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001215 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001216 for (size_t i = 0; i < mTracks.size(); ++i) {
1217 sp<Track> t = mTracks[i];
1218 if (t != 0) {
1219 if (sessionId == t->sessionId() &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001220 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001221 lStatus = BAD_VALUE;
1222 goto Exit;
1223 }
1224 }
1225 }
1226
Eric Laurenta553c252009-07-17 12:17:14 -07001227 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001228 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001229 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001230 lStatus = NO_MEMORY;
1231 goto Exit;
1232 }
1233 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001234
1235 sp<EffectChain> chain = getEffectChain_l(sessionId);
1236 if (chain != 0) {
1237 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1238 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001239 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001240 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001241 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001242 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001243 lStatus = NO_ERROR;
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245Exit:
1246 if(status) {
1247 *status = lStatus;
1248 }
1249 return track;
1250}
1251
Eric Laurenta553c252009-07-17 12:17:14 -07001252uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253{
1254 if (mOutput) {
Dima Zavin31f188892011-04-18 16:57:27 -07001255 return mOutput->stream->get_latency(mOutput->stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
1257 else {
1258 return 0;
1259 }
1260}
1261
Eric Laurenta553c252009-07-17 12:17:14 -07001262status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263{
1264 mMasterVolume = value;
1265 return NO_ERROR;
1266}
1267
Eric Laurenta553c252009-07-17 12:17:14 -07001268status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269{
1270 mMasterMute = muted;
1271 return NO_ERROR;
1272}
1273
Eric Laurenta553c252009-07-17 12:17:14 -07001274float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275{
1276 return mMasterVolume;
1277}
1278
Eric Laurenta553c252009-07-17 12:17:14 -07001279bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280{
1281 return mMasterMute;
1282}
1283
Eric Laurenta553c252009-07-17 12:17:14 -07001284status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285{
1286 mStreamTypes[stream].volume = value;
1287 return NO_ERROR;
1288}
1289
Eric Laurenta553c252009-07-17 12:17:14 -07001290status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291{
1292 mStreamTypes[stream].mute = muted;
1293 return NO_ERROR;
1294}
1295
Eric Laurenta553c252009-07-17 12:17:14 -07001296float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297{
1298 return mStreamTypes[stream].volume;
1299}
1300
Eric Laurenta553c252009-07-17 12:17:14 -07001301bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302{
1303 return mStreamTypes[stream].mute;
1304}
1305
Eric Laurenta553c252009-07-17 12:17:14 -07001306// addTrack_l() must be called with ThreadBase::mLock held
1307status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308{
1309 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001310
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001311 // set retry count for buffer fill
1312 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001313 if (mActiveTracks.indexOf(track) < 0) {
1314 // the track is newly added, make sure it fills up all its
1315 // buffers before playing. This is to ensure the client will
1316 // effectively get the latency it requested.
1317 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001318 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001319 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001320 if (track->mainBuffer() != mMixBuffer) {
1321 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1322 if (chain != 0) {
1323 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001324 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001325 }
1326 }
1327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001329 }
Eric Laurenta553c252009-07-17 12:17:14 -07001330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001332 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333
1334 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001335}
1336
Eric Laurenta553c252009-07-17 12:17:14 -07001337// destroyTrack_l() must be called with ThreadBase::mLock held
1338void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001339{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001340 track->mState = TrackBase::TERMINATED;
1341 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001342 removeTrack_l(track);
1343 }
1344}
1345
1346void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1347{
1348 mTracks.remove(track);
1349 deleteTrackName_l(track->name());
1350 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1351 if (chain != 0) {
1352 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001353 }
1354}
1355
Eric Laurenta553c252009-07-17 12:17:14 -07001356String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001357{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001358 String8 out_s8;
1359 char *s;
1360
Dima Zavin31f188892011-04-18 16:57:27 -07001361 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001362 out_s8 = String8(s);
1363 free(s);
1364 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001365}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001366
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001367// destroyTrack_l() must be called with AudioFlinger::mLock held
1368void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001369 AudioSystem::OutputDescriptor desc;
1370 void *param2 = 0;
1371
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001372 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001373
1374 switch (event) {
1375 case AudioSystem::OUTPUT_OPENED:
1376 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001377 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001378 desc.samplingRate = mSampleRate;
1379 desc.format = mFormat;
1380 desc.frameCount = mFrameCount;
1381 desc.latency = latency();
1382 param2 = &desc;
1383 break;
1384
1385 case AudioSystem::STREAM_CONFIG_CHANGED:
1386 param2 = &param;
1387 case AudioSystem::OUTPUT_CLOSED:
1388 default:
1389 break;
1390 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001391 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001392}
1393
1394void AudioFlinger::PlaybackThread::readOutputParameters()
1395{
Dima Zavin31f188892011-04-18 16:57:27 -07001396 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1397 mChannels = mOutput->stream->common.get_channels(&mOutput->stream->common);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001398 mChannelCount = (uint16_t)popcount(mChannels);
Dima Zavin31f188892011-04-18 16:57:27 -07001399 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1400 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1401 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001402
Eric Laurenta553c252009-07-17 12:17:14 -07001403 // FIXME - Current mixer implementation only supports stereo output: Always
1404 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001405 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001406 mMixBuffer = new int16_t[mFrameCount * 2];
1407 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001408
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001409 // force reconfiguration of effect chains and engines to take new buffer size and audio
1410 // parameters into account
1411 // Note that mLock is not held when readOutputParameters() is called from the constructor
1412 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1413 // matter.
1414 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1415 Vector< sp<EffectChain> > effectChains = mEffectChains;
1416 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001417 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001418 }
Eric Laurenta553c252009-07-17 12:17:14 -07001419}
1420
Eric Laurent0986e792010-01-19 17:37:09 -08001421status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1422{
1423 if (halFrames == 0 || dspFrames == 0) {
1424 return BAD_VALUE;
1425 }
1426 if (mOutput == 0) {
1427 return INVALID_OPERATION;
1428 }
Dima Zavin31f188892011-04-18 16:57:27 -07001429 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001430
Dima Zavin31f188892011-04-18 16:57:27 -07001431 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001432}
1433
Eric Laurent493941b2010-07-28 01:32:47 -07001434uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001435{
1436 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001437 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001438 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001439 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001440 }
1441
1442 for (size_t i = 0; i < mTracks.size(); ++i) {
1443 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001444 if (sessionId == track->sessionId() &&
1445 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001446 result |= TRACK_SESSION;
1447 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001448 }
1449 }
1450
Eric Laurent493941b2010-07-28 01:32:47 -07001451 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001452}
1453
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001454uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1455{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001456 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001457 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001458 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1459 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001460 }
1461 for (size_t i = 0; i < mTracks.size(); i++) {
1462 sp<Track> track = mTracks[i];
1463 if (sessionId == track->sessionId() &&
1464 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001465 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001466 }
1467 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001468 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001469}
1470
Eric Laurent65b65452010-06-01 23:49:17 -07001471sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1472{
1473 Mutex::Autolock _l(mLock);
1474 return getEffectChain_l(sessionId);
1475}
1476
1477sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1478{
1479 sp<EffectChain> chain;
1480
1481 size_t size = mEffectChains.size();
1482 for (size_t i = 0; i < size; i++) {
1483 if (mEffectChains[i]->sessionId() == sessionId) {
1484 chain = mEffectChains[i];
1485 break;
1486 }
1487 }
1488 return chain;
1489}
1490
Eric Laurent53334cd2010-06-23 17:38:20 -07001491void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1492{
1493 Mutex::Autolock _l(mLock);
1494 size_t size = mEffectChains.size();
1495 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001496 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001497 }
1498}
1499
Eric Laurenta553c252009-07-17 12:17:14 -07001500// ----------------------------------------------------------------------------
1501
Dima Zavin31f188892011-04-18 16:57:27 -07001502AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001503 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001504 mAudioMixer(0)
1505{
1506 mType = PlaybackThread::MIXER;
1507 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1508
1509 // FIXME - Current mixer implementation only supports stereo output
1510 if (mChannelCount == 1) {
1511 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001513}
1514
Eric Laurenta553c252009-07-17 12:17:14 -07001515AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001516{
Eric Laurenta553c252009-07-17 12:17:14 -07001517 delete mAudioMixer;
1518}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519
Eric Laurenta553c252009-07-17 12:17:14 -07001520bool AudioFlinger::MixerThread::threadLoop()
1521{
Eric Laurenta553c252009-07-17 12:17:14 -07001522 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001523 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001524 nsecs_t standbyTime = systemTime();
1525 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001526 // FIXME: Relaxed timing because of a certain device that can't meet latency
1527 // Should be reduced to 2x after the vendor fixes the driver issue
1528 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1529 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001530 bool longStandbyExit = false;
1531 uint32_t activeSleepTime = activeSleepTimeUs();
1532 uint32_t idleSleepTime = idleSleepTimeUs();
1533 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001534 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535
Eric Laurenta553c252009-07-17 12:17:14 -07001536 while (!exitPending())
1537 {
1538 processConfigEvents();
1539
Eric Laurent059b4be2009-11-09 23:32:22 -08001540 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001541 { // scope for mLock
1542
1543 Mutex::Autolock _l(mLock);
1544
1545 if (checkForNewParameters_l()) {
1546 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001547 // FIXME: Relaxed timing because of a certain device that can't meet latency
1548 // Should be reduced to 2x after the vendor fixes the driver issue
1549 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001550 activeSleepTime = activeSleepTimeUs();
1551 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001552 }
1553
1554 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1555
1556 // put audio hardware into standby after short delay
1557 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1558 mSuspended) {
1559 if (!mStandby) {
1560 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001561 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001562 mStandby = true;
1563 mBytesWritten = 0;
1564 }
1565
1566 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1567 // we're about to wait, flush the binder command buffer
1568 IPCThreadState::self()->flushCommands();
1569
1570 if (exitPending()) break;
1571
1572 // wait until we have something to do...
1573 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1574 mWaitWorkCV.wait(mLock);
1575 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1576
1577 if (mMasterMute == false) {
1578 char value[PROPERTY_VALUE_MAX];
1579 property_get("ro.audio.silent", value, "0");
1580 if (atoi(value)) {
1581 LOGD("Silence is golden");
1582 setMasterMute(true);
1583 }
1584 }
1585
1586 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001587 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001588 continue;
1589 }
1590 }
1591
Eric Laurent059b4be2009-11-09 23:32:22 -08001592 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001593
1594 // prevent any changes in effect chain list and in each effect chain
1595 // during mixing and effect process as the audio buffers could be deleted
1596 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001597 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001598 }
1599
Eric Laurent059b4be2009-11-09 23:32:22 -08001600 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001601 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001602 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001603 sleepTime = 0;
1604 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001605 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001606 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001607 // If no tracks are ready, sleep once for the duration of an output
1608 // buffer size, then write 0s to the output
1609 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001610 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1611 sleepTime = activeSleepTime;
1612 } else {
1613 sleepTime = idleSleepTime;
1614 }
1615 } else if (mBytesWritten != 0 ||
1616 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001617 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001618 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001619 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001620 }
Eric Laurent65b65452010-06-01 23:49:17 -07001621 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001622 }
1623
1624 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001625 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001626 }
1627 // sleepTime == 0 means we must write to audio hardware
1628 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001629 for (size_t i = 0; i < effectChains.size(); i ++) {
1630 effectChains[i]->process_l();
1631 }
1632 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001633 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07001634 mLastWriteTime = systemTime();
1635 mInWrite = true;
1636 mBytesWritten += mixBufferSize;
1637
Dima Zavin31f188892011-04-18 16:57:27 -07001638 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001639 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001640 mNumWrites++;
1641 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001642 nsecs_t now = systemTime();
1643 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001644 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001645 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001646 if ((now - lastWarning) > kWarningThrottle) {
1647 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1648 ns2ms(delta), mNumDelayedWrites, this);
1649 lastWarning = now;
1650 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001651 if (mStandby) {
1652 longStandbyExit = true;
1653 }
Eric Laurenta553c252009-07-17 12:17:14 -07001654 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001655 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001656 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001657 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001658 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001659 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001660 }
1661
1662 // finally let go of all our tracks, without the lock held
1663 // since we can't guarantee the destructors won't acquire that
1664 // same lock.
1665 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001666
1667 // Effect chains will be actually deleted here if they were removed from
1668 // mEffectChains list during mixing or effects processing
1669 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001670 }
1671
1672 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07001673 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001674 }
Eric Laurenta553c252009-07-17 12:17:14 -07001675
1676 LOGV("MixerThread %p exiting", this);
1677 return false;
1678}
1679
1680// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001681uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001682{
1683
Eric Laurent059b4be2009-11-09 23:32:22 -08001684 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001685 // find out which tracks need to be processed
1686 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001687 size_t mixedTracks = 0;
1688 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001689
1690 float masterVolume = mMasterVolume;
1691 bool masterMute = mMasterMute;
1692
Eric Laurent8cc93b92010-08-11 05:20:11 -07001693 if (masterMute) {
1694 masterVolume = 0;
1695 }
Eric Laurent65b65452010-06-01 23:49:17 -07001696 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001697 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001698 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001699 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001700 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001701 masterVolume = (float)((v + (1 << 23)) >> 24);
1702 chain.clear();
1703 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001704
Eric Laurenta553c252009-07-17 12:17:14 -07001705 for (size_t i=0 ; i<count ; i++) {
1706 sp<Track> t = activeTracks[i].promote();
1707 if (t == 0) continue;
1708
1709 Track* const track = t.get();
1710 audio_track_cblk_t* cblk = track->cblk();
1711
1712 // The first time a track is added we wait
1713 // for all its buffers to be filled before processing it
1714 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001715 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001716 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001717 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001718 //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 -07001719
Eric Laurent65b65452010-06-01 23:49:17 -07001720 mixedTracks++;
1721
1722 // track->mainBuffer() != mMixBuffer means there is an effect chain
1723 // connected to the track
1724 chain.clear();
1725 if (track->mainBuffer() != mMixBuffer) {
1726 chain = getEffectChain_l(track->sessionId());
1727 // Delegate volume control to effect in track effect chain if needed
1728 if (chain != 0) {
1729 tracksWithEffect++;
1730 } else {
1731 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1732 track->name(), track->sessionId());
1733 }
1734 }
1735
1736
1737 int param = AudioMixer::VOLUME;
1738 if (track->mFillingUpStatus == Track::FS_FILLED) {
1739 // no ramp for the first volume setting
1740 track->mFillingUpStatus = Track::FS_ACTIVE;
1741 if (track->mState == TrackBase::RESUMING) {
1742 track->mState = TrackBase::ACTIVE;
1743 param = AudioMixer::RAMP_VOLUME;
1744 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08001745 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07001746 } else if (cblk->server != 0) {
1747 // If the track is stopped before the first frame was mixed,
1748 // do not apply ramp
1749 param = AudioMixer::RAMP_VOLUME;
1750 }
1751
Eric Laurenta553c252009-07-17 12:17:14 -07001752 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001753 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001754 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001755 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001756 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001757 if (track->isPausing()) {
1758 track->setPaused();
1759 }
1760 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001761
Glenn Kasten871c16c2010-03-05 12:18:01 -08001762 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001763 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001764 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001765 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1766 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001767
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001768 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001769 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001770 // Delegate volume control to effect in track effect chain if needed
1771 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1772 // Do not ramp volume if volume is controlled by effect
1773 param = AudioMixer::VOLUME;
1774 track->mHasVolumeController = true;
1775 } else {
1776 // force no volume ramp when volume controller was just disabled or removed
1777 // from effect chain to avoid volume spike
1778 if (track->mHasVolumeController) {
1779 param = AudioMixer::VOLUME;
1780 }
1781 track->mHasVolumeController = false;
1782 }
1783
1784 // Convert volumes from 8.24 to 4.12 format
1785 int16_t left, right, aux;
1786 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1787 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1788 left = int16_t(v_clamped);
1789 v_clamped = (vr + (1 << 11)) >> 12;
1790 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1791 right = int16_t(v_clamped);
1792
1793 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1794 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07001795
Eric Laurent65b65452010-06-01 23:49:17 -07001796 // XXX: these things DON'T need to be done each time
1797 mAudioMixer->setBufferProvider(track);
1798 mAudioMixer->enable(AudioMixer::MIXING);
1799
1800 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1801 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1802 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001803 mAudioMixer->setParameter(
1804 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001805 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001806 mAudioMixer->setParameter(
1807 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001808 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001809 mAudioMixer->setParameter(
1810 AudioMixer::RESAMPLE,
1811 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001812 (void *)(cblk->sampleRate));
1813 mAudioMixer->setParameter(
1814 AudioMixer::TRACK,
1815 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1816 mAudioMixer->setParameter(
1817 AudioMixer::TRACK,
1818 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001819
1820 // reset retry count
1821 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001822 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001823 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001824 //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 -07001825 if (track->isStopped()) {
1826 track->reset();
1827 }
1828 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1829 // We have consumed all the buffers of this track.
1830 // Remove it from the list of active tracks.
1831 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001832 } else {
1833 // No buffers for this track. Give it a few chances to
1834 // fill a buffer, then remove it from active list.
1835 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001836 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001837 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07001838 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07001839 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08001840 } else if (mixerStatus != MIXER_TRACKS_READY) {
1841 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001842 }
Eric Laurenta553c252009-07-17 12:17:14 -07001843 }
Eric Laurent65b65452010-06-01 23:49:17 -07001844 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001845 }
1846 }
1847
1848 // remove all the tracks that need to be...
1849 count = tracksToRemove->size();
1850 if (UNLIKELY(count)) {
1851 for (size_t i=0 ; i<count ; i++) {
1852 const sp<Track>& track = tracksToRemove->itemAt(i);
1853 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001854 if (track->mainBuffer() != mMixBuffer) {
1855 chain = getEffectChain_l(track->sessionId());
1856 if (chain != 0) {
1857 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001858 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001859 }
1860 }
Eric Laurenta553c252009-07-17 12:17:14 -07001861 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07001862 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001863 }
1864 }
1865 }
1866
Eric Laurent65b65452010-06-01 23:49:17 -07001867 // mix buffer must be cleared if all tracks are connected to an
1868 // effect chain as in this case the mixer will not write to
1869 // mix buffer and track effects will accumulate into it
1870 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1871 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1872 }
1873
Eric Laurent059b4be2009-11-09 23:32:22 -08001874 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001875}
1876
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001877void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001878{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001879 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1880 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001881 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001882
Eric Laurenta553c252009-07-17 12:17:14 -07001883 size_t size = mTracks.size();
1884 for (size_t i = 0; i < size; i++) {
1885 sp<Track> t = mTracks[i];
1886 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07001887 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001888 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07001889 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001890 }
1891}
Eric Laurenta553c252009-07-17 12:17:14 -07001892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893
Eric Laurenta553c252009-07-17 12:17:14 -07001894// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001895int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896{
1897 return mAudioMixer->getTrackName();
1898}
1899
Eric Laurenta553c252009-07-17 12:17:14 -07001900// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001901void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902{
Eric Laurent0a080292009-12-07 10:53:10 -08001903 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 mAudioMixer->deleteTrackName(name);
1905}
1906
Eric Laurenta553c252009-07-17 12:17:14 -07001907// checkForNewParameters_l() must be called with ThreadBase::mLock held
1908bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909{
Eric Laurenta553c252009-07-17 12:17:14 -07001910 bool reconfig = false;
1911
Eric Laurent8fce46a2009-08-04 09:45:33 -07001912 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001913 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001914 String8 keyValuePair = mNewParameters[0];
1915 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001916 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001917
Eric Laurenta553c252009-07-17 12:17:14 -07001918 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1919 reconfig = true;
1920 }
1921 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001922 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07001923 status = BAD_VALUE;
1924 } else {
1925 reconfig = true;
1926 }
1927 }
1928 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001929 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07001930 status = BAD_VALUE;
1931 } else {
1932 reconfig = true;
1933 }
1934 }
1935 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1936 // do not accept frame count changes if tracks are open as the track buffer
1937 // size depends on frame count and correct behavior would not be garantied
1938 // if frame count is changed after track creation
1939 if (!mTracks.isEmpty()) {
1940 status = INVALID_OPERATION;
1941 } else {
1942 reconfig = true;
1943 }
1944 }
Eric Laurent65b65452010-06-01 23:49:17 -07001945 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001946 // when changing the audio output device, call addBatteryData to notify
1947 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07001948 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001949 uint32_t params = 0;
1950 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001951 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001952 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1953 }
1954
1955 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001956 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08001957 // check if any other device (except speaker) is on
1958 if (value & deviceWithoutSpeaker ) {
1959 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1960 }
1961
1962 if (params != 0) {
1963 addBatteryData(params);
1964 }
1965 }
1966
Eric Laurent65b65452010-06-01 23:49:17 -07001967 // forward device change to effects that have requested to be
1968 // aware of attached audio device.
1969 mDevice = (uint32_t)value;
1970 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001971 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001972 }
1973 }
1974
Eric Laurenta553c252009-07-17 12:17:14 -07001975 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001976 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001977 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001978 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07001979 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001980 mStandby = true;
1981 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07001982 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001983 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001984 }
1985 if (status == NO_ERROR && reconfig) {
1986 delete mAudioMixer;
1987 readOutputParameters();
1988 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1989 for (size_t i = 0; i < mTracks.size() ; i++) {
1990 int name = getTrackName_l();
1991 if (name < 0) break;
1992 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001993 // limit track sample rate to 2 x new output sample rate
1994 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1995 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1996 }
Eric Laurenta553c252009-07-17 12:17:14 -07001997 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001998 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001999 }
2000 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002001
2002 mNewParameters.removeAt(0);
2003
Eric Laurenta553c252009-07-17 12:17:14 -07002004 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002005 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002006 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002007 }
2008 return reconfig;
2009}
2010
2011status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2012{
2013 const size_t SIZE = 256;
2014 char buffer[SIZE];
2015 String8 result;
2016
2017 PlaybackThread::dumpInternals(fd, args);
2018
2019 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2020 result.append(buffer);
2021 write(fd, result.string(), result.size());
2022 return NO_ERROR;
2023}
2024
Eric Laurent059b4be2009-11-09 23:32:22 -08002025uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002026{
Dima Zavin31f188892011-04-18 16:57:27 -07002027 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002028}
2029
2030uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2031{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002032 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002033}
2034
Eric Laurent8448a792010-08-18 18:13:17 -07002035uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2036{
2037 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2038}
2039
Eric Laurenta553c252009-07-17 12:17:14 -07002040// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002041AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002042 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002043{
2044 mType = PlaybackThread::DIRECT;
2045}
2046
2047AudioFlinger::DirectOutputThread::~DirectOutputThread()
2048{
2049}
2050
2051
Eric Laurent65b65452010-06-01 23:49:17 -07002052static inline int16_t clamp16(int32_t sample)
2053{
2054 if ((sample>>15) ^ (sample>>31))
2055 sample = 0x7FFF ^ (sample>>31);
2056 return sample;
2057}
2058
2059static inline
2060int32_t mul(int16_t in, int16_t v)
2061{
2062#if defined(__arm__) && !defined(__thumb__)
2063 int32_t out;
2064 asm( "smulbb %[out], %[in], %[v] \n"
2065 : [out]"=r"(out)
2066 : [in]"%r"(in), [v]"r"(v)
2067 : );
2068 return out;
2069#else
2070 return in * int32_t(v);
2071#endif
2072}
2073
2074void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2075{
2076 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002077 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002078 return;
2079 }
2080
2081 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002082 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002083 size_t count = mFrameCount * mChannelCount;
2084 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2085 int16_t *dst = mMixBuffer + count-1;
2086 while(count--) {
2087 *dst-- = (int16_t)(*src--^0x80) << 8;
2088 }
2089 }
2090
2091 size_t frameCount = mFrameCount;
2092 int16_t *out = mMixBuffer;
2093 if (ramp) {
2094 if (mChannelCount == 1) {
2095 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2096 int32_t vlInc = d / (int32_t)frameCount;
2097 int32_t vl = ((int32_t)mLeftVolShort << 16);
2098 do {
2099 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2100 out++;
2101 vl += vlInc;
2102 } while (--frameCount);
2103
2104 } else {
2105 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2106 int32_t vlInc = d / (int32_t)frameCount;
2107 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2108 int32_t vrInc = d / (int32_t)frameCount;
2109 int32_t vl = ((int32_t)mLeftVolShort << 16);
2110 int32_t vr = ((int32_t)mRightVolShort << 16);
2111 do {
2112 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2113 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2114 out += 2;
2115 vl += vlInc;
2116 vr += vrInc;
2117 } while (--frameCount);
2118 }
2119 } else {
2120 if (mChannelCount == 1) {
2121 do {
2122 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2123 out++;
2124 } while (--frameCount);
2125 } else {
2126 do {
2127 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2128 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2129 out += 2;
2130 } while (--frameCount);
2131 }
2132 }
2133
2134 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002135 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002136 size_t count = mFrameCount * mChannelCount;
2137 int16_t *src = mMixBuffer;
2138 uint8_t *dst = (uint8_t *)mMixBuffer;
2139 while(count--) {
2140 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2141 }
2142 }
2143
2144 mLeftVolShort = leftVol;
2145 mRightVolShort = rightVol;
2146}
2147
Eric Laurenta553c252009-07-17 12:17:14 -07002148bool AudioFlinger::DirectOutputThread::threadLoop()
2149{
Eric Laurent059b4be2009-11-09 23:32:22 -08002150 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002151 sp<Track> trackToRemove;
2152 sp<Track> activeTrack;
2153 nsecs_t standbyTime = systemTime();
2154 int8_t *curBuf;
2155 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002156 uint32_t activeSleepTime = activeSleepTimeUs();
2157 uint32_t idleSleepTime = idleSleepTimeUs();
2158 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002159 // use shorter standby delay as on normal output to release
2160 // hardware resources as soon as possible
2161 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002162
Eric Laurenta553c252009-07-17 12:17:14 -07002163 while (!exitPending())
2164 {
Eric Laurent65b65452010-06-01 23:49:17 -07002165 bool rampVolume;
2166 uint16_t leftVol;
2167 uint16_t rightVol;
2168 Vector< sp<EffectChain> > effectChains;
2169
Eric Laurenta553c252009-07-17 12:17:14 -07002170 processConfigEvents();
2171
Eric Laurent059b4be2009-11-09 23:32:22 -08002172 mixerStatus = MIXER_IDLE;
2173
Eric Laurenta553c252009-07-17 12:17:14 -07002174 { // scope for the mLock
2175
2176 Mutex::Autolock _l(mLock);
2177
2178 if (checkForNewParameters_l()) {
2179 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002180 activeSleepTime = activeSleepTimeUs();
2181 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002182 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002183 }
2184
2185 // put audio hardware into standby after short delay
2186 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2187 mSuspended) {
2188 // wait until we have something to do...
2189 if (!mStandby) {
2190 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002191 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002192 mStandby = true;
2193 mBytesWritten = 0;
2194 }
2195
2196 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2197 // we're about to wait, flush the binder command buffer
2198 IPCThreadState::self()->flushCommands();
2199
2200 if (exitPending()) break;
2201
2202 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2203 mWaitWorkCV.wait(mLock);
2204 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2205
2206 if (mMasterMute == false) {
2207 char value[PROPERTY_VALUE_MAX];
2208 property_get("ro.audio.silent", value, "0");
2209 if (atoi(value)) {
2210 LOGD("Silence is golden");
2211 setMasterMute(true);
2212 }
2213 }
2214
Eric Laurentef9500f2010-03-11 14:47:00 -08002215 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002216 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002217 continue;
2218 }
2219 }
2220
Eric Laurent65b65452010-06-01 23:49:17 -07002221 effectChains = mEffectChains;
2222
Eric Laurenta553c252009-07-17 12:17:14 -07002223 // find out which tracks need to be processed
2224 if (mActiveTracks.size() != 0) {
2225 sp<Track> t = mActiveTracks[0].promote();
2226 if (t == 0) continue;
2227
2228 Track* const track = t.get();
2229 audio_track_cblk_t* cblk = track->cblk();
2230
2231 // The first time a track is added we wait
2232 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002233 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002234 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002235 {
2236 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2237
Eric Laurent65b65452010-06-01 23:49:17 -07002238 if (track->mFillingUpStatus == Track::FS_FILLED) {
2239 track->mFillingUpStatus = Track::FS_ACTIVE;
2240 mLeftVolFloat = mRightVolFloat = 0;
2241 mLeftVolShort = mRightVolShort = 0;
2242 if (track->mState == TrackBase::RESUMING) {
2243 track->mState = TrackBase::ACTIVE;
2244 rampVolume = true;
2245 }
2246 } else if (cblk->server != 0) {
2247 // If the track is stopped before the first frame was mixed,
2248 // do not apply ramp
2249 rampVolume = true;
2250 }
Eric Laurenta553c252009-07-17 12:17:14 -07002251 // compute volume for this track
2252 float left, right;
2253 if (track->isMuted() || mMasterMute || track->isPausing() ||
2254 mStreamTypes[track->type()].mute) {
2255 left = right = 0;
2256 if (track->isPausing()) {
2257 track->setPaused();
2258 }
2259 } else {
2260 float typeVolume = mStreamTypes[track->type()].volume;
2261 float v = mMasterVolume * typeVolume;
2262 float v_clamped = v * cblk->volume[0];
2263 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2264 left = v_clamped/MAX_GAIN;
2265 v_clamped = v * cblk->volume[1];
2266 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2267 right = v_clamped/MAX_GAIN;
2268 }
2269
Eric Laurent65b65452010-06-01 23:49:17 -07002270 if (left != mLeftVolFloat || right != mRightVolFloat) {
2271 mLeftVolFloat = left;
2272 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002273
Eric Laurent65b65452010-06-01 23:49:17 -07002274 // If audio HAL implements volume control,
2275 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002276 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002277 left = 1.0f;
2278 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002279 }
Eric Laurent65b65452010-06-01 23:49:17 -07002280
2281 // Convert volumes from float to 8.24
2282 uint32_t vl = (uint32_t)(left * (1 << 24));
2283 uint32_t vr = (uint32_t)(right * (1 << 24));
2284
2285 // Delegate volume control to effect in track effect chain if needed
2286 // only one effect chain can be present on DirectOutputThread, so if
2287 // there is one, the track is connected to it
2288 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002289 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002290 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002291 rampVolume = false;
2292 }
2293 }
2294
2295 // Convert volumes from 8.24 to 4.12 format
2296 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2297 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2298 leftVol = (uint16_t)v_clamped;
2299 v_clamped = (vr + (1 << 11)) >> 12;
2300 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2301 rightVol = (uint16_t)v_clamped;
2302 } else {
2303 leftVol = mLeftVolShort;
2304 rightVol = mRightVolShort;
2305 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002306 }
2307
2308 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002309 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002310 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002311 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002312 } else {
2313 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2314 if (track->isStopped()) {
2315 track->reset();
2316 }
2317 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2318 // We have consumed all the buffers of this track.
2319 // Remove it from the list of active tracks.
2320 trackToRemove = track;
2321 } else {
2322 // No buffers for this track. Give it a few chances to
2323 // fill a buffer, then remove it from active list.
2324 if (--(track->mRetryCount) <= 0) {
2325 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2326 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002327 } else {
2328 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002329 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002330 }
Eric Laurenta553c252009-07-17 12:17:14 -07002331 }
2332 }
2333
2334 // remove all the tracks that need to be...
2335 if (UNLIKELY(trackToRemove != 0)) {
2336 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002337 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002338 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2339 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002340 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002341 }
Eric Laurenta553c252009-07-17 12:17:14 -07002342 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002343 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002344 }
2345 }
Eric Laurent65b65452010-06-01 23:49:17 -07002346
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002347 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002348 }
2349
Eric Laurent059b4be2009-11-09 23:32:22 -08002350 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002351 AudioBufferProvider::Buffer buffer;
2352 size_t frameCount = mFrameCount;
2353 curBuf = (int8_t *)mMixBuffer;
2354 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002355 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002356 buffer.frameCount = frameCount;
2357 activeTrack->getNextBuffer(&buffer);
2358 if (UNLIKELY(buffer.raw == 0)) {
2359 memset(curBuf, 0, frameCount * mFrameSize);
2360 break;
2361 }
2362 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2363 frameCount -= buffer.frameCount;
2364 curBuf += buffer.frameCount * mFrameSize;
2365 activeTrack->releaseBuffer(&buffer);
2366 }
2367 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002368 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002369 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002370 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002371 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2372 sleepTime = activeSleepTime;
2373 } else {
2374 sleepTime = idleSleepTime;
2375 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002376 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002377 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002378 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002379 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002380 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002381
Eric Laurentf69a3f82009-09-22 00:35:48 -07002382 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002383 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002384 }
2385 // sleepTime == 0 means we must write to audio hardware
2386 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002387 if (mixerStatus == MIXER_TRACKS_READY) {
2388 applyVolume(leftVol, rightVol, rampVolume);
2389 }
2390 for (size_t i = 0; i < effectChains.size(); i ++) {
2391 effectChains[i]->process_l();
2392 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002393 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002394
Eric Laurentf69a3f82009-09-22 00:35:48 -07002395 mLastWriteTime = systemTime();
2396 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002397 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002398 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002399 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002400 mNumWrites++;
2401 mInWrite = false;
2402 mStandby = false;
2403 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002404 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002405 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002406 }
2407
2408 // finally let go of removed track, without the lock held
2409 // since we can't guarantee the destructors won't acquire that
2410 // same lock.
2411 trackToRemove.clear();
2412 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002413
2414 // Effect chains will be actually deleted here if they were removed from
2415 // mEffectChains list during mixing or effects processing
2416 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002417 }
2418
2419 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002420 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002421 }
Eric Laurenta553c252009-07-17 12:17:14 -07002422
2423 LOGV("DirectOutputThread %p exiting", this);
2424 return false;
2425}
2426
2427// getTrackName_l() must be called with ThreadBase::mLock held
2428int AudioFlinger::DirectOutputThread::getTrackName_l()
2429{
2430 return 0;
2431}
2432
2433// deleteTrackName_l() must be called with ThreadBase::mLock held
2434void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2435{
2436}
2437
2438// checkForNewParameters_l() must be called with ThreadBase::mLock held
2439bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2440{
2441 bool reconfig = false;
2442
Eric Laurent8fce46a2009-08-04 09:45:33 -07002443 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002444 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002445 String8 keyValuePair = mNewParameters[0];
2446 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002447 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002448
Eric Laurenta553c252009-07-17 12:17:14 -07002449 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2450 // do not accept frame count changes if tracks are open as the track buffer
2451 // size depends on frame count and correct behavior would not be garantied
2452 // if frame count is changed after track creation
2453 if (!mTracks.isEmpty()) {
2454 status = INVALID_OPERATION;
2455 } else {
2456 reconfig = true;
2457 }
2458 }
2459 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002460 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002461 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002462 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002463 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002464 mStandby = true;
2465 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002466 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002467 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002468 }
2469 if (status == NO_ERROR && reconfig) {
2470 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002471 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002472 }
2473 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002474
2475 mNewParameters.removeAt(0);
2476
Eric Laurenta553c252009-07-17 12:17:14 -07002477 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002478 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002479 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002480 }
2481 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002482}
2483
Eric Laurent059b4be2009-11-09 23:32:22 -08002484uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002485{
2486 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002487 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin31f188892011-04-18 16:57:27 -07002488 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002489 } else {
2490 time = 10000;
2491 }
2492 return time;
2493}
2494
2495uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2496{
2497 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002498 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002499 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002500 } else {
2501 time = 10000;
2502 }
2503 return time;
2504}
2505
Eric Laurent8448a792010-08-18 18:13:17 -07002506uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2507{
2508 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002509 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002510 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2511 } else {
2512 time = 10000;
2513 }
2514 return time;
2515}
2516
2517
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002518// ----------------------------------------------------------------------------
2519
Eric Laurent49f02be2009-11-19 09:00:56 -08002520AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002521 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002522{
2523 mType = PlaybackThread::DUPLICATING;
2524 addOutputTrack(mainThread);
2525}
2526
2527AudioFlinger::DuplicatingThread::~DuplicatingThread()
2528{
Eric Laurent0a080292009-12-07 10:53:10 -08002529 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2530 mOutputTracks[i]->destroy();
2531 }
Eric Laurenta553c252009-07-17 12:17:14 -07002532 mOutputTracks.clear();
2533}
2534
2535bool AudioFlinger::DuplicatingThread::threadLoop()
2536{
Eric Laurenta553c252009-07-17 12:17:14 -07002537 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002538 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002539 nsecs_t standbyTime = systemTime();
2540 size_t mixBufferSize = mFrameCount*mFrameSize;
2541 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002542 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002543 uint32_t activeSleepTime = activeSleepTimeUs();
2544 uint32_t idleSleepTime = idleSleepTimeUs();
2545 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002546 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002547
2548 while (!exitPending())
2549 {
2550 processConfigEvents();
2551
Eric Laurent059b4be2009-11-09 23:32:22 -08002552 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002553 { // scope for the mLock
2554
2555 Mutex::Autolock _l(mLock);
2556
2557 if (checkForNewParameters_l()) {
2558 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002559 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002560 activeSleepTime = activeSleepTimeUs();
2561 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002562 }
2563
2564 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2565
2566 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2567 outputTracks.add(mOutputTracks[i]);
2568 }
2569
2570 // put audio hardware into standby after short delay
2571 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2572 mSuspended) {
2573 if (!mStandby) {
2574 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002575 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002576 }
2577 mStandby = true;
2578 mBytesWritten = 0;
2579 }
2580
2581 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2582 // we're about to wait, flush the binder command buffer
2583 IPCThreadState::self()->flushCommands();
2584 outputTracks.clear();
2585
2586 if (exitPending()) break;
2587
2588 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2589 mWaitWorkCV.wait(mLock);
2590 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2591 if (mMasterMute == false) {
2592 char value[PROPERTY_VALUE_MAX];
2593 property_get("ro.audio.silent", value, "0");
2594 if (atoi(value)) {
2595 LOGD("Silence is golden");
2596 setMasterMute(true);
2597 }
2598 }
2599
2600 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002601 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002602 continue;
2603 }
2604 }
2605
Eric Laurent059b4be2009-11-09 23:32:22 -08002606 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002607
2608 // prevent any changes in effect chain list and in each effect chain
2609 // during mixing and effect process as the audio buffers could be deleted
2610 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002611 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002612 }
Eric Laurenta553c252009-07-17 12:17:14 -07002613
Eric Laurent059b4be2009-11-09 23:32:22 -08002614 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002615 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002616 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002617 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002618 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002619 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002620 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002621 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002622 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002623 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002624 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002625 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2626 sleepTime = activeSleepTime;
2627 } else {
2628 sleepTime = idleSleepTime;
2629 }
Eric Laurent62443f52009-10-05 20:29:18 -07002630 } else if (mBytesWritten != 0) {
2631 // flush remaining overflow buffers in output tracks
2632 for (size_t i = 0; i < outputTracks.size(); i++) {
2633 if (outputTracks[i]->isActive()) {
2634 sleepTime = 0;
2635 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002636 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002637 break;
2638 }
2639 }
Eric Laurenta553c252009-07-17 12:17:14 -07002640 }
2641 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002642
2643 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002644 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002645 }
2646 // sleepTime == 0 means we must write to audio hardware
2647 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002648 for (size_t i = 0; i < effectChains.size(); i ++) {
2649 effectChains[i]->process_l();
2650 }
2651 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002652 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002653
Eric Laurent62443f52009-10-05 20:29:18 -07002654 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002655 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002656 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002657 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002658 mStandby = false;
2659 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002660 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002661 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002662 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002663 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002664 }
2665
2666 // finally let go of all our tracks, without the lock held
2667 // since we can't guarantee the destructors won't acquire that
2668 // same lock.
2669 tracksToRemove.clear();
2670 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002671
2672 // Effect chains will be actually deleted here if they were removed from
2673 // mEffectChains list during mixing or effects processing
2674 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002675 }
2676
Eric Laurenta553c252009-07-17 12:17:14 -07002677 return false;
2678}
2679
2680void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2681{
2682 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2683 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002684 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002685 mSampleRate,
2686 mFormat,
2687 mChannelCount,
2688 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002689 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002690 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07002691 mOutputTracks.add(outputTrack);
2692 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002693 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002694 }
Eric Laurenta553c252009-07-17 12:17:14 -07002695}
2696
2697void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2698{
2699 Mutex::Autolock _l(mLock);
2700 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2701 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002702 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002703 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002704 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002705 return;
2706 }
2707 }
2708 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2709}
2710
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002711void AudioFlinger::DuplicatingThread::updateWaitTime()
2712{
2713 mWaitTimeMs = UINT_MAX;
2714 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2715 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2716 if (strong != NULL) {
2717 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2718 if (waitTimeMs < mWaitTimeMs) {
2719 mWaitTimeMs = waitTimeMs;
2720 }
2721 }
2722 }
2723}
2724
2725
2726bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2727{
2728 for (size_t i = 0; i < outputTracks.size(); i++) {
2729 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2730 if (thread == 0) {
2731 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2732 return false;
2733 }
2734 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2735 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2736 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2737 return false;
2738 }
2739 }
2740 return true;
2741}
2742
2743uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2744{
2745 return (mWaitTimeMs * 1000) / 2;
2746}
2747
Eric Laurenta553c252009-07-17 12:17:14 -07002748// ----------------------------------------------------------------------------
2749
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002750// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002751AudioFlinger::ThreadBase::TrackBase::TrackBase(
2752 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002753 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002754 uint32_t sampleRate,
2755 int format,
2756 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002757 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002759 const sp<IMemory>& sharedBuffer,
2760 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002761 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002762 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002763 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002764 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002765 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002766 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002767 mClientTid(-1),
2768 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002769 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2770 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002771{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002772 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2773
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002774 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002775 size_t size = sizeof(audio_track_cblk_t);
2776 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2777 if (sharedBuffer == 0) {
2778 size += bufferSize;
2779 }
2780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 if (client != NULL) {
2782 mCblkMemory = client->heap()->allocate(size);
2783 if (mCblkMemory != 0) {
2784 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2785 if (mCblk) { // construct the shared structure in-place.
2786 new(mCblk) audio_track_cblk_t();
2787 // clear all buffers
2788 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002789 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002790 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 if (sharedBuffer == 0) {
2792 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2793 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2794 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002795 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002796 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 } else {
2798 mBuffer = sharedBuffer->pointer();
2799 }
2800 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 } else {
2803 LOGE("not enough memory for AudioTrack size=%u", size);
2804 client->heap()->dump("AudioTrack");
2805 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 } else {
2808 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2809 if (mCblk) { // construct the shared structure in-place.
2810 new(mCblk) audio_track_cblk_t();
2811 // clear all buffers
2812 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002813 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002814 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2816 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2817 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002818 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002819 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2821 }
2822 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002823}
2824
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002825AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002826{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002828 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2829 if (mClient == NULL) {
2830 delete mCblk;
2831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002833 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002834 if (mClient != NULL) {
2835 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2836 mClient.clear();
2837 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002838}
2839
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002840void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002841{
2842 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002843 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002844 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002845 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002846}
2847
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002848bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002849 bool result;
2850 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002851
2852 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002853 if (!result) {
2854 LOGV("stepServer failed acquiring cblk mutex");
2855 mFlags |= STEPSERVER_FAILED;
2856 }
2857 return result;
2858}
2859
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002860void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002861 audio_track_cblk_t* cblk = this->cblk();
2862
2863 cblk->user = 0;
2864 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002865 cblk->userBase = 0;
2866 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002868 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002869}
2870
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002871sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002872{
2873 return mCblkMemory;
2874}
2875
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002876int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002877 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002878}
2879
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002880int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002881 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002882}
2883
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002884void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002885 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002886 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2887 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002888
2889 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002890 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2891 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002892 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002893 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002894 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002895 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002896 return 0;
2897 }
2898
2899 return bufferStart;
2900}
2901
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002902// ----------------------------------------------------------------------------
2903
Eric Laurenta553c252009-07-17 12:17:14 -07002904// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2905AudioFlinger::PlaybackThread::Track::Track(
2906 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002907 const sp<Client>& client,
2908 int streamType,
2909 uint32_t sampleRate,
2910 int format,
2911 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002912 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002913 const sp<IMemory>& sharedBuffer,
2914 int sessionId)
2915 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07002916 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2917 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002918{
Eric Laurent8a77a992009-09-09 05:16:08 -07002919 if (mCblk != NULL) {
2920 sp<ThreadBase> baseThread = thread.promote();
2921 if (baseThread != 0) {
2922 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2923 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002924 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002925 }
2926 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2927 if (mName < 0) {
2928 LOGE("no more track names available");
2929 }
2930 mVolume[0] = 1.0f;
2931 mVolume[1] = 1.0f;
2932 mStreamType = streamType;
2933 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2934 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002935 mCblk->frameSize = audio_is_linear_pcm(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002936 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002937}
2938
Eric Laurenta553c252009-07-17 12:17:14 -07002939AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002940{
Eric Laurenta553c252009-07-17 12:17:14 -07002941 LOGV("PlaybackThread::Track destructor");
2942 sp<ThreadBase> thread = mThread.promote();
2943 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002944 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002945 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002946 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002947}
2948
Eric Laurenta553c252009-07-17 12:17:14 -07002949void AudioFlinger::PlaybackThread::Track::destroy()
2950{
2951 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2952 // by removing it from mTracks vector, so there is a risk that this Tracks's
2953 // desctructor is called. As the destructor needs to lock mLock,
2954 // we must acquire a strong reference on this Track before locking mLock
2955 // here so that the destructor is called only when exiting this function.
2956 // On the other hand, as long as Track::destroy() is only called by
2957 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2958 // this Track with its member mTrack.
2959 sp<Track> keep(this);
2960 { // scope for mLock
2961 sp<ThreadBase> thread = mThread.promote();
2962 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002963 if (!isOutputTrack()) {
2964 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002965 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002966 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002967 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08002968
2969 // to track the speaker usage
2970 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08002971 }
2972 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002973 }
Eric Laurenta553c252009-07-17 12:17:14 -07002974 Mutex::Autolock _l(thread->mLock);
2975 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2976 playbackThread->destroyTrack_l(this);
2977 }
2978 }
2979}
2980
2981void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002982{
Eric Laurent65b65452010-06-01 23:49:17 -07002983 snprintf(buffer, size, " %05d %05d %03u %03u %03u %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 -07002984 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002986 mStreamType,
2987 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002988 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002989 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002990 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002991 mState,
2992 mMute,
2993 mFillingUpStatus,
2994 mCblk->sampleRate,
2995 mCblk->volume[0],
2996 mCblk->volume[1],
2997 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002998 mCblk->user,
2999 (int)mMainBuffer,
3000 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003001}
3002
Eric Laurenta553c252009-07-17 12:17:14 -07003003status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003004{
3005 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003006 uint32_t framesReady;
3007 uint32_t framesReq = buffer->frameCount;
3008
3009 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003010 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3011 if (!step()) goto getNextBuffer_exit;
3012 LOGV("stepServer recovered");
3013 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3014 }
3015
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003016 framesReady = cblk->framesReady();
3017
3018 if (LIKELY(framesReady)) {
3019 uint32_t s = cblk->server;
3020 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3021
3022 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3023 if (framesReq > framesReady) {
3024 framesReq = framesReady;
3025 }
3026 if (s + framesReq > bufferEnd) {
3027 framesReq = bufferEnd - s;
3028 }
3029
3030 buffer->raw = getBuffer(s, framesReq);
3031 if (buffer->raw == 0) goto getNextBuffer_exit;
3032
3033 buffer->frameCount = framesReq;
3034 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003035 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003036
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003037getNextBuffer_exit:
3038 buffer->raw = 0;
3039 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003040 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 -07003041 return NOT_ENOUGH_DATA;
3042}
3043
Eric Laurenta553c252009-07-17 12:17:14 -07003044bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003045 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003046
3047 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003048 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003049 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003050 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003051 return true;
3052 }
3053 return false;
3054}
3055
Eric Laurenta553c252009-07-17 12:17:14 -07003056status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003057{
Eric Laurent49f02be2009-11-19 09:00:56 -08003058 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003059 LOGV("start(%d), calling thread %d session %d",
3060 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003061 sp<ThreadBase> thread = mThread.promote();
3062 if (thread != 0) {
3063 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003064 int state = mState;
3065 // here the track could be either new, or restarted
3066 // in both cases "unstop" the track
3067 if (mState == PAUSED) {
3068 mState = TrackBase::RESUMING;
3069 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3070 } else {
3071 mState = TrackBase::ACTIVE;
3072 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3073 }
3074
3075 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3076 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003077 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003078 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003079 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003080 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003081
3082 // to track the speaker usage
3083 if (status == NO_ERROR) {
3084 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3085 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003086 }
3087 if (status == NO_ERROR) {
3088 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3089 playbackThread->addTrack_l(this);
3090 } else {
3091 mState = state;
3092 }
3093 } else {
3094 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003095 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003096 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003097}
3098
Eric Laurenta553c252009-07-17 12:17:14 -07003099void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003100{
Eric Laurenta553c252009-07-17 12:17:14 -07003101 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3102 sp<ThreadBase> thread = mThread.promote();
3103 if (thread != 0) {
3104 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003105 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003106 if (mState > STOPPED) {
3107 mState = STOPPED;
3108 // If the track is not active (PAUSED and buffers full), flush buffers
3109 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3110 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3111 reset();
3112 }
Eric Laurent62443f52009-10-05 20:29:18 -07003113 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003114 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003115 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3116 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003117 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003118 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003119 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003120 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003121
3122 // to track the speaker usage
3123 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003124 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003125 }
3126}
3127
Eric Laurenta553c252009-07-17 12:17:14 -07003128void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003129{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003131 sp<ThreadBase> thread = mThread.promote();
3132 if (thread != 0) {
3133 Mutex::Autolock _l(thread->mLock);
3134 if (mState == ACTIVE || mState == RESUMING) {
3135 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003136 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003137 if (!isOutputTrack()) {
3138 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003139 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003140 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003141 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003142 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003143
3144 // to track the speaker usage
3145 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003146 }
Eric Laurenta553c252009-07-17 12:17:14 -07003147 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003148 }
3149}
3150
Eric Laurenta553c252009-07-17 12:17:14 -07003151void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003152{
3153 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003154 sp<ThreadBase> thread = mThread.promote();
3155 if (thread != 0) {
3156 Mutex::Autolock _l(thread->mLock);
3157 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3158 return;
3159 }
3160 // No point remaining in PAUSED state after a flush => go to
3161 // STOPPED state
3162 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003163
Eric Laurentae29b762011-03-28 18:37:07 -07003164 // do not reset the track if it is still in the process of being stopped or paused.
3165 // this will be done by prepareTracks_l() when the track is stopped.
3166 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3167 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3168 reset();
3169 }
Eric Laurenta553c252009-07-17 12:17:14 -07003170 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003171}
3172
Eric Laurenta553c252009-07-17 12:17:14 -07003173void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003174{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003175 // Do not reset twice to avoid discarding data written just after a flush and before
3176 // the audioflinger thread detects the track is stopped.
3177 if (!mResetDone) {
3178 TrackBase::reset();
3179 // Force underrun condition to avoid false underrun callback until first data is
3180 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003181 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3182 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003183 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003184 mResetDone = true;
3185 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003186}
3187
Eric Laurenta553c252009-07-17 12:17:14 -07003188void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003189{
3190 mMute = muted;
3191}
3192
Eric Laurenta553c252009-07-17 12:17:14 -07003193void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003194{
3195 mVolume[0] = left;
3196 mVolume[1] = right;
3197}
3198
Eric Laurent65b65452010-06-01 23:49:17 -07003199status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3200{
3201 status_t status = DEAD_OBJECT;
3202 sp<ThreadBase> thread = mThread.promote();
3203 if (thread != 0) {
3204 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3205 status = playbackThread->attachAuxEffect(this, EffectId);
3206 }
3207 return status;
3208}
3209
3210void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3211{
3212 mAuxEffectId = EffectId;
3213 mAuxBuffer = buffer;
3214}
3215
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003216// ----------------------------------------------------------------------------
3217
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003218// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003219AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3220 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 uint32_t sampleRate,
3223 int format,
3224 int channelCount,
3225 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003226 uint32_t flags,
3227 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003228 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003229 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003230 mOverflow(false)
3231{
Eric Laurent8a77a992009-09-09 05:16:08 -07003232 if (mCblk != NULL) {
3233 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003234 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurent8a77a992009-09-09 05:16:08 -07003235 mCblk->frameSize = channelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003236 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent8a77a992009-09-09 05:16:08 -07003237 mCblk->frameSize = channelCount * sizeof(int8_t);
3238 } else {
3239 mCblk->frameSize = sizeof(int8_t);
3240 }
3241 }
Eric Laurenta553c252009-07-17 12:17:14 -07003242}
3243
3244AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245{
Eric Laurent49f02be2009-11-19 09:00:56 -08003246 sp<ThreadBase> thread = mThread.promote();
3247 if (thread != 0) {
3248 AudioSystem::releaseInput(thread->id());
3249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250}
3251
Eric Laurenta553c252009-07-17 12:17:14 -07003252status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253{
3254 audio_track_cblk_t* cblk = this->cblk();
3255 uint32_t framesAvail;
3256 uint32_t framesReq = buffer->frameCount;
3257
3258 // Check if last stepServer failed, try to step now
3259 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3260 if (!step()) goto getNextBuffer_exit;
3261 LOGV("stepServer recovered");
3262 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3263 }
3264
3265 framesAvail = cblk->framesAvailable_l();
3266
3267 if (LIKELY(framesAvail)) {
3268 uint32_t s = cblk->server;
3269 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3270
3271 if (framesReq > framesAvail) {
3272 framesReq = framesAvail;
3273 }
3274 if (s + framesReq > bufferEnd) {
3275 framesReq = bufferEnd - s;
3276 }
3277
3278 buffer->raw = getBuffer(s, framesReq);
3279 if (buffer->raw == 0) goto getNextBuffer_exit;
3280
3281 buffer->frameCount = framesReq;
3282 return NO_ERROR;
3283 }
3284
3285getNextBuffer_exit:
3286 buffer->raw = 0;
3287 buffer->frameCount = 0;
3288 return NOT_ENOUGH_DATA;
3289}
3290
Eric Laurenta553c252009-07-17 12:17:14 -07003291status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292{
Eric Laurenta553c252009-07-17 12:17:14 -07003293 sp<ThreadBase> thread = mThread.promote();
3294 if (thread != 0) {
3295 RecordThread *recordThread = (RecordThread *)thread.get();
3296 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003297 } else {
3298 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300}
3301
Eric Laurenta553c252009-07-17 12:17:14 -07003302void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303{
Eric Laurenta553c252009-07-17 12:17:14 -07003304 sp<ThreadBase> thread = mThread.promote();
3305 if (thread != 0) {
3306 RecordThread *recordThread = (RecordThread *)thread.get();
3307 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003308 TrackBase::reset();
3309 // Force overerrun condition to avoid false overrun callback until first data is
3310 // read from buffer
3311 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313}
3314
Eric Laurent3fdb1262009-11-07 00:01:32 -08003315void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3316{
Eric Laurent65b65452010-06-01 23:49:17 -07003317 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003318 (mClient == NULL) ? getpid() : mClient->pid(),
3319 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003320 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003321 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003322 mFrameCount,
3323 mState,
3324 mCblk->sampleRate,
3325 mCblk->server,
3326 mCblk->user);
3327}
3328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329
3330// ----------------------------------------------------------------------------
3331
Eric Laurenta553c252009-07-17 12:17:14 -07003332AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3333 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003334 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 uint32_t sampleRate,
3336 int format,
3337 int channelCount,
3338 int frameCount)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003339 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003340 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341{
Eric Laurenta553c252009-07-17 12:17:14 -07003342
3343 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003344 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003345 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003346 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3347 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3348 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003349 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003350 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3351 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003352 } else {
3353 LOGW("Error creating output track on thread %p", playbackThread);
3354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355}
3356
Eric Laurenta553c252009-07-17 12:17:14 -07003357AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358{
Eric Laurent6c30a712009-08-10 23:22:32 -07003359 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360}
3361
Eric Laurenta553c252009-07-17 12:17:14 -07003362status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363{
3364 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003365 if (status != NO_ERROR) {
3366 return status;
3367 }
3368
3369 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 mRetryCount = 127;
3371 return status;
3372}
3373
Eric Laurenta553c252009-07-17 12:17:14 -07003374void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375{
3376 Track::stop();
3377 clearBufferQueue();
3378 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003379 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380}
3381
Eric Laurenta553c252009-07-17 12:17:14 -07003382bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383{
3384 Buffer *pInBuffer;
3385 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003386 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003387 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 inBuffer.frameCount = frames;
3389 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003390
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003391 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003392
Eric Laurent62443f52009-10-05 20:29:18 -07003393 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003394 start();
3395 sp<ThreadBase> thread = mThread.promote();
3396 if (thread != 0) {
3397 MixerThread *mixerThread = (MixerThread *)thread.get();
3398 if (mCblk->frameCount > frames){
3399 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3400 uint32_t startFrames = (mCblk->frameCount - frames);
3401 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003402 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003403 pInBuffer->frameCount = startFrames;
3404 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003405 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003406 mBufferQueue.add(pInBuffer);
3407 } else {
3408 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 }
Eric Laurenta553c252009-07-17 12:17:14 -07003411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 }
3413
Eric Laurenta553c252009-07-17 12:17:14 -07003414 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 // First write pending buffers, then new data
3416 if (mBufferQueue.size()) {
3417 pInBuffer = mBufferQueue.itemAt(0);
3418 } else {
3419 pInBuffer = &inBuffer;
3420 }
Eric Laurenta553c252009-07-17 12:17:14 -07003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 if (pInBuffer->frameCount == 0) {
3423 break;
3424 }
Eric Laurenta553c252009-07-17 12:17:14 -07003425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 if (mOutBuffer.frameCount == 0) {
3427 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003428 nsecs_t startTime = systemTime();
3429 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003430 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003431 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 break;
3433 }
Eric Laurenta553c252009-07-17 12:17:14 -07003434 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003435 if (waitTimeLeftMs >= waitTimeMs) {
3436 waitTimeLeftMs -= waitTimeMs;
3437 } else {
3438 waitTimeLeftMs = 0;
3439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 }
Eric Laurenta553c252009-07-17 12:17:14 -07003441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003443 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 mCblk->stepUser(outFrames);
3445 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003446 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003448 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 if (pInBuffer->frameCount == 0) {
3451 if (mBufferQueue.size()) {
3452 mBufferQueue.removeAt(0);
3453 delete [] pInBuffer->mBuffer;
3454 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003455 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 -08003456 } else {
3457 break;
3458 }
3459 }
3460 }
Eric Laurenta553c252009-07-17 12:17:14 -07003461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 // If we could not write all frames, allocate a buffer and queue it for next time.
3463 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003464 sp<ThreadBase> thread = mThread.promote();
3465 if (thread != 0 && !thread->standby()) {
3466 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3467 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003468 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003469 pInBuffer->frameCount = inBuffer.frameCount;
3470 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003471 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003472 mBufferQueue.add(pInBuffer);
3473 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3474 } else {
3475 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 }
3478 }
Eric Laurenta553c252009-07-17 12:17:14 -07003479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003481 // 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 -08003482 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003483 if (frames == 0 && mBufferQueue.size() == 0) {
3484 if (mCblk->user < mCblk->frameCount) {
3485 frames = mCblk->frameCount - mCblk->user;
3486 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003487 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003488 pInBuffer->frameCount = frames;
3489 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003490 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003491 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003492 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003493 stop();
3494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 }
3496
Eric Laurenta553c252009-07-17 12:17:14 -07003497 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498}
3499
Eric Laurenta553c252009-07-17 12:17:14 -07003500status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501{
3502 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 status_t result;
3504 audio_track_cblk_t* cblk = mCblk;
3505 uint32_t framesReq = buffer->frameCount;
3506
Eric Laurenta553c252009-07-17 12:17:14 -07003507// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 uint32_t framesAvail = cblk->framesAvailable();
3511
Eric Laurenta553c252009-07-17 12:17:14 -07003512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003514 Mutex::Autolock _l(cblk->lock);
3515 goto start_loop_here;
3516 while (framesAvail == 0) {
3517 active = mActive;
3518 if (UNLIKELY(!active)) {
3519 LOGV("Not active and NO_MORE_BUFFERS");
3520 return AudioTrack::NO_MORE_BUFFERS;
3521 }
3522 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3523 if (result != NO_ERROR) {
3524 return AudioTrack::NO_MORE_BUFFERS;
3525 }
3526 // read the server count again
3527 start_loop_here:
3528 framesAvail = cblk->framesAvailable_l();
3529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 }
3531
Eric Laurenta553c252009-07-17 12:17:14 -07003532// if (framesAvail < framesReq) {
3533// return AudioTrack::NO_MORE_BUFFERS;
3534// }
3535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 if (framesReq > framesAvail) {
3537 framesReq = framesAvail;
3538 }
3539
3540 uint32_t u = cblk->user;
3541 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3542
3543 if (u + framesReq > bufferEnd) {
3544 framesReq = bufferEnd - u;
3545 }
3546
3547 buffer->frameCount = framesReq;
3548 buffer->raw = (void *)cblk->buffer(u);
3549 return NO_ERROR;
3550}
3551
3552
Eric Laurenta553c252009-07-17 12:17:14 -07003553void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554{
3555 size_t size = mBufferQueue.size();
3556 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 for (size_t i = 0; i < size; i++) {
3559 pBuffer = mBufferQueue.itemAt(i);
3560 delete [] pBuffer->mBuffer;
3561 delete pBuffer;
3562 }
3563 mBufferQueue.clear();
3564}
3565
3566// ----------------------------------------------------------------------------
3567
3568AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3569 : RefBase(),
3570 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003571 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 mPid(pid)
3573{
3574 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3575}
3576
Eric Laurentb9481d82009-09-17 05:12:56 -07003577// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578AudioFlinger::Client::~Client()
3579{
Eric Laurentb9481d82009-09-17 05:12:56 -07003580 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581}
3582
3583const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3584{
3585 return mMemoryDealer;
3586}
3587
3588// ----------------------------------------------------------------------------
3589
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003590AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3591 const sp<IAudioFlingerClient>& client,
3592 pid_t pid)
3593 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3594{
3595}
3596
3597AudioFlinger::NotificationClient::~NotificationClient()
3598{
3599 mClient.clear();
3600}
3601
3602void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3603{
3604 sp<NotificationClient> keep(this);
3605 {
3606 mAudioFlinger->removeNotificationClient(mPid);
3607 }
3608}
3609
3610// ----------------------------------------------------------------------------
3611
Eric Laurenta553c252009-07-17 12:17:14 -07003612AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003613 : BnAudioTrack(),
3614 mTrack(track)
3615{
3616}
3617
3618AudioFlinger::TrackHandle::~TrackHandle() {
3619 // just stop the track on deletion, associated resources
3620 // will be freed from the main thread once all pending buffers have
3621 // been played. Unless it's not in the active track list, in which
3622 // case we free everything now...
3623 mTrack->destroy();
3624}
3625
3626status_t AudioFlinger::TrackHandle::start() {
3627 return mTrack->start();
3628}
3629
3630void AudioFlinger::TrackHandle::stop() {
3631 mTrack->stop();
3632}
3633
3634void AudioFlinger::TrackHandle::flush() {
3635 mTrack->flush();
3636}
3637
3638void AudioFlinger::TrackHandle::mute(bool e) {
3639 mTrack->mute(e);
3640}
3641
3642void AudioFlinger::TrackHandle::pause() {
3643 mTrack->pause();
3644}
3645
3646void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3647 mTrack->setVolume(left, right);
3648}
3649
3650sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3651 return mTrack->getCblk();
3652}
3653
Eric Laurent65b65452010-06-01 23:49:17 -07003654status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3655{
3656 return mTrack->attachAuxEffect(EffectId);
3657}
3658
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003659status_t AudioFlinger::TrackHandle::onTransact(
3660 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3661{
3662 return BnAudioTrack::onTransact(code, data, reply, flags);
3663}
3664
3665// ----------------------------------------------------------------------------
3666
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003667sp<IAudioRecord> AudioFlinger::openRecord(
3668 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003669 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003670 uint32_t sampleRate,
3671 int format,
3672 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003673 int frameCount,
3674 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003675 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003676 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003677{
Eric Laurenta553c252009-07-17 12:17:14 -07003678 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003679 sp<RecordHandle> recordHandle;
3680 sp<Client> client;
3681 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003682 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003683 RecordThread *thread;
3684 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003685 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003686
3687 // check calling permissions
3688 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003689 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003690 goto Exit;
3691 }
3692
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003693 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003694 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003695 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003696 thread = checkRecordThread_l(input);
3697 if (thread == NULL) {
3698 lStatus = BAD_VALUE;
3699 goto Exit;
3700 }
3701
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003702 wclient = mClients.valueFor(pid);
3703 if (wclient != NULL) {
3704 client = wclient.promote();
3705 } else {
3706 client = new Client(this, pid);
3707 mClients.add(pid, client);
3708 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003709
Eric Laurent65b65452010-06-01 23:49:17 -07003710 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003711 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003712 lSessionId = *sessionId;
3713 } else {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08003714 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003715 if (sessionId != NULL) {
3716 *sessionId = lSessionId;
3717 }
3718 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003719 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003720 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003721 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003724 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3725 // destructor is called by the TrackBase destructor with mLock held
3726 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 recordTrack.clear();
3728 lStatus = NO_MEMORY;
3729 goto Exit;
3730 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003731
3732 // return to handle to client
3733 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003734 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003735
3736Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003737 if (status) {
3738 *status = lStatus;
3739 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003740 return recordHandle;
3741}
3742
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003743// ----------------------------------------------------------------------------
3744
Eric Laurenta553c252009-07-17 12:17:14 -07003745AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003746 : BnAudioRecord(),
3747 mRecordTrack(recordTrack)
3748{
3749}
3750
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003751AudioFlinger::RecordHandle::~RecordHandle() {
3752 stop();
3753}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003754
3755status_t AudioFlinger::RecordHandle::start() {
3756 LOGV("RecordHandle::start()");
3757 return mRecordTrack->start();
3758}
3759
3760void AudioFlinger::RecordHandle::stop() {
3761 LOGV("RecordHandle::stop()");
3762 mRecordTrack->stop();
3763}
3764
3765sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3766 return mRecordTrack->getCblk();
3767}
3768
3769status_t AudioFlinger::RecordHandle::onTransact(
3770 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3771{
3772 return BnAudioRecord::onTransact(code, data, reply, flags);
3773}
3774
3775// ----------------------------------------------------------------------------
3776
Dima Zavin31f188892011-04-18 16:57:27 -07003777AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
Eric Laurent49f02be2009-11-19 09:00:56 -08003778 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003779 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003780{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003781 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07003782 mReqSampleRate = sampleRate;
3783 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003784}
3785
Eric Laurenta553c252009-07-17 12:17:14 -07003786
3787AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003788{
Eric Laurenta553c252009-07-17 12:17:14 -07003789 delete[] mRsmpInBuffer;
3790 if (mResampler != 0) {
3791 delete mResampler;
3792 delete[] mRsmpOutBuffer;
3793 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003794}
3795
Eric Laurenta553c252009-07-17 12:17:14 -07003796void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003797{
Eric Laurenta553c252009-07-17 12:17:14 -07003798 const size_t SIZE = 256;
3799 char buffer[SIZE];
3800
3801 snprintf(buffer, SIZE, "Record Thread %p", this);
3802
3803 run(buffer, PRIORITY_URGENT_AUDIO);
3804}
Eric Laurent49f02be2009-11-19 09:00:56 -08003805
Eric Laurenta553c252009-07-17 12:17:14 -07003806bool AudioFlinger::RecordThread::threadLoop()
3807{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003808 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003809 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003810
Eric Laurent4712baa2010-09-30 16:12:31 -07003811 nsecs_t lastWarning = 0;
3812
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003813 // start recording
3814 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003815
Eric Laurenta553c252009-07-17 12:17:14 -07003816 processConfigEvents();
3817
3818 { // scope for mLock
3819 Mutex::Autolock _l(mLock);
3820 checkForNewParameters_l();
3821 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3822 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07003823 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07003824 mStandby = true;
3825 }
3826
3827 if (exitPending()) break;
3828
3829 LOGV("RecordThread: loop stopping");
3830 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003831 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003832 LOGV("RecordThread: loop starting");
3833 continue;
3834 }
3835 if (mActiveTrack != 0) {
3836 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003837 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07003838 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003839 mStandby = true;
3840 }
Eric Laurenta553c252009-07-17 12:17:14 -07003841 mActiveTrack.clear();
3842 mStartStopCond.broadcast();
3843 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003844 if (mReqChannelCount != mActiveTrack->channelCount()) {
3845 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003846 mStartStopCond.broadcast();
3847 } else if (mBytesRead != 0) {
3848 // record start succeeds only if first read from audio input
3849 // succeeds
3850 if (mBytesRead > 0) {
3851 mActiveTrack->mState = TrackBase::ACTIVE;
3852 } else {
3853 mActiveTrack.clear();
3854 }
3855 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003856 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003857 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003858 }
Eric Laurenta553c252009-07-17 12:17:14 -07003859 }
3860 }
3861
3862 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003863 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3864 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003865 usleep(5000);
3866 continue;
3867 }
Eric Laurenta553c252009-07-17 12:17:14 -07003868 buffer.frameCount = mFrameCount;
3869 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3870 size_t framesOut = buffer.frameCount;
3871 if (mResampler == 0) {
3872 // no resampling
3873 while (framesOut) {
3874 size_t framesIn = mFrameCount - mRsmpInIndex;
3875 if (framesIn) {
3876 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3877 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3878 if (framesIn > framesOut)
3879 framesIn = framesOut;
3880 mRsmpInIndex += framesIn;
3881 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003882 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003883 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07003884 memcpy(dst, src, framesIn * mFrameSize);
3885 } else {
3886 int16_t *src16 = (int16_t *)src;
3887 int16_t *dst16 = (int16_t *)dst;
3888 if (mChannelCount == 1) {
3889 while (framesIn--) {
3890 *dst16++ = *src16;
3891 *dst16++ = *src16++;
3892 }
3893 } else {
3894 while (framesIn--) {
3895 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3896 src16 += 2;
3897 }
3898 }
3899 }
3900 }
3901 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003902 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003903 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07003904 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003905 framesOut = 0;
3906 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07003907 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003908 mRsmpInIndex = 0;
3909 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003910 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003911 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003912 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003913 // Force input into standby so that it tries to
3914 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07003915 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurentba8811f2010-03-02 18:38:06 -08003916 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003917 }
Eric Laurenta553c252009-07-17 12:17:14 -07003918 mRsmpInIndex = mFrameCount;
3919 framesOut = 0;
3920 buffer.frameCount = 0;
3921 }
3922 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003923 }
3924 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003925 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003926
Eric Laurenta553c252009-07-17 12:17:14 -07003927 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3928 // alter output frame count as if we were expecting stereo samples
3929 if (mChannelCount == 1 && mReqChannelCount == 1) {
3930 framesOut >>= 1;
3931 }
3932 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3933 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3934 // are 32 bit aligned which should be always true.
3935 if (mChannelCount == 2 && mReqChannelCount == 1) {
3936 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3937 // the resampler always outputs stereo samples: do post stereo to mono conversion
3938 int16_t *src = (int16_t *)mRsmpOutBuffer;
3939 int16_t *dst = buffer.i16;
3940 while (framesOut--) {
3941 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3942 src += 2;
3943 }
3944 } else {
3945 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3946 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003947
Eric Laurenta553c252009-07-17 12:17:14 -07003948 }
3949 mActiveTrack->releaseBuffer(&buffer);
3950 mActiveTrack->overflow();
3951 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003952 // client isn't retrieving buffers fast enough
3953 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07003954 if (!mActiveTrack->setOverflow()) {
3955 nsecs_t now = systemTime();
3956 if ((now - lastWarning) > kWarningThrottle) {
3957 LOGW("RecordThread: buffer overflow");
3958 lastWarning = now;
3959 }
3960 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003961 // Release the processor for a while before asking for a new buffer.
3962 // This will give the application more chance to read from the buffer and
3963 // clear the overflow.
3964 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003965 }
3966 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003967 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003968
Eric Laurenta553c252009-07-17 12:17:14 -07003969 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07003970 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003971 }
Eric Laurenta553c252009-07-17 12:17:14 -07003972 mActiveTrack.clear();
3973
Eric Laurent49f02be2009-11-19 09:00:56 -08003974 mStartStopCond.broadcast();
3975
Eric Laurenta553c252009-07-17 12:17:14 -07003976 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003977 return false;
3978}
3979
Eric Laurenta553c252009-07-17 12:17:14 -07003980status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003981{
Eric Laurenta553c252009-07-17 12:17:14 -07003982 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003983 sp <ThreadBase> strongMe = this;
3984 status_t status = NO_ERROR;
3985 {
3986 AutoMutex lock(&mLock);
3987 if (mActiveTrack != 0) {
3988 if (recordTrack != mActiveTrack.get()) {
3989 status = -EBUSY;
3990 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003991 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003992 }
3993 return status;
3994 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003995
Eric Laurent49f02be2009-11-19 09:00:56 -08003996 recordTrack->mState = TrackBase::IDLE;
3997 mActiveTrack = recordTrack;
3998 mLock.unlock();
3999 status_t status = AudioSystem::startInput(mId);
4000 mLock.lock();
4001 if (status != NO_ERROR) {
4002 mActiveTrack.clear();
4003 return status;
4004 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004005 mRsmpInIndex = mFrameCount;
4006 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004007 if (mResampler != NULL) {
4008 mResampler->reset();
4009 }
4010 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004011 // signal thread to start
4012 LOGV("Signal record thread");
4013 mWaitWorkCV.signal();
4014 // do not wait for mStartStopCond if exiting
4015 if (mExiting) {
4016 mActiveTrack.clear();
4017 status = INVALID_OPERATION;
4018 goto startError;
4019 }
4020 mStartStopCond.wait(mLock);
4021 if (mActiveTrack == 0) {
4022 LOGV("Record failed to start");
4023 status = BAD_VALUE;
4024 goto startError;
4025 }
Eric Laurenta553c252009-07-17 12:17:14 -07004026 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004027 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004028 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004029startError:
4030 AudioSystem::stopInput(mId);
4031 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004032}
4033
Eric Laurenta553c252009-07-17 12:17:14 -07004034void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4035 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004036 sp <ThreadBase> strongMe = this;
4037 {
4038 AutoMutex lock(&mLock);
4039 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4040 mActiveTrack->mState = TrackBase::PAUSING;
4041 // do not wait for mStartStopCond if exiting
4042 if (mExiting) {
4043 return;
4044 }
4045 mStartStopCond.wait(mLock);
4046 // if we have been restarted, recordTrack == mActiveTrack.get() here
4047 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4048 mLock.unlock();
4049 AudioSystem::stopInput(mId);
4050 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004051 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004052 }
4053 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004054 }
4055}
4056
Eric Laurenta553c252009-07-17 12:17:14 -07004057status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058{
4059 const size_t SIZE = 256;
4060 char buffer[SIZE];
4061 String8 result;
4062 pid_t pid = 0;
4063
Eric Laurent3fdb1262009-11-07 00:01:32 -08004064 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4065 result.append(buffer);
4066
4067 if (mActiveTrack != 0) {
4068 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07004069 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004070 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004072
4073 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4074 result.append(buffer);
4075 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4076 result.append(buffer);
4077 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4078 result.append(buffer);
4079 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4080 result.append(buffer);
4081 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4082 result.append(buffer);
4083
4084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 } else {
4086 result.append("No record client\n");
4087 }
4088 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004089
4090 dumpBase(fd, args);
4091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 return NO_ERROR;
4093}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004094
Eric Laurenta553c252009-07-17 12:17:14 -07004095status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4096{
4097 size_t framesReq = buffer->frameCount;
4098 size_t framesReady = mFrameCount - mRsmpInIndex;
4099 int channelCount;
4100
4101 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004102 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004103 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004104 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004105 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004106 // Force input into standby so that it tries to
4107 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004108 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurentba8811f2010-03-02 18:38:06 -08004109 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004110 }
Eric Laurenta553c252009-07-17 12:17:14 -07004111 buffer->raw = 0;
4112 buffer->frameCount = 0;
4113 return NOT_ENOUGH_DATA;
4114 }
4115 mRsmpInIndex = 0;
4116 framesReady = mFrameCount;
4117 }
4118
4119 if (framesReq > framesReady) {
4120 framesReq = framesReady;
4121 }
4122
4123 if (mChannelCount == 1 && mReqChannelCount == 2) {
4124 channelCount = 1;
4125 } else {
4126 channelCount = 2;
4127 }
4128 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4129 buffer->frameCount = framesReq;
4130 return NO_ERROR;
4131}
4132
4133void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4134{
4135 mRsmpInIndex += buffer->frameCount;
4136 buffer->frameCount = 0;
4137}
4138
4139bool AudioFlinger::RecordThread::checkForNewParameters_l()
4140{
4141 bool reconfig = false;
4142
Eric Laurent8fce46a2009-08-04 09:45:33 -07004143 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004144 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004145 String8 keyValuePair = mNewParameters[0];
4146 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004147 int value;
4148 int reqFormat = mFormat;
4149 int reqSamplingRate = mReqSampleRate;
4150 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004151
Eric Laurenta553c252009-07-17 12:17:14 -07004152 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4153 reqSamplingRate = value;
4154 reconfig = true;
4155 }
4156 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4157 reqFormat = value;
4158 reconfig = true;
4159 }
4160 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004161 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004162 reconfig = true;
4163 }
4164 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4165 // do not accept frame count changes if tracks are open as the track buffer
4166 // size depends on frame count and correct behavior would not be garantied
4167 // if frame count is changed after track creation
4168 if (mActiveTrack != 0) {
4169 status = INVALID_OPERATION;
4170 } else {
4171 reconfig = true;
4172 }
4173 }
4174 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004175 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004176 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004177 mInput->stream->common.standby(&mInput->stream->common);
4178 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004179 }
4180 if (reconfig) {
4181 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004182 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004183 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004184 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4185 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004186 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004187 status = NO_ERROR;
4188 }
4189 if (status == NO_ERROR) {
4190 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004191 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004192 }
4193 }
4194 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004195
4196 mNewParameters.removeAt(0);
4197
Eric Laurenta553c252009-07-17 12:17:14 -07004198 mParamStatus = status;
4199 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004200 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004201 }
4202 return reconfig;
4203}
4204
4205String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4206{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004207 char *s;
4208 String8 out_s8;
4209
Dima Zavin31f188892011-04-18 16:57:27 -07004210 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004211 out_s8 = String8(s);
4212 free(s);
4213 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004214}
4215
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004216void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004217 AudioSystem::OutputDescriptor desc;
4218 void *param2 = 0;
4219
4220 switch (event) {
4221 case AudioSystem::INPUT_OPENED:
4222 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004223 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004224 desc.samplingRate = mSampleRate;
4225 desc.format = mFormat;
4226 desc.frameCount = mFrameCount;
4227 desc.latency = 0;
4228 param2 = &desc;
4229 break;
4230
4231 case AudioSystem::INPUT_CLOSED:
4232 default:
4233 break;
4234 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004235 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004236}
4237
4238void AudioFlinger::RecordThread::readInputParameters()
4239{
4240 if (mRsmpInBuffer) delete mRsmpInBuffer;
4241 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4242 if (mResampler) delete mResampler;
4243 mResampler = 0;
4244
Dima Zavin31f188892011-04-18 16:57:27 -07004245 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4246 mChannels = mInput->stream->common.get_channels(&mInput->stream->common);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004247 mChannelCount = (uint16_t)popcount(mChannels);
Dima Zavin31f188892011-04-18 16:57:27 -07004248 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4249 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4250 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004251 mFrameCount = mInputBytes / mFrameSize;
4252 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4253
4254 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4255 {
4256 int channelCount;
4257 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4258 // stereo to mono post process as the resampler always outputs stereo.
4259 if (mChannelCount == 1 && mReqChannelCount == 2) {
4260 channelCount = 1;
4261 } else {
4262 channelCount = 2;
4263 }
4264 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4265 mResampler->setSampleRate(mSampleRate);
4266 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4267 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4268
4269 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4270 if (mChannelCount == 1 && mReqChannelCount == 1) {
4271 mFrameCount >>= 1;
4272 }
4273
4274 }
4275 mRsmpInIndex = mFrameCount;
4276}
4277
Eric Laurent47d0a922010-02-26 02:47:27 -08004278unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4279{
Dima Zavin31f188892011-04-18 16:57:27 -07004280 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004281}
4282
Eric Laurenta553c252009-07-17 12:17:14 -07004283// ----------------------------------------------------------------------------
4284
Eric Laurentddb78e72009-07-28 08:44:33 -07004285int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004286 uint32_t *pSamplingRate,
4287 uint32_t *pFormat,
4288 uint32_t *pChannels,
4289 uint32_t *pLatencyMs,
4290 uint32_t flags)
4291{
4292 status_t status;
4293 PlaybackThread *thread = NULL;
4294 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4295 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4296 uint32_t format = pFormat ? *pFormat : 0;
4297 uint32_t channels = pChannels ? *pChannels : 0;
4298 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004299 audio_stream_out_t *outStream;
4300 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004301
4302 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4303 pDevices ? *pDevices : 0,
4304 samplingRate,
4305 format,
4306 channels,
4307 flags);
4308
4309 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004310 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004311 }
Dima Zavin31f188892011-04-18 16:57:27 -07004312
Eric Laurenta553c252009-07-17 12:17:14 -07004313 Mutex::Autolock _l(mLock);
4314
Dima Zavin31f188892011-04-18 16:57:27 -07004315 outHwDev = findSuitableHwDev_l(*pDevices);
4316 if (outHwDev == NULL)
4317 return 0;
4318
4319 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4320 &channels, &samplingRate, &outStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004321 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004322 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004323 samplingRate,
4324 format,
4325 channels,
4326 status);
4327
4328 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004329 if (outStream != NULL) {
4330 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004331 int id = nextUniqueId_l();
Dima Zavin31f188892011-04-18 16:57:27 -07004332
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004333 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4334 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4335 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004336 thread = new DirectOutputThread(this, output, id, *pDevices);
4337 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004338 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004339 thread = new MixerThread(this, output, id, *pDevices);
4340 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004341 }
Eric Laurent65b65452010-06-01 23:49:17 -07004342 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004343
4344 if (pSamplingRate) *pSamplingRate = samplingRate;
4345 if (pFormat) *pFormat = format;
4346 if (pChannels) *pChannels = channels;
4347 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004348
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004349 // notify client processes of the new output creation
4350 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004351 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004352 }
4353
Eric Laurent9cc489a22009-12-05 05:20:01 -08004354 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004355}
4356
Eric Laurentddb78e72009-07-28 08:44:33 -07004357int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004358{
4359 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004360 MixerThread *thread1 = checkMixerThread_l(output1);
4361 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004362
Eric Laurentddb78e72009-07-28 08:44:33 -07004363 if (thread1 == NULL || thread2 == NULL) {
4364 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4365 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004366 }
4367
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004368 int id = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004369 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004370 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004371 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004372 // notify client processes of the new output creation
4373 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004374 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004375}
4376
Eric Laurentddb78e72009-07-28 08:44:33 -07004377status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004378{
Eric Laurent49018a52009-08-04 08:37:05 -07004379 // keep strong reference on the playback thread so that
4380 // it is not destroyed while exit() is executed
4381 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004382 {
4383 Mutex::Autolock _l(mLock);
4384 thread = checkPlaybackThread_l(output);
4385 if (thread == NULL) {
4386 return BAD_VALUE;
4387 }
4388
Eric Laurentddb78e72009-07-28 08:44:33 -07004389 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004390
4391 if (thread->type() == PlaybackThread::MIXER) {
4392 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004393 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4394 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004395 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004396 }
4397 }
4398 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004399 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004400 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004401 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004402 }
4403 thread->exit();
4404
Eric Laurent49018a52009-08-04 08:37:05 -07004405 if (thread->type() != PlaybackThread::DUPLICATING) {
Dima Zavin31f188892011-04-18 16:57:27 -07004406 AudioStreamOut *out = thread->getOutput();
4407 out->hwDev->close_output_stream(out->hwDev, out->stream);
4408 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07004409 }
Eric Laurenta553c252009-07-17 12:17:14 -07004410 return NO_ERROR;
4411}
4412
Eric Laurentddb78e72009-07-28 08:44:33 -07004413status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004414{
4415 Mutex::Autolock _l(mLock);
4416 PlaybackThread *thread = checkPlaybackThread_l(output);
4417
4418 if (thread == NULL) {
4419 return BAD_VALUE;
4420 }
4421
Eric Laurentddb78e72009-07-28 08:44:33 -07004422 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004423 thread->suspend();
4424
4425 return NO_ERROR;
4426}
4427
Eric Laurentddb78e72009-07-28 08:44:33 -07004428status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004429{
4430 Mutex::Autolock _l(mLock);
4431 PlaybackThread *thread = checkPlaybackThread_l(output);
4432
4433 if (thread == NULL) {
4434 return BAD_VALUE;
4435 }
4436
Eric Laurentddb78e72009-07-28 08:44:33 -07004437 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004438
4439 thread->restore();
4440
4441 return NO_ERROR;
4442}
4443
Eric Laurentddb78e72009-07-28 08:44:33 -07004444int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004445 uint32_t *pSamplingRate,
4446 uint32_t *pFormat,
4447 uint32_t *pChannels,
4448 uint32_t acoustics)
4449{
4450 status_t status;
4451 RecordThread *thread = NULL;
4452 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4453 uint32_t format = pFormat ? *pFormat : 0;
4454 uint32_t channels = pChannels ? *pChannels : 0;
4455 uint32_t reqSamplingRate = samplingRate;
4456 uint32_t reqFormat = format;
4457 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07004458 audio_stream_in_t *inStream;
4459 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004460
4461 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004462 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004463 }
Dima Zavin31f188892011-04-18 16:57:27 -07004464
Eric Laurenta553c252009-07-17 12:17:14 -07004465 Mutex::Autolock _l(mLock);
4466
Dima Zavin31f188892011-04-18 16:57:27 -07004467 inHwDev = findSuitableHwDev_l(*pDevices);
4468 if (inHwDev == NULL)
4469 return 0;
4470
4471 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4472 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004473 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07004474 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004475 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004476 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004477 samplingRate,
4478 format,
4479 channels,
4480 acoustics,
4481 status);
4482
4483 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4484 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4485 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07004486 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004487 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07004488 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004489 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004490 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07004491 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4492 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004493 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07004494 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004495 }
4496
Dima Zavin31f188892011-04-18 16:57:27 -07004497 if (inStream != NULL) {
4498 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4499
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004500 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004501 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004502 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4503 mRecordThreads.add(id, thread);
4504 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004505 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4506 if (pFormat) *pFormat = format;
4507 if (pChannels) *pChannels = reqChannels;
4508
Dima Zavin31f188892011-04-18 16:57:27 -07004509 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004510
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004511 // notify client processes of the new input creation
4512 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004513 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004514 }
4515
Eric Laurent9cc489a22009-12-05 05:20:01 -08004516 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004517}
4518
Eric Laurentddb78e72009-07-28 08:44:33 -07004519status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004520{
Eric Laurent49018a52009-08-04 08:37:05 -07004521 // keep strong reference on the record thread so that
4522 // it is not destroyed while exit() is executed
4523 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004524 {
4525 Mutex::Autolock _l(mLock);
4526 thread = checkRecordThread_l(input);
4527 if (thread == NULL) {
4528 return BAD_VALUE;
4529 }
4530
Eric Laurentddb78e72009-07-28 08:44:33 -07004531 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004532 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004533 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004534 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004535 }
4536 thread->exit();
4537
Dima Zavin31f188892011-04-18 16:57:27 -07004538 AudioStreamIn *in = thread->getInput();
4539 in->hwDev->close_input_stream(in->hwDev, in->stream);
4540 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07004541
Eric Laurenta553c252009-07-17 12:17:14 -07004542 return NO_ERROR;
4543}
4544
Eric Laurentddb78e72009-07-28 08:44:33 -07004545status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004546{
4547 Mutex::Autolock _l(mLock);
4548 MixerThread *dstThread = checkMixerThread_l(output);
4549 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004550 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004551 return BAD_VALUE;
4552 }
4553
Eric Laurentddb78e72009-07-28 08:44:33 -07004554 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004555 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004556
4557 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004558 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004559 if (thread != dstThread &&
4560 thread->type() != PlaybackThread::DIRECT) {
4561 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004562 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004563 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004564 }
Eric Laurentd069f322009-09-01 05:56:26 -07004565
Eric Laurenta553c252009-07-17 12:17:14 -07004566 return NO_ERROR;
4567}
4568
Eric Laurent65b65452010-06-01 23:49:17 -07004569
4570int AudioFlinger::newAudioSessionId()
4571{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004572 AutoMutex _l(mLock);
4573 return nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004574}
4575
Eric Laurenta553c252009-07-17 12:17:14 -07004576// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004577AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004578{
4579 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004580 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4581 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004582 }
Eric Laurenta553c252009-07-17 12:17:14 -07004583 return thread;
4584}
4585
4586// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004587AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004588{
4589 PlaybackThread *thread = checkPlaybackThread_l(output);
4590 if (thread != NULL) {
4591 if (thread->type() == PlaybackThread::DIRECT) {
4592 thread = NULL;
4593 }
4594 }
4595 return (MixerThread *)thread;
4596}
4597
4598// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004599AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004600{
4601 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004602 if (mRecordThreads.indexOfKey(input) >= 0) {
4603 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004604 }
Eric Laurenta553c252009-07-17 12:17:14 -07004605 return thread;
4606}
4607
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004608// nextUniqueId_l() must be called with AudioFlinger::mLock held
4609int AudioFlinger::nextUniqueId_l()
Eric Laurent65b65452010-06-01 23:49:17 -07004610{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004611 return mNextUniqueId++;
Eric Laurent65b65452010-06-01 23:49:17 -07004612}
4613
4614// ----------------------------------------------------------------------------
4615// Effect management
4616// ----------------------------------------------------------------------------
4617
4618
4619status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4620{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004621 // check calling permissions
4622 if (!settingsAllowed()) {
4623 return PERMISSION_DENIED;
4624 }
4625 // only allow libraries loaded from /system/lib/soundfx for now
4626 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4627 return PERMISSION_DENIED;
4628 }
4629
Eric Laurent65b65452010-06-01 23:49:17 -07004630 Mutex::Autolock _l(mLock);
4631 return EffectLoadLibrary(libPath, handle);
4632}
4633
4634status_t AudioFlinger::unloadEffectLibrary(int handle)
4635{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004636 // check calling permissions
4637 if (!settingsAllowed()) {
4638 return PERMISSION_DENIED;
4639 }
4640
Eric Laurent65b65452010-06-01 23:49:17 -07004641 Mutex::Autolock _l(mLock);
4642 return EffectUnloadLibrary(handle);
4643}
4644
4645status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4646{
4647 Mutex::Autolock _l(mLock);
4648 return EffectQueryNumberEffects(numEffects);
4649}
4650
Eric Laurent53334cd2010-06-23 17:38:20 -07004651status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004652{
4653 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004654 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004655}
4656
4657status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4658{
4659 Mutex::Autolock _l(mLock);
4660 return EffectGetDescriptor(pUuid, descriptor);
4661}
4662
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004663
4664// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4665static const effect_uuid_t VISUALIZATION_UUID_ =
4666 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4667
Eric Laurent65b65452010-06-01 23:49:17 -07004668sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4669 effect_descriptor_t *pDesc,
4670 const sp<IEffectClient>& effectClient,
4671 int32_t priority,
4672 int output,
4673 int sessionId,
4674 status_t *status,
4675 int *id,
4676 int *enabled)
4677{
4678 status_t lStatus = NO_ERROR;
4679 sp<EffectHandle> handle;
4680 effect_interface_t itfe;
4681 effect_descriptor_t desc;
4682 sp<Client> client;
4683 wp<Client> wclient;
4684
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004685 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4686 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004687
4688 if (pDesc == NULL) {
4689 lStatus = BAD_VALUE;
4690 goto Exit;
4691 }
4692
Eric Laurent98c92592010-09-23 16:10:16 -07004693 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004694 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07004695 lStatus = PERMISSION_DENIED;
4696 goto Exit;
4697 }
4698
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004699 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07004700 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004701 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07004702 lStatus = PERMISSION_DENIED;
4703 goto Exit;
4704 }
4705
4706 // check recording permission for visualizer
4707 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4708 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4709 !recordingAllowed()) {
4710 lStatus = PERMISSION_DENIED;
4711 goto Exit;
4712 }
4713
4714 if (output == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004715 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07004716 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004717 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07004718 lStatus = BAD_VALUE;
4719 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004720 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07004721 // if the output returned by getOutputForEffect() is removed before we lock the
4722 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4723 // and we will exit safely
4724 output = AudioSystem::getOutputForEffect(&desc);
4725 }
4726 }
4727
Eric Laurent65b65452010-06-01 23:49:17 -07004728 {
4729 Mutex::Autolock _l(mLock);
4730
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004731
Eric Laurent65b65452010-06-01 23:49:17 -07004732 if (!EffectIsNullUuid(&pDesc->uuid)) {
4733 // if uuid is specified, request effect descriptor
4734 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4735 if (lStatus < 0) {
4736 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4737 goto Exit;
4738 }
4739 } else {
4740 // if uuid is not specified, look for an available implementation
4741 // of the required type in effect factory
4742 if (EffectIsNullUuid(&pDesc->type)) {
4743 LOGW("createEffect() no effect type");
4744 lStatus = BAD_VALUE;
4745 goto Exit;
4746 }
4747 uint32_t numEffects = 0;
4748 effect_descriptor_t d;
4749 bool found = false;
4750
4751 lStatus = EffectQueryNumberEffects(&numEffects);
4752 if (lStatus < 0) {
4753 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4754 goto Exit;
4755 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004756 for (uint32_t i = 0; i < numEffects; i++) {
4757 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004758 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004759 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004760 continue;
4761 }
4762 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4763 // If matching type found save effect descriptor. If the session is
4764 // 0 and the effect is not auxiliary, continue enumeration in case
4765 // an auxiliary version of this effect type is available
4766 found = true;
4767 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004768 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004769 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4770 break;
4771 }
4772 }
4773 }
4774 if (!found) {
4775 lStatus = BAD_VALUE;
4776 LOGW("createEffect() effect not found");
4777 goto Exit;
4778 }
4779 // For same effect type, chose auxiliary version over insert version if
4780 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004781 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004782 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4783 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4784 }
4785 }
4786
4787 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004788 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004789 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4790 lStatus = INVALID_OPERATION;
4791 goto Exit;
4792 }
4793
4794 // return effect descriptor
4795 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4796
4797 // If output is not specified try to find a matching audio session ID in one of the
4798 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07004799 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4800 // because of code checking output when entering the function.
Eric Laurent65b65452010-06-01 23:49:17 -07004801 if (output == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07004802 // look for the thread where the specified audio session is present
4803 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4804 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4805 output = mPlaybackThreads.keyAt(i);
4806 break;
Eric Laurent493941b2010-07-28 01:32:47 -07004807 }
Eric Laurent65b65452010-06-01 23:49:17 -07004808 }
Eric Laurent98c92592010-09-23 16:10:16 -07004809 // If no output thread contains the requested session ID, default to
4810 // first output. The effect chain will be moved to the correct output
4811 // thread when a track with the same session ID is created
4812 if (output == 0 && mPlaybackThreads.size()) {
4813 output = mPlaybackThreads.keyAt(0);
4814 }
Eric Laurent65b65452010-06-01 23:49:17 -07004815 }
Eric Laurent98c92592010-09-23 16:10:16 -07004816 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004817 PlaybackThread *thread = checkPlaybackThread_l(output);
4818 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004819 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004820 lStatus = BAD_VALUE;
4821 goto Exit;
4822 }
4823
Eric Laurent98c92592010-09-23 16:10:16 -07004824 // TODO: allow attachment of effect to inputs
4825
Eric Laurent65b65452010-06-01 23:49:17 -07004826 wclient = mClients.valueFor(pid);
4827
4828 if (wclient != NULL) {
4829 client = wclient.promote();
4830 } else {
4831 client = new Client(this, pid);
4832 mClients.add(pid, client);
4833 }
4834
4835 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004836 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4837 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004838 if (handle != 0 && id != NULL) {
4839 *id = handle->id();
4840 }
4841 }
4842
4843Exit:
4844 if(status) {
4845 *status = lStatus;
4846 }
4847 return handle;
4848}
4849
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004850status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4851{
4852 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4853 session, srcOutput, dstOutput);
4854 Mutex::Autolock _l(mLock);
4855 if (srcOutput == dstOutput) {
4856 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4857 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004858 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004859 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4860 if (srcThread == NULL) {
4861 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4862 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004863 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004864 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4865 if (dstThread == NULL) {
4866 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4867 return BAD_VALUE;
4868 }
4869
4870 Mutex::Autolock _dl(dstThread->mLock);
4871 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07004872 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004873
Eric Laurent53334cd2010-06-23 17:38:20 -07004874 return NO_ERROR;
4875}
4876
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004877// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4878status_t AudioFlinger::moveEffectChain_l(int session,
4879 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07004880 AudioFlinger::PlaybackThread *dstThread,
4881 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004882{
4883 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4884 session, srcThread, dstThread);
4885
4886 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4887 if (chain == 0) {
4888 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4889 session, srcThread);
4890 return INVALID_OPERATION;
4891 }
4892
Eric Laurent493941b2010-07-28 01:32:47 -07004893 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004894 // so that a new chain is created with correct parameters when first effect is added. This is
4895 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4896 // removed.
4897 srcThread->removeEffectChain_l(chain);
4898
4899 // transfer all effects one by one so that new effect chain is created on new thread with
4900 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07004901 int dstOutput = dstThread->id();
4902 sp<EffectChain> dstChain;
4903 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004904 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4905 while (effect != 0) {
4906 srcThread->removeEffect_l(effect);
4907 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07004908 // if the move request is not received from audio policy manager, the effect must be
4909 // re-registered with the new strategy and output
4910 if (dstChain == 0) {
4911 dstChain = effect->chain().promote();
4912 if (dstChain == 0) {
4913 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4914 srcThread->addEffect_l(effect);
4915 return NO_INIT;
4916 }
4917 strategy = dstChain->strategy();
4918 }
4919 if (reRegister) {
4920 AudioSystem::unregisterEffect(effect->id());
4921 AudioSystem::registerEffect(&effect->desc(),
4922 dstOutput,
4923 strategy,
4924 session,
4925 effect->id());
4926 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004927 effect = chain->getEffectFromId_l(0);
4928 }
4929
4930 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004931}
4932
Eric Laurent65b65452010-06-01 23:49:17 -07004933// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4934sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4935 const sp<AudioFlinger::Client>& client,
4936 const sp<IEffectClient>& effectClient,
4937 int32_t priority,
4938 int sessionId,
4939 effect_descriptor_t *desc,
4940 int *enabled,
4941 status_t *status
4942 )
4943{
4944 sp<EffectModule> effect;
4945 sp<EffectHandle> handle;
4946 status_t lStatus;
4947 sp<Track> track;
4948 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004949 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004950 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004951 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004952
4953 if (mOutput == 0) {
4954 LOGW("createEffect_l() Audio driver not initialized.");
4955 lStatus = NO_INIT;
4956 goto Exit;
4957 }
4958
4959 // Do not allow auxiliary effect on session other than 0
4960 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004961 sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004962 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4963 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004964 lStatus = BAD_VALUE;
4965 goto Exit;
4966 }
4967
4968 // Do not allow effects with session ID 0 on direct output or duplicating threads
4969 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004970 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004971 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4972 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004973 lStatus = BAD_VALUE;
4974 goto Exit;
4975 }
4976
4977 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4978
4979 { // scope for mLock
4980 Mutex::Autolock _l(mLock);
4981
4982 // check for existing effect chain with the requested audio session
4983 chain = getEffectChain_l(sessionId);
4984 if (chain == 0) {
4985 // create a new chain for this session
4986 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4987 chain = new EffectChain(this, sessionId);
4988 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004989 chain->setStrategy(getStrategyForSession_l(sessionId));
4990 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004991 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004992 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004993 }
4994
4995 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4996
4997 if (effect == 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004998 int id = mAudioFlinger->nextUniqueId_l();
Eric Laurent53334cd2010-06-23 17:38:20 -07004999 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005000 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005001 if (lStatus != NO_ERROR) {
5002 goto Exit;
5003 }
5004 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005005 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005006 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005007 lStatus = effect->status();
5008 if (lStatus != NO_ERROR) {
5009 goto Exit;
5010 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005011 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005012 if (lStatus != NO_ERROR) {
5013 goto Exit;
5014 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005015 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005016
5017 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005018 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005019 }
5020 // create effect handle and connect it to effect module
5021 handle = new EffectHandle(effect, client, effectClient, priority);
5022 lStatus = effect->addHandle(handle);
5023 if (enabled) {
5024 *enabled = (int)effect->isEnabled();
5025 }
5026 }
5027
5028Exit:
5029 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005030 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005031 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005032 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005033 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005034 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005035 AudioSystem::unregisterEffect(effect->id());
5036 }
5037 if (chainCreated) {
5038 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005039 }
Eric Laurent65b65452010-06-01 23:49:17 -07005040 handle.clear();
5041 }
5042
5043 if(status) {
5044 *status = lStatus;
5045 }
5046 return handle;
5047}
5048
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005049// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5050// PlaybackThread::mLock held
5051status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5052{
5053 // check for existing effect chain with the requested audio session
5054 int sessionId = effect->sessionId();
5055 sp<EffectChain> chain = getEffectChain_l(sessionId);
5056 bool chainCreated = false;
5057
5058 if (chain == 0) {
5059 // create a new chain for this session
5060 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5061 chain = new EffectChain(this, sessionId);
5062 addEffectChain_l(chain);
5063 chain->setStrategy(getStrategyForSession_l(sessionId));
5064 chainCreated = true;
5065 }
5066 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5067
5068 if (chain->getEffectFromId_l(effect->id()) != 0) {
5069 LOGW("addEffect_l() %p effect %s already present in chain %p",
5070 this, effect->desc().name, chain.get());
5071 return BAD_VALUE;
5072 }
5073
5074 status_t status = chain->addEffect_l(effect);
5075 if (status != NO_ERROR) {
5076 if (chainCreated) {
5077 removeEffectChain_l(chain);
5078 }
5079 return status;
5080 }
5081
5082 effect->setDevice(mDevice);
5083 effect->setMode(mAudioFlinger->getMode());
5084 return NO_ERROR;
5085}
5086
5087void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5088
5089 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005090 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005091 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5092 detachAuxEffect_l(effect->id());
5093 }
5094
5095 sp<EffectChain> chain = effect->chain().promote();
5096 if (chain != 0) {
5097 // remove effect chain if removing last effect
5098 if (chain->removeEffect_l(effect) == 0) {
5099 removeEffectChain_l(chain);
5100 }
5101 } else {
5102 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5103 }
5104}
5105
5106void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5107 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005108 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005109 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005110 // delete the effect module if removing last handle on it
5111 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005112 removeEffect_l(effect);
5113 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07005114 }
5115}
5116
Eric Laurent65b65452010-06-01 23:49:17 -07005117status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5118{
5119 int session = chain->sessionId();
5120 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005121 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005122
5123 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005124 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005125 // Only one effect chain can be present in direct output thread and it uses
5126 // the mix buffer as input
5127 if (mType != DIRECT) {
5128 size_t numSamples = mFrameCount * mChannelCount;
5129 buffer = new int16_t[numSamples];
5130 memset(buffer, 0, numSamples * sizeof(int16_t));
5131 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5132 ownsBuffer = true;
5133 }
Eric Laurent65b65452010-06-01 23:49:17 -07005134
Eric Laurent53334cd2010-06-23 17:38:20 -07005135 // Attach all tracks with same session ID to this chain.
5136 for (size_t i = 0; i < mTracks.size(); ++i) {
5137 sp<Track> track = mTracks[i];
5138 if (session == track->sessionId()) {
5139 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5140 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005141 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005142 }
5143 }
5144
5145 // indicate all active tracks in the chain
5146 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5147 sp<Track> track = mActiveTracks[i].promote();
5148 if (track == 0) continue;
5149 if (session == track->sessionId()) {
5150 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005151 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005152 }
Eric Laurent65b65452010-06-01 23:49:17 -07005153 }
5154 }
5155
Eric Laurent53334cd2010-06-23 17:38:20 -07005156 chain->setInBuffer(buffer, ownsBuffer);
5157 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005158 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005159 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005160 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5161 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005162 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005163 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5164 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005165 // Effect chain for other sessions are inserted at beginning of effect
5166 // chains list to be processed before output mix effects. Relative order between other
5167 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005168 size_t size = mEffectChains.size();
5169 size_t i = 0;
5170 for (i = 0; i < size; i++) {
5171 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005172 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005173 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005174
5175 return NO_ERROR;
5176}
5177
5178size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5179{
5180 int session = chain->sessionId();
5181
5182 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5183
5184 for (size_t i = 0; i < mEffectChains.size(); i++) {
5185 if (chain == mEffectChains[i]) {
5186 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005187 // detach all active tracks from the chain
5188 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5189 sp<Track> track = mActiveTracks[i].promote();
5190 if (track == 0) continue;
5191 if (session == track->sessionId()) {
5192 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5193 chain.get(), session);
5194 chain->decActiveTrackCnt();
5195 }
5196 }
5197
Eric Laurent65b65452010-06-01 23:49:17 -07005198 // detach all tracks with same session ID from this chain
5199 for (size_t i = 0; i < mTracks.size(); ++i) {
5200 sp<Track> track = mTracks[i];
5201 if (session == track->sessionId()) {
5202 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005203 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005204 }
5205 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005206 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005207 }
5208 }
5209 return mEffectChains.size();
5210}
5211
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005212void AudioFlinger::PlaybackThread::lockEffectChains_l(
5213 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005214{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005215 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005216 for (size_t i = 0; i < mEffectChains.size(); i++) {
5217 mEffectChains[i]->lock();
5218 }
5219}
5220
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005221void AudioFlinger::PlaybackThread::unlockEffectChains(
5222 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005223{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005224 for (size_t i = 0; i < effectChains.size(); i++) {
5225 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005226 }
5227}
5228
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005229
Eric Laurent65b65452010-06-01 23:49:17 -07005230sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5231{
5232 sp<EffectModule> effect;
5233
5234 sp<EffectChain> chain = getEffectChain_l(sessionId);
5235 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005236 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005237 }
5238 return effect;
5239}
5240
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005241status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5242 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005243{
5244 Mutex::Autolock _l(mLock);
5245 return attachAuxEffect_l(track, EffectId);
5246}
5247
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005248status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5249 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005250{
5251 status_t status = NO_ERROR;
5252
5253 if (EffectId == 0) {
5254 track->setAuxBuffer(0, NULL);
5255 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005256 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5257 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005258 if (effect != 0) {
5259 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5260 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5261 } else {
5262 status = INVALID_OPERATION;
5263 }
5264 } else {
5265 status = BAD_VALUE;
5266 }
5267 }
5268 return status;
5269}
5270
5271void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5272{
5273 for (size_t i = 0; i < mTracks.size(); ++i) {
5274 sp<Track> track = mTracks[i];
5275 if (track->auxEffectId() == effectId) {
5276 attachAuxEffect_l(track, 0);
5277 }
5278 }
5279}
5280
5281// ----------------------------------------------------------------------------
5282// EffectModule implementation
5283// ----------------------------------------------------------------------------
5284
5285#undef LOG_TAG
5286#define LOG_TAG "AudioFlinger::EffectModule"
5287
5288AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5289 const wp<AudioFlinger::EffectChain>& chain,
5290 effect_descriptor_t *desc,
5291 int id,
5292 int sessionId)
5293 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5294 mStatus(NO_INIT), mState(IDLE)
5295{
5296 LOGV("Constructor %p", this);
5297 int lStatus;
5298 sp<ThreadBase> thread = mThread.promote();
5299 if (thread == 0) {
5300 return;
5301 }
5302 PlaybackThread *p = (PlaybackThread *)thread.get();
5303
5304 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5305
5306 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005307 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5308
Eric Laurent65b65452010-06-01 23:49:17 -07005309 if (mStatus != NO_ERROR) {
5310 return;
5311 }
5312 lStatus = init();
5313 if (lStatus < 0) {
5314 mStatus = lStatus;
5315 goto Error;
5316 }
5317
5318 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5319 return;
5320Error:
5321 EffectRelease(mEffectInterface);
5322 mEffectInterface = NULL;
5323 LOGV("Constructor Error %d", mStatus);
5324}
5325
5326AudioFlinger::EffectModule::~EffectModule()
5327{
5328 LOGV("Destructor %p", this);
5329 if (mEffectInterface != NULL) {
5330 // release effect engine
5331 EffectRelease(mEffectInterface);
5332 }
5333}
5334
5335status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5336{
5337 status_t status;
5338
5339 Mutex::Autolock _l(mLock);
5340 // First handle in mHandles has highest priority and controls the effect module
5341 int priority = handle->priority();
5342 size_t size = mHandles.size();
5343 sp<EffectHandle> h;
5344 size_t i;
5345 for (i = 0; i < size; i++) {
5346 h = mHandles[i].promote();
5347 if (h == 0) continue;
5348 if (h->priority() <= priority) break;
5349 }
5350 // if inserted in first place, move effect control from previous owner to this handle
5351 if (i == 0) {
5352 if (h != 0) {
5353 h->setControl(false, true);
5354 }
5355 handle->setControl(true, false);
5356 status = NO_ERROR;
5357 } else {
5358 status = ALREADY_EXISTS;
5359 }
5360 mHandles.insertAt(handle, i);
5361 return status;
5362}
5363
5364size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5365{
5366 Mutex::Autolock _l(mLock);
5367 size_t size = mHandles.size();
5368 size_t i;
5369 for (i = 0; i < size; i++) {
5370 if (mHandles[i] == handle) break;
5371 }
5372 if (i == size) {
5373 return size;
5374 }
5375 mHandles.removeAt(i);
5376 size = mHandles.size();
5377 // if removed from first place, move effect control from this handle to next in line
5378 if (i == 0 && size != 0) {
5379 sp<EffectHandle> h = mHandles[0].promote();
5380 if (h != 0) {
5381 h->setControl(true, true);
5382 }
5383 }
5384
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005385 // Release effect engine here so that it is done immediately. Otherwise it will be released
5386 // by the destructor when the last strong reference on the this object is released which can
5387 // happen after next process is called on this effect.
5388 if (size == 0 && mEffectInterface != NULL) {
5389 // release effect engine
5390 EffectRelease(mEffectInterface);
5391 mEffectInterface = NULL;
5392 }
5393
Eric Laurent65b65452010-06-01 23:49:17 -07005394 return size;
5395}
5396
5397void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5398{
5399 // keep a strong reference on this EffectModule to avoid calling the
5400 // destructor before we exit
5401 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005402 {
5403 sp<ThreadBase> thread = mThread.promote();
5404 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005405 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005406 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005407 }
5408 }
5409}
5410
Eric Laurent7d850f22010-07-09 13:34:17 -07005411void AudioFlinger::EffectModule::updateState() {
5412 Mutex::Autolock _l(mLock);
5413
5414 switch (mState) {
5415 case RESTART:
5416 reset_l();
5417 // FALL THROUGH
5418
5419 case STARTING:
5420 // clear auxiliary effect input buffer for next accumulation
5421 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5422 memset(mConfig.inputCfg.buffer.raw,
5423 0,
5424 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5425 }
5426 start_l();
5427 mState = ACTIVE;
5428 break;
5429 case STOPPING:
5430 stop_l();
5431 mDisableWaitCnt = mMaxDisableWaitCnt;
5432 mState = STOPPED;
5433 break;
5434 case STOPPED:
5435 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5436 // turn off sequence.
5437 if (--mDisableWaitCnt == 0) {
5438 reset_l();
5439 mState = IDLE;
5440 }
5441 break;
5442 default: //IDLE , ACTIVE
5443 break;
5444 }
5445}
5446
Eric Laurent65b65452010-06-01 23:49:17 -07005447void AudioFlinger::EffectModule::process()
5448{
5449 Mutex::Autolock _l(mLock);
5450
Eric Laurent7d850f22010-07-09 13:34:17 -07005451 if (mEffectInterface == NULL ||
5452 mConfig.inputCfg.buffer.raw == NULL ||
5453 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005454 return;
5455 }
5456
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005457 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005458 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5459 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5460 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5461 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005462 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005463 }
5464
Eric Laurent65b65452010-06-01 23:49:17 -07005465 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005466 int ret = (*mEffectInterface)->process(mEffectInterface,
5467 &mConfig.inputCfg.buffer,
5468 &mConfig.outputCfg.buffer);
5469
5470 // force transition to IDLE state when engine is ready
5471 if (mState == STOPPED && ret == -ENODATA) {
5472 mDisableWaitCnt = 1;
5473 }
Eric Laurent65b65452010-06-01 23:49:17 -07005474
5475 // clear auxiliary effect input buffer for next accumulation
5476 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005477 memset(mConfig.inputCfg.buffer.raw, 0,
5478 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07005479 }
5480 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08005481 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5482 // If an insert effect is idle and input buffer is different from output buffer,
5483 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07005484 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07005485 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005486 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5487 int16_t *in = mConfig.inputCfg.buffer.s16;
5488 int16_t *out = mConfig.outputCfg.buffer.s16;
5489 for (size_t i = 0; i < frameCnt; i++) {
5490 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07005491 }
Eric Laurent65b65452010-06-01 23:49:17 -07005492 }
5493 }
5494}
5495
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005496void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005497{
5498 if (mEffectInterface == NULL) {
5499 return;
5500 }
5501 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5502}
5503
5504status_t AudioFlinger::EffectModule::configure()
5505{
5506 uint32_t channels;
5507 if (mEffectInterface == NULL) {
5508 return NO_INIT;
5509 }
5510
5511 sp<ThreadBase> thread = mThread.promote();
5512 if (thread == 0) {
5513 return DEAD_OBJECT;
5514 }
5515
5516 // TODO: handle configuration of effects replacing track process
5517 if (thread->channelCount() == 1) {
5518 channels = CHANNEL_MONO;
5519 } else {
5520 channels = CHANNEL_STEREO;
5521 }
5522
5523 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5524 mConfig.inputCfg.channels = CHANNEL_MONO;
5525 } else {
5526 mConfig.inputCfg.channels = channels;
5527 }
5528 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005529 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5530 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005531 mConfig.inputCfg.samplingRate = thread->sampleRate();
5532 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5533 mConfig.inputCfg.bufferProvider.cookie = NULL;
5534 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5535 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5536 mConfig.outputCfg.bufferProvider.cookie = NULL;
5537 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5538 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5539 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5540 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005541 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005542 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005543 // - in other sessions:
5544 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5545 // other effect: overwrites output buffer: input buffer == output buffer
5546 // Auxiliary effect:
5547 // accumulates in output buffer: input buffer != output buffer
5548 // Therefore: accumulate <=> input buffer != output buffer
5549 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5550 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5551 } else {
5552 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5553 }
5554 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5555 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5556 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5557 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5558
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005559 LOGV("configure() %p thread %p buffer %p framecount %d",
5560 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5561
Eric Laurent65b65452010-06-01 23:49:17 -07005562 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005563 uint32_t size = sizeof(int);
5564 status_t status = (*mEffectInterface)->command(mEffectInterface,
5565 EFFECT_CMD_CONFIGURE,
5566 sizeof(effect_config_t),
5567 &mConfig,
5568 &size,
5569 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005570 if (status == 0) {
5571 status = cmdStatus;
5572 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005573
5574 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5575 (1000 * mConfig.outputCfg.buffer.frameCount);
5576
Eric Laurent65b65452010-06-01 23:49:17 -07005577 return status;
5578}
5579
5580status_t AudioFlinger::EffectModule::init()
5581{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005582 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005583 if (mEffectInterface == NULL) {
5584 return NO_INIT;
5585 }
5586 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005587 uint32_t size = sizeof(status_t);
5588 status_t status = (*mEffectInterface)->command(mEffectInterface,
5589 EFFECT_CMD_INIT,
5590 0,
5591 NULL,
5592 &size,
5593 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005594 if (status == 0) {
5595 status = cmdStatus;
5596 }
5597 return status;
5598}
5599
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005600status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005601{
5602 if (mEffectInterface == NULL) {
5603 return NO_INIT;
5604 }
5605 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005606 uint32_t size = sizeof(status_t);
5607 status_t status = (*mEffectInterface)->command(mEffectInterface,
5608 EFFECT_CMD_ENABLE,
5609 0,
5610 NULL,
5611 &size,
5612 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005613 if (status == 0) {
5614 status = cmdStatus;
5615 }
5616 return status;
5617}
5618
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005619status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005620{
5621 if (mEffectInterface == NULL) {
5622 return NO_INIT;
5623 }
5624 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005625 uint32_t size = sizeof(status_t);
5626 status_t status = (*mEffectInterface)->command(mEffectInterface,
5627 EFFECT_CMD_DISABLE,
5628 0,
5629 NULL,
5630 &size,
5631 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005632 if (status == 0) {
5633 status = cmdStatus;
5634 }
5635 return status;
5636}
5637
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005638status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5639 uint32_t cmdSize,
5640 void *pCmdData,
5641 uint32_t *replySize,
5642 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005643{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005644 Mutex::Autolock _l(mLock);
5645// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005646
5647 if (mEffectInterface == NULL) {
5648 return NO_INIT;
5649 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005650 status_t status = (*mEffectInterface)->command(mEffectInterface,
5651 cmdCode,
5652 cmdSize,
5653 pCmdData,
5654 replySize,
5655 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07005656 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005657 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005658 for (size_t i = 1; i < mHandles.size(); i++) {
5659 sp<EffectHandle> h = mHandles[i].promote();
5660 if (h != 0) {
5661 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5662 }
5663 }
5664 }
5665 return status;
5666}
5667
5668status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5669{
5670 Mutex::Autolock _l(mLock);
5671 LOGV("setEnabled %p enabled %d", this, enabled);
5672
5673 if (enabled != isEnabled()) {
5674 switch (mState) {
5675 // going from disabled to enabled
5676 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005677 mState = STARTING;
5678 break;
5679 case STOPPED:
5680 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005681 break;
5682 case STOPPING:
5683 mState = ACTIVE;
5684 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005685
5686 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005687 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005688 mState = STOPPED;
5689 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005690 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005691 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005692 break;
5693 case ACTIVE:
5694 mState = STOPPING;
5695 break;
5696 }
5697 for (size_t i = 1; i < mHandles.size(); i++) {
5698 sp<EffectHandle> h = mHandles[i].promote();
5699 if (h != 0) {
5700 h->setEnabled(enabled);
5701 }
5702 }
5703 }
5704 return NO_ERROR;
5705}
5706
5707bool AudioFlinger::EffectModule::isEnabled()
5708{
5709 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005710 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005711 case STARTING:
5712 case ACTIVE:
5713 return true;
5714 case IDLE:
5715 case STOPPING:
5716 case STOPPED:
5717 default:
5718 return false;
5719 }
5720}
5721
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005722bool AudioFlinger::EffectModule::isProcessEnabled()
5723{
5724 switch (mState) {
5725 case RESTART:
5726 case ACTIVE:
5727 case STOPPING:
5728 case STOPPED:
5729 return true;
5730 case IDLE:
5731 case STARTING:
5732 default:
5733 return false;
5734 }
5735}
5736
Eric Laurent65b65452010-06-01 23:49:17 -07005737status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5738{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005739 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005740 status_t status = NO_ERROR;
5741
5742 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5743 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005744 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07005745 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5746 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005747 status_t cmdStatus;
5748 uint32_t volume[2];
5749 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005750 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07005751 volume[0] = *left;
5752 volume[1] = *right;
5753 if (controller) {
5754 pVolume = volume;
5755 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005756 status = (*mEffectInterface)->command(mEffectInterface,
5757 EFFECT_CMD_SET_VOLUME,
5758 size,
5759 volume,
5760 &size,
5761 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07005762 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5763 *left = volume[0];
5764 *right = volume[1];
5765 }
5766 }
5767 return status;
5768}
5769
5770status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5771{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005772 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005773 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005774 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5775 // convert device bit field from AudioSystem to EffectApi format.
5776 device = deviceAudioSystemToEffectApi(device);
5777 if (device == 0) {
5778 return BAD_VALUE;
5779 }
Eric Laurent65b65452010-06-01 23:49:17 -07005780 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005781 uint32_t size = sizeof(status_t);
5782 status = (*mEffectInterface)->command(mEffectInterface,
5783 EFFECT_CMD_SET_DEVICE,
5784 sizeof(uint32_t),
5785 &device,
5786 &size,
5787 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005788 if (status == NO_ERROR) {
5789 status = cmdStatus;
5790 }
5791 }
5792 return status;
5793}
5794
Eric Laurent53334cd2010-06-23 17:38:20 -07005795status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5796{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005797 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005798 status_t status = NO_ERROR;
5799 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5800 // convert audio mode from AudioSystem to EffectApi format.
5801 int effectMode = modeAudioSystemToEffectApi(mode);
5802 if (effectMode < 0) {
5803 return BAD_VALUE;
5804 }
5805 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005806 uint32_t size = sizeof(status_t);
5807 status = (*mEffectInterface)->command(mEffectInterface,
5808 EFFECT_CMD_SET_AUDIO_MODE,
5809 sizeof(int),
5810 &effectMode,
5811 &size,
5812 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07005813 if (status == NO_ERROR) {
5814 status = cmdStatus;
5815 }
5816 }
5817 return status;
5818}
5819
5820// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5821const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005822 DEVICE_EARPIECE, // AUDIO_DEVICE_OUT_EARPIECE
5823 DEVICE_SPEAKER, // AUDIO_DEVICE_OUT_SPEAKER
5824 DEVICE_WIRED_HEADSET, // case AUDIO_DEVICE_OUT_WIRED_HEADSET
5825 DEVICE_WIRED_HEADPHONE, // AUDIO_DEVICE_OUT_WIRED_HEADPHONE
5826 DEVICE_BLUETOOTH_SCO, // AUDIO_DEVICE_OUT_BLUETOOTH_SCO
5827 DEVICE_BLUETOOTH_SCO_HEADSET, // AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5828 DEVICE_BLUETOOTH_SCO_CARKIT, // AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5829 DEVICE_BLUETOOTH_A2DP, // AUDIO_DEVICE_OUT_BLUETOOTH_A2DP
5830 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5831 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5832 DEVICE_AUX_DIGITAL // AUDIO_DEVICE_OUT_AUX_DIGITAL
Eric Laurent53334cd2010-06-23 17:38:20 -07005833};
5834
5835uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5836{
5837 uint32_t deviceOut = 0;
5838 while (device) {
5839 const uint32_t i = 31 - __builtin_clz(device);
5840 device &= ~(1 << i);
5841 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
Glenn Kastened0079d2011-04-04 10:50:50 -07005842 LOGE("device conversion error for AudioSystem device 0x%08x", device);
Eric Laurent53334cd2010-06-23 17:38:20 -07005843 return 0;
5844 }
5845 deviceOut |= (uint32_t)sDeviceConvTable[i];
5846 }
5847 return deviceOut;
5848}
5849
5850// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5851const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005852 AUDIO_EFFECT_MODE_NORMAL, // AUDIO_MODE_NORMAL
5853 AUDIO_EFFECT_MODE_RINGTONE, // AUDIO_MODE_RINGTONE
5854 AUDIO_EFFECT_MODE_IN_CALL, // AUDIO_MODE_IN_CALL
5855 AUDIO_EFFECT_MODE_IN_CALL // AUDIO_MODE_IN_COMMUNICATION, same conversion as for AUDIO_MODE_IN_CALL
Eric Laurent53334cd2010-06-23 17:38:20 -07005856};
5857
5858int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5859{
5860 int modeOut = -1;
5861 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5862 modeOut = (int)sModeConvTable[mode];
5863 }
5864 return modeOut;
5865}
Eric Laurent65b65452010-06-01 23:49:17 -07005866
5867status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5868{
5869 const size_t SIZE = 256;
5870 char buffer[SIZE];
5871 String8 result;
5872
5873 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5874 result.append(buffer);
5875
5876 bool locked = tryLock(mLock);
5877 // failed to lock - AudioFlinger is probably deadlocked
5878 if (!locked) {
5879 result.append("\t\tCould not lock Fx mutex:\n");
5880 }
5881
5882 result.append("\t\tSession Status State Engine:\n");
5883 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5884 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5885 result.append(buffer);
5886
5887 result.append("\t\tDescriptor:\n");
5888 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5889 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5890 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5891 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5892 result.append(buffer);
5893 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5894 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5895 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5896 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5897 result.append(buffer);
5898 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5899 mDescriptor.apiVersion,
5900 mDescriptor.flags);
5901 result.append(buffer);
5902 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5903 mDescriptor.name);
5904 result.append(buffer);
5905 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5906 mDescriptor.implementor);
5907 result.append(buffer);
5908
5909 result.append("\t\t- Input configuration:\n");
5910 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5911 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5912 (uint32_t)mConfig.inputCfg.buffer.raw,
5913 mConfig.inputCfg.buffer.frameCount,
5914 mConfig.inputCfg.samplingRate,
5915 mConfig.inputCfg.channels,
5916 mConfig.inputCfg.format);
5917 result.append(buffer);
5918
5919 result.append("\t\t- Output configuration:\n");
5920 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5921 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5922 (uint32_t)mConfig.outputCfg.buffer.raw,
5923 mConfig.outputCfg.buffer.frameCount,
5924 mConfig.outputCfg.samplingRate,
5925 mConfig.outputCfg.channels,
5926 mConfig.outputCfg.format);
5927 result.append(buffer);
5928
5929 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5930 result.append(buffer);
5931 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5932 for (size_t i = 0; i < mHandles.size(); ++i) {
5933 sp<EffectHandle> handle = mHandles[i].promote();
5934 if (handle != 0) {
5935 handle->dump(buffer, SIZE);
5936 result.append(buffer);
5937 }
5938 }
5939
5940 result.append("\n");
5941
5942 write(fd, result.string(), result.length());
5943
5944 if (locked) {
5945 mLock.unlock();
5946 }
5947
5948 return NO_ERROR;
5949}
5950
5951// ----------------------------------------------------------------------------
5952// EffectHandle implementation
5953// ----------------------------------------------------------------------------
5954
5955#undef LOG_TAG
5956#define LOG_TAG "AudioFlinger::EffectHandle"
5957
5958AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5959 const sp<AudioFlinger::Client>& client,
5960 const sp<IEffectClient>& effectClient,
5961 int32_t priority)
5962 : BnEffect(),
5963 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5964{
5965 LOGV("constructor %p", this);
5966
5967 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5968 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5969 if (mCblkMemory != 0) {
5970 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5971
5972 if (mCblk) {
5973 new(mCblk) effect_param_cblk_t();
5974 mBuffer = (uint8_t *)mCblk + bufOffset;
5975 }
5976 } else {
5977 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5978 return;
5979 }
5980}
5981
5982AudioFlinger::EffectHandle::~EffectHandle()
5983{
5984 LOGV("Destructor %p", this);
5985 disconnect();
5986}
5987
5988status_t AudioFlinger::EffectHandle::enable()
5989{
5990 if (!mHasControl) return INVALID_OPERATION;
5991 if (mEffect == 0) return DEAD_OBJECT;
5992
5993 return mEffect->setEnabled(true);
5994}
5995
5996status_t AudioFlinger::EffectHandle::disable()
5997{
5998 if (!mHasControl) return INVALID_OPERATION;
5999 if (mEffect == NULL) return DEAD_OBJECT;
6000
6001 return mEffect->setEnabled(false);
6002}
6003
6004void AudioFlinger::EffectHandle::disconnect()
6005{
6006 if (mEffect == 0) {
6007 return;
6008 }
6009 mEffect->disconnect(this);
6010 // release sp on module => module destructor can be called now
6011 mEffect.clear();
6012 if (mCblk) {
6013 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6014 }
6015 mCblkMemory.clear(); // and free the shared memory
6016 if (mClient != 0) {
6017 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6018 mClient.clear();
6019 }
6020}
6021
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006022status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6023 uint32_t cmdSize,
6024 void *pCmdData,
6025 uint32_t *replySize,
6026 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006027{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006028// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6029// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006030
6031 // only get parameter command is permitted for applications not controlling the effect
6032 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6033 return INVALID_OPERATION;
6034 }
6035 if (mEffect == 0) return DEAD_OBJECT;
6036
6037 // handle commands that are not forwarded transparently to effect engine
6038 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6039 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6040 // no risk to block the whole media server process or mixer threads is we are stuck here
6041 Mutex::Autolock _l(mCblk->lock);
6042 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6043 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6044 mCblk->serverIndex = 0;
6045 mCblk->clientIndex = 0;
6046 return BAD_VALUE;
6047 }
6048 status_t status = NO_ERROR;
6049 while (mCblk->serverIndex < mCblk->clientIndex) {
6050 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006051 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006052 int *p = (int *)(mBuffer + mCblk->serverIndex);
6053 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006054 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6055 LOGW("command(): invalid parameter block size");
6056 break;
6057 }
Eric Laurent65b65452010-06-01 23:49:17 -07006058 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006059 if (param->psize == 0 || param->vsize == 0) {
6060 LOGW("command(): null parameter or value size");
6061 mCblk->serverIndex += size;
6062 continue;
6063 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006064 uint32_t psize = sizeof(effect_param_t) +
6065 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6066 param->vsize;
6067 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6068 psize,
6069 p,
6070 &rsize,
6071 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006072 // stop at first error encountered
6073 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006074 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006075 *(int *)pReplyData = reply;
6076 break;
6077 } else if (reply != NO_ERROR) {
6078 *(int *)pReplyData = reply;
6079 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006080 }
6081 mCblk->serverIndex += size;
6082 }
6083 mCblk->serverIndex = 0;
6084 mCblk->clientIndex = 0;
6085 return status;
6086 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006087 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006088 return enable();
6089 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006090 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006091 return disable();
6092 }
6093
6094 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6095}
6096
6097sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6098 return mCblkMemory;
6099}
6100
6101void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6102{
6103 LOGV("setControl %p control %d", this, hasControl);
6104
6105 mHasControl = hasControl;
6106 if (signal && mEffectClient != 0) {
6107 mEffectClient->controlStatusChanged(hasControl);
6108 }
6109}
6110
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006111void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6112 uint32_t cmdSize,
6113 void *pCmdData,
6114 uint32_t replySize,
6115 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006116{
6117 if (mEffectClient != 0) {
6118 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6119 }
6120}
6121
6122
6123
6124void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6125{
6126 if (mEffectClient != 0) {
6127 mEffectClient->enableStatusChanged(enabled);
6128 }
6129}
6130
6131status_t AudioFlinger::EffectHandle::onTransact(
6132 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6133{
6134 return BnEffect::onTransact(code, data, reply, flags);
6135}
6136
6137
6138void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6139{
6140 bool locked = tryLock(mCblk->lock);
6141
6142 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6143 (mClient == NULL) ? getpid() : mClient->pid(),
6144 mPriority,
6145 mHasControl,
6146 !locked,
6147 mCblk->clientIndex,
6148 mCblk->serverIndex
6149 );
6150
6151 if (locked) {
6152 mCblk->lock.unlock();
6153 }
6154}
6155
6156#undef LOG_TAG
6157#define LOG_TAG "AudioFlinger::EffectChain"
6158
6159AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6160 int sessionId)
Eric Laurent90681d62011-05-09 12:09:06 -07006161 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6162 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6163 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006164{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006165 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006166}
6167
6168AudioFlinger::EffectChain::~EffectChain()
6169{
6170 if (mOwnInBuffer) {
6171 delete mInBuffer;
6172 }
6173
6174}
6175
Eric Laurent76c40f72010-07-15 12:50:15 -07006176// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6177sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006178{
6179 sp<EffectModule> effect;
6180 size_t size = mEffects.size();
6181
6182 for (size_t i = 0; i < size; i++) {
6183 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6184 effect = mEffects[i];
6185 break;
6186 }
6187 }
6188 return effect;
6189}
6190
Eric Laurent76c40f72010-07-15 12:50:15 -07006191// getEffectFromId_l() must be called with PlaybackThread::mLock held
6192sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006193{
6194 sp<EffectModule> effect;
6195 size_t size = mEffects.size();
6196
6197 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006198 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6199 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006200 effect = mEffects[i];
6201 break;
6202 }
6203 }
6204 return effect;
6205}
6206
6207// Must be called with EffectChain::mLock locked
6208void AudioFlinger::EffectChain::process_l()
6209{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006210 sp<ThreadBase> thread = mThread.promote();
6211 if (thread == 0) {
6212 LOGW("process_l(): cannot promote mixer thread");
6213 return;
6214 }
6215 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006216 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6217 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006218 bool tracksOnSession = false;
6219 if (!isGlobalSession) {
Eric Laurent90681d62011-05-09 12:09:06 -07006220 tracksOnSession = (trackCnt() != 0);
6221 }
6222
6223 // if no track is active, input buffer must be cleared here as the mixer process
6224 // will not do it
6225 if (tracksOnSession &&
6226 activeTrackCnt() == 0) {
6227 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6228 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006229 }
6230
Eric Laurent65b65452010-06-01 23:49:17 -07006231 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006232 // do not process effect if no track is present in same audio session
6233 if (isGlobalSession || tracksOnSession) {
6234 for (size_t i = 0; i < size; i++) {
6235 mEffects[i]->process();
6236 }
Eric Laurent65b65452010-06-01 23:49:17 -07006237 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006238 for (size_t i = 0; i < size; i++) {
6239 mEffects[i]->updateState();
6240 }
Eric Laurent65b65452010-06-01 23:49:17 -07006241}
6242
Eric Laurent76c40f72010-07-15 12:50:15 -07006243// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006244status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006245{
6246 effect_descriptor_t desc = effect->desc();
6247 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6248
6249 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006250 effect->setChain(this);
6251 sp<ThreadBase> thread = mThread.promote();
6252 if (thread == 0) {
6253 return NO_INIT;
6254 }
6255 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006256
6257 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6258 // Auxiliary effects are inserted at the beginning of mEffects vector as
6259 // they are processed first and accumulated in chain input buffer
6260 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006261
Eric Laurent65b65452010-06-01 23:49:17 -07006262 // the input buffer for auxiliary effect contains mono samples in
6263 // 32 bit format. This is to avoid saturation in AudoMixer
6264 // accumulation stage. Saturation is done in EffectModule::process() before
6265 // calling the process in effect engine
6266 size_t numSamples = thread->frameCount();
6267 int32_t *buffer = new int32_t[numSamples];
6268 memset(buffer, 0, numSamples * sizeof(int32_t));
6269 effect->setInBuffer((int16_t *)buffer);
6270 // auxiliary effects output samples to chain input buffer for further processing
6271 // by insert effects
6272 effect->setOutBuffer(mInBuffer);
6273 } else {
6274 // Insert effects are inserted at the end of mEffects vector as they are processed
6275 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006276 // Insert effect order as a function of indicated preference:
6277 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6278 // another effect is present
6279 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6280 // last effect claiming first position
6281 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6282 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006283 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006284 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6285 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006286
6287 int size = (int)mEffects.size();
6288 int idx_insert = size;
6289 int idx_insert_first = -1;
6290 int idx_insert_last = -1;
6291
6292 for (int i = 0; i < size; i++) {
6293 effect_descriptor_t d = mEffects[i]->desc();
6294 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6295 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6296 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6297 // check invalid effect chaining combinations
6298 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006299 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006300 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006301 return INVALID_OPERATION;
6302 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006303 // remember position of first insert effect and by default
6304 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006305 if (idx_insert == size) {
6306 idx_insert = i;
6307 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006308 // remember position of last insert effect claiming
6309 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006310 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6311 idx_insert_first = i;
6312 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006313 // remember position of first insert effect claiming
6314 // last position
6315 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6316 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006317 idx_insert_last = i;
6318 }
6319 }
6320 }
6321
Eric Laurent53334cd2010-06-23 17:38:20 -07006322 // modify idx_insert from first position if needed
6323 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6324 if (idx_insert_last != -1) {
6325 idx_insert = idx_insert_last;
6326 } else {
6327 idx_insert = size;
6328 }
6329 } else {
6330 if (idx_insert_first != -1) {
6331 idx_insert = idx_insert_first + 1;
6332 }
Eric Laurent65b65452010-06-01 23:49:17 -07006333 }
6334
6335 // always read samples from chain input buffer
6336 effect->setInBuffer(mInBuffer);
6337
6338 // if last effect in the chain, output samples to chain
6339 // output buffer, otherwise to chain input buffer
6340 if (idx_insert == size) {
6341 if (idx_insert != 0) {
6342 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6343 mEffects[idx_insert-1]->configure();
6344 }
6345 effect->setOutBuffer(mOutBuffer);
6346 } else {
6347 effect->setOutBuffer(mInBuffer);
6348 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006349 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006350
Eric Laurent76c40f72010-07-15 12:50:15 -07006351 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006352 }
6353 effect->configure();
6354 return NO_ERROR;
6355}
6356
Eric Laurent76c40f72010-07-15 12:50:15 -07006357// removeEffect_l() must be called with PlaybackThread::mLock held
6358size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006359{
6360 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006361 int size = (int)mEffects.size();
6362 int i;
6363 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6364
6365 for (i = 0; i < size; i++) {
6366 if (effect == mEffects[i]) {
6367 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6368 delete[] effect->inBuffer();
6369 } else {
6370 if (i == size - 1 && i != 0) {
6371 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6372 mEffects[i - 1]->configure();
6373 }
6374 }
6375 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006376 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006377 break;
6378 }
6379 }
Eric Laurent65b65452010-06-01 23:49:17 -07006380
6381 return mEffects.size();
6382}
6383
Eric Laurent76c40f72010-07-15 12:50:15 -07006384// setDevice_l() must be called with PlaybackThread::mLock held
6385void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006386{
6387 size_t size = mEffects.size();
6388 for (size_t i = 0; i < size; i++) {
6389 mEffects[i]->setDevice(device);
6390 }
6391}
6392
Eric Laurent76c40f72010-07-15 12:50:15 -07006393// setMode_l() must be called with PlaybackThread::mLock held
6394void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006395{
6396 size_t size = mEffects.size();
6397 for (size_t i = 0; i < size; i++) {
6398 mEffects[i]->setMode(mode);
6399 }
6400}
6401
Eric Laurent76c40f72010-07-15 12:50:15 -07006402// setVolume_l() must be called with PlaybackThread::mLock held
6403bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006404{
6405 uint32_t newLeft = *left;
6406 uint32_t newRight = *right;
6407 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006408 int ctrlIdx = -1;
6409 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006410
Eric Laurent76c40f72010-07-15 12:50:15 -07006411 // first update volume controller
6412 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006413 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006414 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6415 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006416 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006417 break;
6418 }
6419 }
6420
6421 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006422 if (hasControl) {
6423 *left = mNewLeftVolume;
6424 *right = mNewRightVolume;
6425 }
6426 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006427 }
6428
6429 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006430 mLeftVolume = newLeft;
6431 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006432
6433 // second get volume update from volume controller
6434 if (ctrlIdx >= 0) {
6435 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006436 mNewLeftVolume = newLeft;
6437 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006438 }
6439 // then indicate volume to all other effects in chain.
6440 // Pass altered volume to effects before volume controller
6441 // and requested volume to effects after controller
6442 uint32_t lVol = newLeft;
6443 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006444
Eric Laurent65b65452010-06-01 23:49:17 -07006445 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006446 if ((int)i == ctrlIdx) continue;
6447 // this also works for ctrlIdx == -1 when there is no volume controller
6448 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006449 lVol = *left;
6450 rVol = *right;
6451 }
6452 mEffects[i]->setVolume(&lVol, &rVol, false);
6453 }
6454 *left = newLeft;
6455 *right = newRight;
6456
6457 return hasControl;
6458}
6459
Eric Laurent65b65452010-06-01 23:49:17 -07006460status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6461{
6462 const size_t SIZE = 256;
6463 char buffer[SIZE];
6464 String8 result;
6465
6466 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6467 result.append(buffer);
6468
6469 bool locked = tryLock(mLock);
6470 // failed to lock - AudioFlinger is probably deadlocked
6471 if (!locked) {
6472 result.append("\tCould not lock mutex:\n");
6473 }
6474
Eric Laurent76c40f72010-07-15 12:50:15 -07006475 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6476 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006477 mEffects.size(),
6478 (uint32_t)mInBuffer,
6479 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006480 mActiveTrackCnt);
6481 result.append(buffer);
6482 write(fd, result.string(), result.size());
6483
6484 for (size_t i = 0; i < mEffects.size(); ++i) {
6485 sp<EffectModule> effect = mEffects[i];
6486 if (effect != 0) {
6487 effect->dump(fd, args);
6488 }
6489 }
6490
6491 if (locked) {
6492 mLock.unlock();
6493 }
6494
6495 return NO_ERROR;
6496}
6497
6498#undef LOG_TAG
6499#define LOG_TAG "AudioFlinger"
6500
Eric Laurenta553c252009-07-17 12:17:14 -07006501// ----------------------------------------------------------------------------
6502
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006503status_t AudioFlinger::onTransact(
6504 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6505{
6506 return BnAudioFlinger::onTransact(code, data, reply, flags);
6507}
6508
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006509}; // namespace android