blob: f8066240d6e2dc4b4e9325e88bf44cd0a032b392 [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 -070064
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065namespace android {
66
The Android Open Source Project10592532009-03-18 17:39:46 -070067static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
68static const char* kHardwareLockedString = "Hardware lock is taken\n";
69
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080070//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070071static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070072static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070073
74// retry counts for buffer fill timeout
75// 50 * ~20msecs = 1 second
76static const int8_t kMaxTrackRetries = 50;
77static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080078// allow less retry attempts on direct output thread.
79// direct outputs can be a scarce resource in audio hardware and should
80// be released as quickly as possible.
81static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070082
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070083static const int kDumpLockRetries = 50;
84static const int kDumpLockSleep = 20000;
85
Dave Sparksd0ac8c02009-09-30 03:09:03 -070086static const nsecs_t kWarningThrottle = seconds(5);
87
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070089// ----------------------------------------------------------------------------
90
91static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070092 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
93 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
94 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
95 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070096}
97
98static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070099 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
100 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
101 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
102 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700103}
104
Gloria Wang9b3f1522011-02-24 14:51:45 -0800105// To collect the amplifier usage
106static void addBatteryData(uint32_t params) {
107 sp<IBinder> binder =
108 defaultServiceManager()->getService(String16("media.player"));
109 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
110 if (service.get() == NULL) {
111 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
112 return;
113 }
114
115 service->addBatteryData(params);
116}
117
Dima Zavin31f188892011-04-18 16:57:27 -0700118static int load_audio_interface(const char *if_name, const hw_module_t **mod,
119 audio_hw_device_t **dev)
120{
121 int rc;
122
123 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
124 if (rc)
125 goto out;
126
127 rc = audio_hw_device_open(*mod, dev);
128 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
129 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
130 if (rc)
131 goto out;
132
133 return 0;
134
135out:
136 *mod = NULL;
137 *dev = NULL;
138 return rc;
139}
140
141static const char *audio_interfaces[] = {
142 "primary",
143 "a2dp",
144 "usb",
145};
146#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
147
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700148// ----------------------------------------------------------------------------
149
150AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 : BnAudioFlinger(),
Dima Zavin31f188892011-04-18 16:57:27 -0700152 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700153{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700154}
155
156void AudioFlinger::onFirstRef()
157{
Dima Zavin31f188892011-04-18 16:57:27 -0700158 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700159
Eric Laurent01635942011-01-18 18:39:02 -0800160 Mutex::Autolock _l(mLock);
161
Dima Zavin31f188892011-04-18 16:57:27 -0700162 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700163 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700164
Dima Zavin31f188892011-04-18 16:57:27 -0700165 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
166 const hw_module_t *mod;
167 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700168
Dima Zavin31f188892011-04-18 16:57:27 -0700169 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
170 if (rc)
171 continue;
172
173 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
174 mod->name, mod->id);
175 mAudioHwDevs.push(dev);
176
177 if (!mPrimaryHardwareDev) {
178 mPrimaryHardwareDev = dev;
179 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700180 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700181 }
182 }
Eric Laurenta553c252009-07-17 12:17:14 -0700183
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700184 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700185
Dima Zavin31f188892011-04-18 16:57:27 -0700186 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
187 LOGE("Primary audio interface not found");
188 return;
189 }
190
191 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
192 audio_hw_device_t *dev = mAudioHwDevs[i];
193
194 mHardwareStatus = AUDIO_HW_INIT;
195 rc = dev->init_check(dev);
196 if (rc == 0) {
197 AutoMutex lock(mHardwareLock);
198
199 mMode = AUDIO_MODE_NORMAL;
200 mHardwareStatus = AUDIO_HW_SET_MODE;
201 dev->set_mode(dev, mMode);
202 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
203 dev->set_master_volume(dev, 1.0f);
204 mHardwareStatus = AUDIO_HW_IDLE;
205 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700206 }
207}
208
Dima Zavin2986f5b2011-04-19 19:04:32 -0700209status_t AudioFlinger::initCheck() const
210{
211 Mutex::Autolock _l(mLock);
212 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
213 return NO_INIT;
214 return NO_ERROR;
215}
216
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700217AudioFlinger::~AudioFlinger()
218{
Dima Zavin31f188892011-04-18 16:57:27 -0700219 int num_devs = mAudioHwDevs.size();
220
Eric Laurent7954c462009-08-28 10:39:03 -0700221 while (!mRecordThreads.isEmpty()) {
222 // closeInput() will remove first entry from mRecordThreads
223 closeInput(mRecordThreads.keyAt(0));
224 }
225 while (!mPlaybackThreads.isEmpty()) {
226 // closeOutput() will remove first entry from mPlaybackThreads
227 closeOutput(mPlaybackThreads.keyAt(0));
228 }
Dima Zavin31f188892011-04-18 16:57:27 -0700229
230 for (int i = 0; i < num_devs; i++) {
231 audio_hw_device_t *dev = mAudioHwDevs[i];
232 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700233 }
Dima Zavin31f188892011-04-18 16:57:27 -0700234 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800235}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800236
Dima Zavin31f188892011-04-18 16:57:27 -0700237audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
238{
239 /* first matching HW device is returned */
240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242 if ((dev->get_supported_devices(dev) & devices) == devices)
243 return dev;
244 }
245 return NULL;
246}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700247
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
249{
250 const size_t SIZE = 256;
251 char buffer[SIZE];
252 String8 result;
253
254 result.append("Clients:\n");
255 for (size_t i = 0; i < mClients.size(); ++i) {
256 wp<Client> wClient = mClients.valueAt(i);
257 if (wClient != 0) {
258 sp<Client> client = wClient.promote();
259 if (client != 0) {
260 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
261 result.append(buffer);
262 }
263 }
264 }
265 write(fd, result.string(), result.size());
266 return NO_ERROR;
267}
268
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700269
270status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
271{
272 const size_t SIZE = 256;
273 char buffer[SIZE];
274 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700275 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700276
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700277 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700278 result.append(buffer);
279 write(fd, result.string(), result.size());
280 return NO_ERROR;
281}
282
283status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
284{
285 const size_t SIZE = 256;
286 char buffer[SIZE];
287 String8 result;
288 snprintf(buffer, SIZE, "Permission Denial: "
289 "can't dump AudioFlinger from pid=%d, uid=%d\n",
290 IPCThreadState::self()->getCallingPid(),
291 IPCThreadState::self()->getCallingUid());
292 result.append(buffer);
293 write(fd, result.string(), result.size());
294 return NO_ERROR;
295}
296
The Android Open Source Project10592532009-03-18 17:39:46 -0700297static bool tryLock(Mutex& mutex)
298{
299 bool locked = false;
300 for (int i = 0; i < kDumpLockRetries; ++i) {
301 if (mutex.tryLock() == NO_ERROR) {
302 locked = true;
303 break;
304 }
305 usleep(kDumpLockSleep);
306 }
307 return locked;
308}
309
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
311{
312 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
313 dumpPermissionDenial(fd, args);
314 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700315 // get state of hardware lock
316 bool hardwareLocked = tryLock(mHardwareLock);
317 if (!hardwareLocked) {
318 String8 result(kHardwareLockedString);
319 write(fd, result.string(), result.size());
320 } else {
321 mHardwareLock.unlock();
322 }
323
324 bool locked = tryLock(mLock);
325
326 // failed to lock - AudioFlinger is probably deadlocked
327 if (!locked) {
328 String8 result(kDeadlockedString);
329 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700330 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700331
332 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
Eric Laurenta553c252009-07-17 12:17:14 -0700335 // dump playback threads
336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700337 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700338 }
339
340 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700341 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700342 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344
Dima Zavin31f188892011-04-18 16:57:27 -0700345 // dump all hardware devs
346 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
347 audio_hw_device_t *dev = mAudioHwDevs[i];
348 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700349 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700350 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700351 }
352 return NO_ERROR;
353}
354
Eric Laurenta553c252009-07-17 12:17:14 -0700355
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700356// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357
358
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359sp<IAudioTrack> AudioFlinger::createTrack(
360 pid_t pid,
361 int streamType,
362 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700363 uint32_t format,
364 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800365 int frameCount,
366 uint32_t flags,
367 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700368 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700369 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800370 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371{
Eric Laurenta553c252009-07-17 12:17:14 -0700372 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800375 wp<Client> wclient;
376 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700377 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700379 if (streamType >= AUDIO_STREAM_CNT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800380 LOGE("invalid stream type");
381 lStatus = BAD_VALUE;
382 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700383 }
384
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800385 {
386 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700387 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700388 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700389 if (thread == NULL) {
390 LOGE("unknown output thread");
391 lStatus = BAD_VALUE;
392 goto Exit;
393 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800394
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800395 wclient = mClients.valueFor(pid);
396
397 if (wclient != NULL) {
398 client = wclient.promote();
399 } else {
400 client = new Client(this, pid);
401 mClients.add(pid, client);
402 }
Eric Laurent65b65452010-06-01 23:49:17 -0700403
Eric Laurent65b65452010-06-01 23:49:17 -0700404 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700405 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700407 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
408 if (mPlaybackThreads.keyAt(i) != output) {
409 // prevent same audio session on different output threads
410 uint32_t sessions = t->hasAudioSession(*sessionId);
411 if (sessions & PlaybackThread::TRACK_SESSION) {
412 lStatus = BAD_VALUE;
413 goto Exit;
414 }
415 // check if an effect with same session ID is waiting for a track to be created
416 if (sessions & PlaybackThread::EFFECT_SESSION) {
417 effectThread = t.get();
418 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700419 }
420 }
Eric Laurent65b65452010-06-01 23:49:17 -0700421 lSessionId = *sessionId;
422 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700423 // if no audio session id is provided, create one here
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800424 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -0700425 if (sessionId != NULL) {
426 *sessionId = lSessionId;
427 }
428 }
429 LOGV("createTrack() lSessionId: %d", lSessionId);
430
Eric Laurenta553c252009-07-17 12:17:14 -0700431 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700432 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700433
434 // move effect chain to this output thread if an effect on same session was waiting
435 // for a track to be created
436 if (lStatus == NO_ERROR && effectThread != NULL) {
437 Mutex::Autolock _dl(thread->mLock);
438 Mutex::Autolock _sl(effectThread->mLock);
439 moveEffectChain_l(lSessionId, effectThread, thread, true);
440 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700441 }
442 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800443 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700444 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700445 // remove local strong reference to Client before deleting the Track so that the Client
446 // destructor is called by the TrackBase destructor with mLock held
447 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700448 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800449 }
450
451Exit:
452 if(status) {
453 *status = lStatus;
454 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700455 return trackHandle;
456}
457
Eric Laurentddb78e72009-07-28 08:44:33 -0700458uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700459{
Eric Laurenta553c252009-07-17 12:17:14 -0700460 Mutex::Autolock _l(mLock);
461 PlaybackThread *thread = checkPlaybackThread_l(output);
462 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700463 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700464 return 0;
465 }
466 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700467}
468
Eric Laurentddb78e72009-07-28 08:44:33 -0700469int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700470{
Eric Laurenta553c252009-07-17 12:17:14 -0700471 Mutex::Autolock _l(mLock);
472 PlaybackThread *thread = checkPlaybackThread_l(output);
473 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700474 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700475 return 0;
476 }
477 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478}
479
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700480uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700481{
Eric Laurenta553c252009-07-17 12:17:14 -0700482 Mutex::Autolock _l(mLock);
483 PlaybackThread *thread = checkPlaybackThread_l(output);
484 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700485 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700486 return 0;
487 }
488 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700489}
490
Eric Laurentddb78e72009-07-28 08:44:33 -0700491size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700492{
Eric Laurenta553c252009-07-17 12:17:14 -0700493 Mutex::Autolock _l(mLock);
494 PlaybackThread *thread = checkPlaybackThread_l(output);
495 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700496 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700497 return 0;
498 }
499 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500}
501
Eric Laurentddb78e72009-07-28 08:44:33 -0700502uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800503{
Eric Laurenta553c252009-07-17 12:17:14 -0700504 Mutex::Autolock _l(mLock);
505 PlaybackThread *thread = checkPlaybackThread_l(output);
506 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700507 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700508 return 0;
509 }
510 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800511}
512
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513status_t AudioFlinger::setMasterVolume(float value)
514{
515 // check calling permissions
516 if (!settingsAllowed()) {
517 return PERMISSION_DENIED;
518 }
519
520 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800521 { // scope for the lock
522 AutoMutex lock(mHardwareLock);
523 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700524 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800525 value = 1.0f;
526 }
527 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700528 }
Eric Laurenta553c252009-07-17 12:17:14 -0700529
Eric Laurent01635942011-01-18 18:39:02 -0800530 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700531 mMasterVolume = value;
532 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700533 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700534
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700535 return NO_ERROR;
536}
537
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700538status_t AudioFlinger::setMode(int mode)
539{
Eric Laurent53334cd2010-06-23 17:38:20 -0700540 status_t ret;
541
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700542 // check calling permissions
543 if (!settingsAllowed()) {
544 return PERMISSION_DENIED;
545 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700546 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700547 LOGW("Illegal value: setMode(%d)", mode);
548 return BAD_VALUE;
549 }
550
Eric Laurent53334cd2010-06-23 17:38:20 -0700551 { // scope for the lock
552 AutoMutex lock(mHardwareLock);
553 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700554 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700555 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800556 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700557
558 if (NO_ERROR == ret) {
559 Mutex::Autolock _l(mLock);
560 mMode = mode;
561 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
562 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700563 }
564
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700565 return ret;
566}
567
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700568status_t AudioFlinger::setMicMute(bool state)
569{
570 // check calling permissions
571 if (!settingsAllowed()) {
572 return PERMISSION_DENIED;
573 }
574
575 AutoMutex lock(mHardwareLock);
576 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700577 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700578 mHardwareStatus = AUDIO_HW_IDLE;
579 return ret;
580}
581
582bool AudioFlinger::getMicMute() const
583{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700584 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700585 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700586 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700587 mHardwareStatus = AUDIO_HW_IDLE;
588 return state;
589}
590
591status_t AudioFlinger::setMasterMute(bool muted)
592{
593 // check calling permissions
594 if (!settingsAllowed()) {
595 return PERMISSION_DENIED;
596 }
Eric Laurenta553c252009-07-17 12:17:14 -0700597
Eric Laurent01635942011-01-18 18:39:02 -0800598 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700599 mMasterMute = muted;
600 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700601 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700602
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700603 return NO_ERROR;
604}
605
606float AudioFlinger::masterVolume() const
607{
Eric Laurenta553c252009-07-17 12:17:14 -0700608 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700609}
610
611bool AudioFlinger::masterMute() const
612{
Eric Laurenta553c252009-07-17 12:17:14 -0700613 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700614}
615
Eric Laurentddb78e72009-07-28 08:44:33 -0700616status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700617{
618 // check calling permissions
619 if (!settingsAllowed()) {
620 return PERMISSION_DENIED;
621 }
622
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700623 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700624 return BAD_VALUE;
625 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800626
Eric Laurenta553c252009-07-17 12:17:14 -0700627 AutoMutex lock(mLock);
628 PlaybackThread *thread = NULL;
629 if (output) {
630 thread = checkPlaybackThread_l(output);
631 if (thread == NULL) {
632 return BAD_VALUE;
633 }
634 }
635
Eric Laurenta553c252009-07-17 12:17:14 -0700636 mStreamTypes[stream].volume = value;
637
638 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700639 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700640 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700641 }
Eric Laurenta553c252009-07-17 12:17:14 -0700642 } else {
643 thread->setStreamVolume(stream, value);
644 }
Eric Laurentef028272009-04-21 07:56:33 -0700645
Eric Laurent415f3e22009-10-21 08:14:22 -0700646 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700647}
648
649status_t AudioFlinger::setStreamMute(int stream, bool muted)
650{
651 // check calling permissions
652 if (!settingsAllowed()) {
653 return PERMISSION_DENIED;
654 }
655
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700656 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
657 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700658 return BAD_VALUE;
659 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700660
Eric Laurent01635942011-01-18 18:39:02 -0800661 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700662 mStreamTypes[stream].mute = muted;
663 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700664 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700666 return NO_ERROR;
667}
668
Eric Laurentddb78e72009-07-28 08:44:33 -0700669float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700670{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700671 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700672 return 0.0f;
673 }
Eric Laurenta553c252009-07-17 12:17:14 -0700674
675 AutoMutex lock(mLock);
676 float volume;
677 if (output) {
678 PlaybackThread *thread = checkPlaybackThread_l(output);
679 if (thread == NULL) {
680 return 0.0f;
681 }
682 volume = thread->streamVolume(stream);
683 } else {
684 volume = mStreamTypes[stream].volume;
685 }
686
Eric Laurentef028272009-04-21 07:56:33 -0700687 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700688}
689
690bool AudioFlinger::streamMute(int stream) const
691{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700692 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700693 return true;
694 }
Eric Laurenta553c252009-07-17 12:17:14 -0700695
696 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700697}
698
Eric Laurentddb78e72009-07-28 08:44:33 -0700699status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700700{
Eric Laurenta553c252009-07-17 12:17:14 -0700701 status_t result;
702
Eric Laurentddb78e72009-07-28 08:44:33 -0700703 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700704 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
705 // check calling permissions
706 if (!settingsAllowed()) {
707 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800708 }
Eric Laurenta553c252009-07-17 12:17:14 -0700709
710 // ioHandle == 0 means the parameters are global to the audio hardware interface
711 if (ioHandle == 0) {
712 AutoMutex lock(mHardwareLock);
713 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700714 status_t final_result = NO_ERROR;
715 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
716 audio_hw_device_t *dev = mAudioHwDevs[i];
717 result = dev->set_parameters(dev, keyValuePairs.string());
718 final_result = result ?: final_result;
719 }
Eric Laurenta553c252009-07-17 12:17:14 -0700720 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -0700721 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700722 }
723
Eric Laurentb7d94602009-09-29 11:12:57 -0700724 // hold a strong ref on thread in case closeOutput() or closeInput() is called
725 // and the thread is exited once the lock is released
726 sp<ThreadBase> thread;
727 {
728 Mutex::Autolock _l(mLock);
729 thread = checkPlaybackThread_l(ioHandle);
730 if (thread == NULL) {
731 thread = checkRecordThread_l(ioHandle);
732 }
Eric Laurenta553c252009-07-17 12:17:14 -0700733 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700734 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800735 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800736 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700737 }
Eric Laurenta553c252009-07-17 12:17:14 -0700738 return BAD_VALUE;
739}
740
Eric Laurentddb78e72009-07-28 08:44:33 -0700741String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700742{
Eric Laurentddb78e72009-07-28 08:44:33 -0700743// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700744// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
745
746 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700747 String8 out_s8;
748
Dima Zavin31f188892011-04-18 16:57:27 -0700749 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
750 audio_hw_device_t *dev = mAudioHwDevs[i];
751 char *s = dev->get_parameters(dev, keys.string());
752 out_s8 += String8(s);
753 free(s);
754 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700755 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700756 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700757
758 Mutex::Autolock _l(mLock);
759
Eric Laurenta553c252009-07-17 12:17:14 -0700760 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
761 if (playbackThread != NULL) {
762 return playbackThread->getParameters(keys);
763 }
764 RecordThread *recordThread = checkRecordThread_l(ioHandle);
765 if (recordThread != NULL) {
766 return recordThread->getParameters(keys);
767 }
768 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700769}
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
772{
Dima Zavin31f188892011-04-18 16:57:27 -0700773 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774}
775
Eric Laurent47d0a922010-02-26 02:47:27 -0800776unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
777{
778 if (ioHandle == 0) {
779 return 0;
780 }
781
782 Mutex::Autolock _l(mLock);
783
784 RecordThread *recordThread = checkRecordThread_l(ioHandle);
785 if (recordThread != NULL) {
786 return recordThread->getInputFramesLost();
787 }
788 return 0;
789}
790
Eric Laurent415f3e22009-10-21 08:14:22 -0700791status_t AudioFlinger::setVoiceVolume(float value)
792{
793 // check calling permissions
794 if (!settingsAllowed()) {
795 return PERMISSION_DENIED;
796 }
797
798 AutoMutex lock(mHardwareLock);
799 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700800 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700801 mHardwareStatus = AUDIO_HW_IDLE;
802
803 return ret;
804}
805
Eric Laurent0986e792010-01-19 17:37:09 -0800806status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
807{
808 status_t status;
809
810 Mutex::Autolock _l(mLock);
811
812 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
813 if (playbackThread != NULL) {
814 return playbackThread->getRenderPosition(halFrames, dspFrames);
815 }
816
817 return BAD_VALUE;
818}
819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
821{
Eric Laurenta553c252009-07-17 12:17:14 -0700822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 Mutex::Autolock _l(mLock);
824
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700825 int pid = IPCThreadState::self()->getCallingPid();
826 if (mNotificationClients.indexOfKey(pid) < 0) {
827 sp<NotificationClient> notificationClient = new NotificationClient(this,
828 client,
829 pid);
830 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700831
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700832 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700833
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700834 sp<IBinder> binder = client->asBinder();
835 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700837 // the config change is always sent from playback or record threads to avoid deadlock
838 // with AudioSystem::gLock
839 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
840 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
841 }
Eric Laurenta553c252009-07-17 12:17:14 -0700842
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700843 for (size_t i = 0; i < mRecordThreads.size(); i++) {
844 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846 }
847}
848
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700849void AudioFlinger::removeNotificationClient(pid_t pid)
850{
851 Mutex::Autolock _l(mLock);
852
853 int index = mNotificationClients.indexOfKey(pid);
854 if (index >= 0) {
855 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
856 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700857 mNotificationClients.removeItem(pid);
858 }
859}
860
Eric Laurent296a0ec2009-09-15 07:10:12 -0700861// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700862void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
863{
Eric Laurent49f02be2009-11-19 09:00:56 -0800864 size_t size = mNotificationClients.size();
865 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700866 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700867 }
868}
869
Eric Laurentb9481d82009-09-17 05:12:56 -0700870// removeClient_l() must be called with AudioFlinger::mLock held
871void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700872{
Eric Laurentb9481d82009-09-17 05:12:56 -0700873 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 -0700874 mClients.removeItem(pid);
875}
876
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700877
Eric Laurenta553c252009-07-17 12:17:14 -0700878// ----------------------------------------------------------------------------
879
Eric Laurent49f02be2009-11-19 09:00:56 -0800880AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700881 : Thread(false),
882 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700883 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700884{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885}
886
Eric Laurenta553c252009-07-17 12:17:14 -0700887AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700889 mParamCond.broadcast();
890 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891}
892
Eric Laurenta553c252009-07-17 12:17:14 -0700893void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700894{
Eric Laurentb7d94602009-09-29 11:12:57 -0700895 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700896 // destroyed in the middle of requestExitAndWait()
897 sp <ThreadBase> strongMe = this;
898
899 LOGV("ThreadBase::exit");
900 {
901 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800902 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700903 requestExit();
904 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700905 }
Eric Laurenta553c252009-07-17 12:17:14 -0700906 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700907}
Eric Laurenta553c252009-07-17 12:17:14 -0700908
909uint32_t AudioFlinger::ThreadBase::sampleRate() const
910{
911 return mSampleRate;
912}
913
914int AudioFlinger::ThreadBase::channelCount() const
915{
Eric Laurentb0a01472010-05-14 05:45:46 -0700916 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700917}
918
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700919uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -0700920{
921 return mFormat;
922}
923
924size_t AudioFlinger::ThreadBase::frameCount() const
925{
926 return mFrameCount;
927}
928
929status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
930{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700931 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700932
Eric Laurent8fce46a2009-08-04 09:45:33 -0700933 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700934 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700935
Eric Laurent8fce46a2009-08-04 09:45:33 -0700936 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700937 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700938 // wait condition with timeout in case the thread loop has exited
939 // before the request could be processed
940 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
941 status = mParamStatus;
942 mWaitWorkCV.signal();
943 } else {
944 status = TIMED_OUT;
945 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700946 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700947}
948
949void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
950{
951 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700952 sendConfigEvent_l(event, param);
953}
954
955// sendConfigEvent_l() must be called with ThreadBase::mLock held
956void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
957{
Eric Laurenta553c252009-07-17 12:17:14 -0700958 ConfigEvent *configEvent = new ConfigEvent();
959 configEvent->mEvent = event;
960 configEvent->mParam = param;
961 mConfigEvents.add(configEvent);
962 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
963 mWaitWorkCV.signal();
964}
965
966void AudioFlinger::ThreadBase::processConfigEvents()
967{
968 mLock.lock();
969 while(!mConfigEvents.isEmpty()) {
970 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
971 ConfigEvent *configEvent = mConfigEvents[0];
972 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700973 // release mLock before locking AudioFlinger mLock: lock order is always
974 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700975 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700976 mAudioFlinger->mLock.lock();
977 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
978 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700979 delete configEvent;
980 mLock.lock();
981 }
982 mLock.unlock();
983}
984
Eric Laurent3fdb1262009-11-07 00:01:32 -0800985status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
986{
987 const size_t SIZE = 256;
988 char buffer[SIZE];
989 String8 result;
990
991 bool locked = tryLock(mLock);
992 if (!locked) {
993 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
994 write(fd, buffer, strlen(buffer));
995 }
996
997 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
998 result.append(buffer);
999 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1000 result.append(buffer);
1001 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1002 result.append(buffer);
1003 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1004 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001005 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1006 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001007 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1008 result.append(buffer);
1009 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1010 result.append(buffer);
1011
1012 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1013 result.append(buffer);
1014 result.append(" Index Command");
1015 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1016 snprintf(buffer, SIZE, "\n %02d ", i);
1017 result.append(buffer);
1018 result.append(mNewParameters[i]);
1019 }
1020
1021 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1022 result.append(buffer);
1023 snprintf(buffer, SIZE, " Index event param\n");
1024 result.append(buffer);
1025 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1026 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1027 result.append(buffer);
1028 }
1029 result.append("\n");
1030
1031 write(fd, result.string(), result.size());
1032
1033 if (locked) {
1034 mLock.unlock();
1035 }
1036 return NO_ERROR;
1037}
1038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039
1040// ----------------------------------------------------------------------------
1041
Dima Zavin31f188892011-04-18 16:57:27 -07001042AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -08001043 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -07001044 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -07001045 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1046 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047{
Eric Laurenta553c252009-07-17 12:17:14 -07001048 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049
Eric Laurenta553c252009-07-17 12:17:14 -07001050 mMasterVolume = mAudioFlinger->masterVolume();
1051 mMasterMute = mAudioFlinger->masterMute();
1052
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001053 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001054 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1055 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057}
1058
Eric Laurenta553c252009-07-17 12:17:14 -07001059AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060{
1061 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062}
1063
Eric Laurenta553c252009-07-17 12:17:14 -07001064status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065{
1066 dumpInternals(fd, args);
1067 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001068 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 return NO_ERROR;
1070}
1071
Eric Laurenta553c252009-07-17 12:17:14 -07001072status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073{
1074 const size_t SIZE = 256;
1075 char buffer[SIZE];
1076 String8 result;
1077
Eric Laurenta553c252009-07-17 12:17:14 -07001078 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001080 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001082 sp<Track> track = mTracks[i];
1083 if (track != 0) {
1084 track->dump(buffer, SIZE);
1085 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
1087 }
1088
Eric Laurenta553c252009-07-17 12:17:14 -07001089 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001091 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001093 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 if (wTrack != 0) {
1095 sp<Track> track = wTrack.promote();
1096 if (track != 0) {
1097 track->dump(buffer, SIZE);
1098 result.append(buffer);
1099 }
1100 }
1101 }
1102 write(fd, result.string(), result.size());
1103 return NO_ERROR;
1104}
1105
Eric Laurent65b65452010-06-01 23:49:17 -07001106status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1107{
1108 const size_t SIZE = 256;
1109 char buffer[SIZE];
1110 String8 result;
1111
1112 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1113 write(fd, buffer, strlen(buffer));
1114
1115 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1116 sp<EffectChain> chain = mEffectChains[i];
1117 if (chain != 0) {
1118 chain->dump(fd, args);
1119 }
1120 }
1121 return NO_ERROR;
1122}
1123
Eric Laurenta553c252009-07-17 12:17:14 -07001124status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125{
1126 const size_t SIZE = 256;
1127 char buffer[SIZE];
1128 String8 result;
1129
Eric Laurent3fdb1262009-11-07 00:01:32 -08001130 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 result.append(buffer);
1132 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1133 result.append(buffer);
1134 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1137 result.append(buffer);
1138 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1139 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001140 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1141 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001142 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1143 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001145
1146 dumpBase(fd, args);
1147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 return NO_ERROR;
1149}
1150
1151// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001152status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153{
1154 if (mSampleRate == 0) {
1155 LOGE("No working audio driver found.");
1156 return NO_INIT;
1157 }
Eric Laurenta553c252009-07-17 12:17:14 -07001158 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 return NO_ERROR;
1160}
1161
Eric Laurenta553c252009-07-17 12:17:14 -07001162void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163{
1164 const size_t SIZE = 256;
1165 char buffer[SIZE];
1166
Eric Laurenta553c252009-07-17 12:17:14 -07001167 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168
1169 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1170}
1171
Eric Laurenta553c252009-07-17 12:17:14 -07001172// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1173sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 const sp<AudioFlinger::Client>& client,
1175 int streamType,
1176 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001177 uint32_t format,
1178 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 int frameCount,
1180 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001181 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 status_t *status)
1183{
1184 sp<Track> track;
1185 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001186
1187 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001188 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1189 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1190 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1191 "for output %p with format %d",
1192 sampleRate, format, channelMask, mOutput, mFormat);
1193 lStatus = BAD_VALUE;
1194 goto Exit;
1195 }
Eric Laurenta553c252009-07-17 12:17:14 -07001196 }
1197 } else {
1198 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1199 if (sampleRate > mSampleRate*2) {
1200 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1201 lStatus = BAD_VALUE;
1202 goto Exit;
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
1205
Eric Laurenta553c252009-07-17 12:17:14 -07001206 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001207 LOGE("Audio driver not initialized.");
1208 lStatus = NO_INIT;
1209 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211
Eric Laurenta553c252009-07-17 12:17:14 -07001212 { // scope for mLock
1213 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001214
1215 // all tracks in same audio session must share the same routing strategy otherwise
1216 // conflicts will happen when tracks are moved from one output to another by audio policy
1217 // manager
1218 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001219 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001220 for (size_t i = 0; i < mTracks.size(); ++i) {
1221 sp<Track> t = mTracks[i];
1222 if (t != 0) {
1223 if (sessionId == t->sessionId() &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001224 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001225 lStatus = BAD_VALUE;
1226 goto Exit;
1227 }
1228 }
1229 }
1230
Eric Laurenta553c252009-07-17 12:17:14 -07001231 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001232 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001233 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001234 lStatus = NO_MEMORY;
1235 goto Exit;
1236 }
1237 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001238
1239 sp<EffectChain> chain = getEffectChain_l(sessionId);
1240 if (chain != 0) {
1241 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1242 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001243 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001244 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001245 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001246 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001247 lStatus = NO_ERROR;
1248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249Exit:
1250 if(status) {
1251 *status = lStatus;
1252 }
1253 return track;
1254}
1255
Eric Laurenta553c252009-07-17 12:17:14 -07001256uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257{
1258 if (mOutput) {
Dima Zavin31f188892011-04-18 16:57:27 -07001259 return mOutput->stream->get_latency(mOutput->stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
1261 else {
1262 return 0;
1263 }
1264}
1265
Eric Laurenta553c252009-07-17 12:17:14 -07001266status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267{
1268 mMasterVolume = value;
1269 return NO_ERROR;
1270}
1271
Eric Laurenta553c252009-07-17 12:17:14 -07001272status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273{
1274 mMasterMute = muted;
1275 return NO_ERROR;
1276}
1277
Eric Laurenta553c252009-07-17 12:17:14 -07001278float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279{
1280 return mMasterVolume;
1281}
1282
Eric Laurenta553c252009-07-17 12:17:14 -07001283bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284{
1285 return mMasterMute;
1286}
1287
Eric Laurenta553c252009-07-17 12:17:14 -07001288status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289{
1290 mStreamTypes[stream].volume = value;
1291 return NO_ERROR;
1292}
1293
Eric Laurenta553c252009-07-17 12:17:14 -07001294status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295{
1296 mStreamTypes[stream].mute = muted;
1297 return NO_ERROR;
1298}
1299
Eric Laurenta553c252009-07-17 12:17:14 -07001300float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301{
1302 return mStreamTypes[stream].volume;
1303}
1304
Eric Laurenta553c252009-07-17 12:17:14 -07001305bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306{
1307 return mStreamTypes[stream].mute;
1308}
1309
Eric Laurenta553c252009-07-17 12:17:14 -07001310// addTrack_l() must be called with ThreadBase::mLock held
1311status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312{
1313 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001314
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001315 // set retry count for buffer fill
1316 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001317 if (mActiveTracks.indexOf(track) < 0) {
1318 // the track is newly added, make sure it fills up all its
1319 // buffers before playing. This is to ensure the client will
1320 // effectively get the latency it requested.
1321 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001322 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001323 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001324 if (track->mainBuffer() != mMixBuffer) {
1325 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1326 if (chain != 0) {
1327 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001328 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001329 }
1330 }
1331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001333 }
Eric Laurenta553c252009-07-17 12:17:14 -07001334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001336 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337
1338 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001339}
1340
Eric Laurenta553c252009-07-17 12:17:14 -07001341// destroyTrack_l() must be called with ThreadBase::mLock held
1342void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001343{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001344 track->mState = TrackBase::TERMINATED;
1345 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001346 removeTrack_l(track);
1347 }
1348}
1349
1350void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1351{
1352 mTracks.remove(track);
1353 deleteTrackName_l(track->name());
1354 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1355 if (chain != 0) {
1356 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001357 }
1358}
1359
Eric Laurenta553c252009-07-17 12:17:14 -07001360String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001361{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001362 String8 out_s8;
1363 char *s;
1364
Dima Zavin31f188892011-04-18 16:57:27 -07001365 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001366 out_s8 = String8(s);
1367 free(s);
1368 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001369}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001370
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001371// destroyTrack_l() must be called with AudioFlinger::mLock held
1372void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001373 AudioSystem::OutputDescriptor desc;
1374 void *param2 = 0;
1375
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001376 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001377
1378 switch (event) {
1379 case AudioSystem::OUTPUT_OPENED:
1380 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001381 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001382 desc.samplingRate = mSampleRate;
1383 desc.format = mFormat;
1384 desc.frameCount = mFrameCount;
1385 desc.latency = latency();
1386 param2 = &desc;
1387 break;
1388
1389 case AudioSystem::STREAM_CONFIG_CHANGED:
1390 param2 = &param;
1391 case AudioSystem::OUTPUT_CLOSED:
1392 default:
1393 break;
1394 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001395 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001396}
1397
1398void AudioFlinger::PlaybackThread::readOutputParameters()
1399{
Dima Zavin31f188892011-04-18 16:57:27 -07001400 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001401 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1402 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001403 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1404 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1405 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001406
Eric Laurenta553c252009-07-17 12:17:14 -07001407 // FIXME - Current mixer implementation only supports stereo output: Always
1408 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001409 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001410 mMixBuffer = new int16_t[mFrameCount * 2];
1411 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001412
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001413 // force reconfiguration of effect chains and engines to take new buffer size and audio
1414 // parameters into account
1415 // Note that mLock is not held when readOutputParameters() is called from the constructor
1416 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1417 // matter.
1418 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1419 Vector< sp<EffectChain> > effectChains = mEffectChains;
1420 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001421 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001422 }
Eric Laurenta553c252009-07-17 12:17:14 -07001423}
1424
Eric Laurent0986e792010-01-19 17:37:09 -08001425status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1426{
1427 if (halFrames == 0 || dspFrames == 0) {
1428 return BAD_VALUE;
1429 }
1430 if (mOutput == 0) {
1431 return INVALID_OPERATION;
1432 }
Dima Zavin31f188892011-04-18 16:57:27 -07001433 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001434
Dima Zavin31f188892011-04-18 16:57:27 -07001435 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001436}
1437
Eric Laurent493941b2010-07-28 01:32:47 -07001438uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001439{
1440 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001441 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001442 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001443 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001444 }
1445
1446 for (size_t i = 0; i < mTracks.size(); ++i) {
1447 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001448 if (sessionId == track->sessionId() &&
1449 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001450 result |= TRACK_SESSION;
1451 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001452 }
1453 }
1454
Eric Laurent493941b2010-07-28 01:32:47 -07001455 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001456}
1457
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001458uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1459{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001460 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001461 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001462 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1463 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001464 }
1465 for (size_t i = 0; i < mTracks.size(); i++) {
1466 sp<Track> track = mTracks[i];
1467 if (sessionId == track->sessionId() &&
1468 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001469 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001470 }
1471 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001472 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001473}
1474
Eric Laurent65b65452010-06-01 23:49:17 -07001475sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1476{
1477 Mutex::Autolock _l(mLock);
1478 return getEffectChain_l(sessionId);
1479}
1480
1481sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1482{
1483 sp<EffectChain> chain;
1484
1485 size_t size = mEffectChains.size();
1486 for (size_t i = 0; i < size; i++) {
1487 if (mEffectChains[i]->sessionId() == sessionId) {
1488 chain = mEffectChains[i];
1489 break;
1490 }
1491 }
1492 return chain;
1493}
1494
Eric Laurent53334cd2010-06-23 17:38:20 -07001495void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1496{
1497 Mutex::Autolock _l(mLock);
1498 size_t size = mEffectChains.size();
1499 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001500 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001501 }
1502}
1503
Eric Laurenta553c252009-07-17 12:17:14 -07001504// ----------------------------------------------------------------------------
1505
Dima Zavin31f188892011-04-18 16:57:27 -07001506AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001507 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001508 mAudioMixer(0)
1509{
1510 mType = PlaybackThread::MIXER;
1511 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1512
1513 // FIXME - Current mixer implementation only supports stereo output
1514 if (mChannelCount == 1) {
1515 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001517}
1518
Eric Laurenta553c252009-07-17 12:17:14 -07001519AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001520{
Eric Laurenta553c252009-07-17 12:17:14 -07001521 delete mAudioMixer;
1522}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523
Eric Laurenta553c252009-07-17 12:17:14 -07001524bool AudioFlinger::MixerThread::threadLoop()
1525{
Eric Laurenta553c252009-07-17 12:17:14 -07001526 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001527 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001528 nsecs_t standbyTime = systemTime();
1529 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001530 // FIXME: Relaxed timing because of a certain device that can't meet latency
1531 // Should be reduced to 2x after the vendor fixes the driver issue
1532 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1533 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001534 bool longStandbyExit = false;
1535 uint32_t activeSleepTime = activeSleepTimeUs();
1536 uint32_t idleSleepTime = idleSleepTimeUs();
1537 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001538 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539
Eric Laurenta553c252009-07-17 12:17:14 -07001540 while (!exitPending())
1541 {
1542 processConfigEvents();
1543
Eric Laurent059b4be2009-11-09 23:32:22 -08001544 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001545 { // scope for mLock
1546
1547 Mutex::Autolock _l(mLock);
1548
1549 if (checkForNewParameters_l()) {
1550 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001551 // FIXME: Relaxed timing because of a certain device that can't meet latency
1552 // Should be reduced to 2x after the vendor fixes the driver issue
1553 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001554 activeSleepTime = activeSleepTimeUs();
1555 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001556 }
1557
1558 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1559
1560 // put audio hardware into standby after short delay
1561 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1562 mSuspended) {
1563 if (!mStandby) {
1564 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001565 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001566 mStandby = true;
1567 mBytesWritten = 0;
1568 }
1569
1570 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1571 // we're about to wait, flush the binder command buffer
1572 IPCThreadState::self()->flushCommands();
1573
1574 if (exitPending()) break;
1575
1576 // wait until we have something to do...
1577 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1578 mWaitWorkCV.wait(mLock);
1579 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1580
1581 if (mMasterMute == false) {
1582 char value[PROPERTY_VALUE_MAX];
1583 property_get("ro.audio.silent", value, "0");
1584 if (atoi(value)) {
1585 LOGD("Silence is golden");
1586 setMasterMute(true);
1587 }
1588 }
1589
1590 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001591 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001592 continue;
1593 }
1594 }
1595
Eric Laurent059b4be2009-11-09 23:32:22 -08001596 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001597
1598 // prevent any changes in effect chain list and in each effect chain
1599 // during mixing and effect process as the audio buffers could be deleted
1600 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001601 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001602 }
1603
Eric Laurent059b4be2009-11-09 23:32:22 -08001604 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001605 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001606 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001607 sleepTime = 0;
1608 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001609 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001610 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001611 // If no tracks are ready, sleep once for the duration of an output
1612 // buffer size, then write 0s to the output
1613 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001614 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1615 sleepTime = activeSleepTime;
1616 } else {
1617 sleepTime = idleSleepTime;
1618 }
1619 } else if (mBytesWritten != 0 ||
1620 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001621 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001622 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001623 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001624 }
Eric Laurent65b65452010-06-01 23:49:17 -07001625 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001626 }
1627
1628 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001629 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001630 }
1631 // sleepTime == 0 means we must write to audio hardware
1632 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001633 for (size_t i = 0; i < effectChains.size(); i ++) {
1634 effectChains[i]->process_l();
1635 }
1636 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001637 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07001638 mLastWriteTime = systemTime();
1639 mInWrite = true;
1640 mBytesWritten += mixBufferSize;
1641
Dima Zavin31f188892011-04-18 16:57:27 -07001642 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001643 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001644 mNumWrites++;
1645 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001646 nsecs_t now = systemTime();
1647 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001648 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001649 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001650 if ((now - lastWarning) > kWarningThrottle) {
1651 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1652 ns2ms(delta), mNumDelayedWrites, this);
1653 lastWarning = now;
1654 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001655 if (mStandby) {
1656 longStandbyExit = true;
1657 }
Eric Laurenta553c252009-07-17 12:17:14 -07001658 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001659 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001660 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001661 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001662 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001663 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001664 }
1665
1666 // finally let go of all our tracks, without the lock held
1667 // since we can't guarantee the destructors won't acquire that
1668 // same lock.
1669 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001670
1671 // Effect chains will be actually deleted here if they were removed from
1672 // mEffectChains list during mixing or effects processing
1673 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001674 }
1675
1676 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07001677 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001678 }
Eric Laurenta553c252009-07-17 12:17:14 -07001679
1680 LOGV("MixerThread %p exiting", this);
1681 return false;
1682}
1683
1684// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001685uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001686{
1687
Eric Laurent059b4be2009-11-09 23:32:22 -08001688 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001689 // find out which tracks need to be processed
1690 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001691 size_t mixedTracks = 0;
1692 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001693
1694 float masterVolume = mMasterVolume;
1695 bool masterMute = mMasterMute;
1696
Eric Laurent8cc93b92010-08-11 05:20:11 -07001697 if (masterMute) {
1698 masterVolume = 0;
1699 }
Eric Laurent65b65452010-06-01 23:49:17 -07001700 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001701 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001702 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001703 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001704 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001705 masterVolume = (float)((v + (1 << 23)) >> 24);
1706 chain.clear();
1707 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001708
Eric Laurenta553c252009-07-17 12:17:14 -07001709 for (size_t i=0 ; i<count ; i++) {
1710 sp<Track> t = activeTracks[i].promote();
1711 if (t == 0) continue;
1712
1713 Track* const track = t.get();
1714 audio_track_cblk_t* cblk = track->cblk();
1715
1716 // The first time a track is added we wait
1717 // for all its buffers to be filled before processing it
1718 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001719 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001720 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001721 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001722 //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 -07001723
Eric Laurent65b65452010-06-01 23:49:17 -07001724 mixedTracks++;
1725
1726 // track->mainBuffer() != mMixBuffer means there is an effect chain
1727 // connected to the track
1728 chain.clear();
1729 if (track->mainBuffer() != mMixBuffer) {
1730 chain = getEffectChain_l(track->sessionId());
1731 // Delegate volume control to effect in track effect chain if needed
1732 if (chain != 0) {
1733 tracksWithEffect++;
1734 } else {
1735 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1736 track->name(), track->sessionId());
1737 }
1738 }
1739
1740
1741 int param = AudioMixer::VOLUME;
1742 if (track->mFillingUpStatus == Track::FS_FILLED) {
1743 // no ramp for the first volume setting
1744 track->mFillingUpStatus = Track::FS_ACTIVE;
1745 if (track->mState == TrackBase::RESUMING) {
1746 track->mState = TrackBase::ACTIVE;
1747 param = AudioMixer::RAMP_VOLUME;
1748 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08001749 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07001750 } else if (cblk->server != 0) {
1751 // If the track is stopped before the first frame was mixed,
1752 // do not apply ramp
1753 param = AudioMixer::RAMP_VOLUME;
1754 }
1755
Eric Laurenta553c252009-07-17 12:17:14 -07001756 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001757 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001758 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001759 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001760 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001761 if (track->isPausing()) {
1762 track->setPaused();
1763 }
1764 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001765
Glenn Kasten871c16c2010-03-05 12:18:01 -08001766 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001767 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001768 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001769 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1770 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001771
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001772 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001773 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001774 // Delegate volume control to effect in track effect chain if needed
1775 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1776 // Do not ramp volume if volume is controlled by effect
1777 param = AudioMixer::VOLUME;
1778 track->mHasVolumeController = true;
1779 } else {
1780 // force no volume ramp when volume controller was just disabled or removed
1781 // from effect chain to avoid volume spike
1782 if (track->mHasVolumeController) {
1783 param = AudioMixer::VOLUME;
1784 }
1785 track->mHasVolumeController = false;
1786 }
1787
1788 // Convert volumes from 8.24 to 4.12 format
1789 int16_t left, right, aux;
1790 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1791 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1792 left = int16_t(v_clamped);
1793 v_clamped = (vr + (1 << 11)) >> 12;
1794 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1795 right = int16_t(v_clamped);
1796
1797 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1798 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07001799
Eric Laurent65b65452010-06-01 23:49:17 -07001800 // XXX: these things DON'T need to be done each time
1801 mAudioMixer->setBufferProvider(track);
1802 mAudioMixer->enable(AudioMixer::MIXING);
1803
1804 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1805 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1806 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001807 mAudioMixer->setParameter(
1808 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001809 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001810 mAudioMixer->setParameter(
1811 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001812 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07001813 mAudioMixer->setParameter(
1814 AudioMixer::RESAMPLE,
1815 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001816 (void *)(cblk->sampleRate));
1817 mAudioMixer->setParameter(
1818 AudioMixer::TRACK,
1819 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1820 mAudioMixer->setParameter(
1821 AudioMixer::TRACK,
1822 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001823
1824 // reset retry count
1825 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001826 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001827 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001828 //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 -07001829 if (track->isStopped()) {
1830 track->reset();
1831 }
1832 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1833 // We have consumed all the buffers of this track.
1834 // Remove it from the list of active tracks.
1835 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001836 } else {
1837 // No buffers for this track. Give it a few chances to
1838 // fill a buffer, then remove it from active list.
1839 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001840 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001841 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07001842 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07001843 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08001844 } else if (mixerStatus != MIXER_TRACKS_READY) {
1845 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001846 }
Eric Laurenta553c252009-07-17 12:17:14 -07001847 }
Eric Laurent65b65452010-06-01 23:49:17 -07001848 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001849 }
1850 }
1851
1852 // remove all the tracks that need to be...
1853 count = tracksToRemove->size();
1854 if (UNLIKELY(count)) {
1855 for (size_t i=0 ; i<count ; i++) {
1856 const sp<Track>& track = tracksToRemove->itemAt(i);
1857 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001858 if (track->mainBuffer() != mMixBuffer) {
1859 chain = getEffectChain_l(track->sessionId());
1860 if (chain != 0) {
1861 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001862 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001863 }
1864 }
Eric Laurenta553c252009-07-17 12:17:14 -07001865 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07001866 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001867 }
1868 }
1869 }
1870
Eric Laurent65b65452010-06-01 23:49:17 -07001871 // mix buffer must be cleared if all tracks are connected to an
1872 // effect chain as in this case the mixer will not write to
1873 // mix buffer and track effects will accumulate into it
1874 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1875 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1876 }
1877
Eric Laurent059b4be2009-11-09 23:32:22 -08001878 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001879}
1880
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001881void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001882{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001883 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1884 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001885 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001886
Eric Laurenta553c252009-07-17 12:17:14 -07001887 size_t size = mTracks.size();
1888 for (size_t i = 0; i < size; i++) {
1889 sp<Track> t = mTracks[i];
1890 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07001891 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001892 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07001893 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001894 }
1895}
Eric Laurenta553c252009-07-17 12:17:14 -07001896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897
Eric Laurenta553c252009-07-17 12:17:14 -07001898// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001899int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900{
1901 return mAudioMixer->getTrackName();
1902}
1903
Eric Laurenta553c252009-07-17 12:17:14 -07001904// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001905void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906{
Eric Laurent0a080292009-12-07 10:53:10 -08001907 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 mAudioMixer->deleteTrackName(name);
1909}
1910
Eric Laurenta553c252009-07-17 12:17:14 -07001911// checkForNewParameters_l() must be called with ThreadBase::mLock held
1912bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913{
Eric Laurenta553c252009-07-17 12:17:14 -07001914 bool reconfig = false;
1915
Eric Laurent8fce46a2009-08-04 09:45:33 -07001916 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001917 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001918 String8 keyValuePair = mNewParameters[0];
1919 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001920 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001921
Eric Laurenta553c252009-07-17 12:17:14 -07001922 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1923 reconfig = true;
1924 }
1925 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001926 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07001927 status = BAD_VALUE;
1928 } else {
1929 reconfig = true;
1930 }
1931 }
1932 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001933 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07001934 status = BAD_VALUE;
1935 } else {
1936 reconfig = true;
1937 }
1938 }
1939 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1940 // do not accept frame count changes if tracks are open as the track buffer
1941 // size depends on frame count and correct behavior would not be garantied
1942 // if frame count is changed after track creation
1943 if (!mTracks.isEmpty()) {
1944 status = INVALID_OPERATION;
1945 } else {
1946 reconfig = true;
1947 }
1948 }
Eric Laurent65b65452010-06-01 23:49:17 -07001949 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001950 // when changing the audio output device, call addBatteryData to notify
1951 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07001952 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001953 uint32_t params = 0;
1954 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001955 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001956 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1957 }
1958
1959 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001960 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08001961 // check if any other device (except speaker) is on
1962 if (value & deviceWithoutSpeaker ) {
1963 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1964 }
1965
1966 if (params != 0) {
1967 addBatteryData(params);
1968 }
1969 }
1970
Eric Laurent65b65452010-06-01 23:49:17 -07001971 // forward device change to effects that have requested to be
1972 // aware of attached audio device.
1973 mDevice = (uint32_t)value;
1974 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001975 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001976 }
1977 }
1978
Eric Laurenta553c252009-07-17 12:17:14 -07001979 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001980 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001981 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001982 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07001983 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001984 mStandby = true;
1985 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07001986 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001987 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001988 }
1989 if (status == NO_ERROR && reconfig) {
1990 delete mAudioMixer;
1991 readOutputParameters();
1992 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1993 for (size_t i = 0; i < mTracks.size() ; i++) {
1994 int name = getTrackName_l();
1995 if (name < 0) break;
1996 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001997 // limit track sample rate to 2 x new output sample rate
1998 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1999 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2000 }
Eric Laurenta553c252009-07-17 12:17:14 -07002001 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002002 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002003 }
2004 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002005
2006 mNewParameters.removeAt(0);
2007
Eric Laurenta553c252009-07-17 12:17:14 -07002008 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002009 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002010 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002011 }
2012 return reconfig;
2013}
2014
2015status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2016{
2017 const size_t SIZE = 256;
2018 char buffer[SIZE];
2019 String8 result;
2020
2021 PlaybackThread::dumpInternals(fd, args);
2022
2023 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2024 result.append(buffer);
2025 write(fd, result.string(), result.size());
2026 return NO_ERROR;
2027}
2028
Eric Laurent059b4be2009-11-09 23:32:22 -08002029uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002030{
Dima Zavin31f188892011-04-18 16:57:27 -07002031 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002032}
2033
2034uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2035{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002036 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002037}
2038
Eric Laurent8448a792010-08-18 18:13:17 -07002039uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2040{
2041 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2042}
2043
Eric Laurenta553c252009-07-17 12:17:14 -07002044// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002045AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002046 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002047{
2048 mType = PlaybackThread::DIRECT;
2049}
2050
2051AudioFlinger::DirectOutputThread::~DirectOutputThread()
2052{
2053}
2054
2055
Eric Laurent65b65452010-06-01 23:49:17 -07002056static inline int16_t clamp16(int32_t sample)
2057{
2058 if ((sample>>15) ^ (sample>>31))
2059 sample = 0x7FFF ^ (sample>>31);
2060 return sample;
2061}
2062
2063static inline
2064int32_t mul(int16_t in, int16_t v)
2065{
2066#if defined(__arm__) && !defined(__thumb__)
2067 int32_t out;
2068 asm( "smulbb %[out], %[in], %[v] \n"
2069 : [out]"=r"(out)
2070 : [in]"%r"(in), [v]"r"(v)
2071 : );
2072 return out;
2073#else
2074 return in * int32_t(v);
2075#endif
2076}
2077
2078void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2079{
2080 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002081 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002082 return;
2083 }
2084
2085 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002086 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002087 size_t count = mFrameCount * mChannelCount;
2088 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2089 int16_t *dst = mMixBuffer + count-1;
2090 while(count--) {
2091 *dst-- = (int16_t)(*src--^0x80) << 8;
2092 }
2093 }
2094
2095 size_t frameCount = mFrameCount;
2096 int16_t *out = mMixBuffer;
2097 if (ramp) {
2098 if (mChannelCount == 1) {
2099 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2100 int32_t vlInc = d / (int32_t)frameCount;
2101 int32_t vl = ((int32_t)mLeftVolShort << 16);
2102 do {
2103 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2104 out++;
2105 vl += vlInc;
2106 } while (--frameCount);
2107
2108 } else {
2109 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2110 int32_t vlInc = d / (int32_t)frameCount;
2111 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2112 int32_t vrInc = d / (int32_t)frameCount;
2113 int32_t vl = ((int32_t)mLeftVolShort << 16);
2114 int32_t vr = ((int32_t)mRightVolShort << 16);
2115 do {
2116 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2117 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2118 out += 2;
2119 vl += vlInc;
2120 vr += vrInc;
2121 } while (--frameCount);
2122 }
2123 } else {
2124 if (mChannelCount == 1) {
2125 do {
2126 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2127 out++;
2128 } while (--frameCount);
2129 } else {
2130 do {
2131 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2132 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2133 out += 2;
2134 } while (--frameCount);
2135 }
2136 }
2137
2138 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002139 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002140 size_t count = mFrameCount * mChannelCount;
2141 int16_t *src = mMixBuffer;
2142 uint8_t *dst = (uint8_t *)mMixBuffer;
2143 while(count--) {
2144 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2145 }
2146 }
2147
2148 mLeftVolShort = leftVol;
2149 mRightVolShort = rightVol;
2150}
2151
Eric Laurenta553c252009-07-17 12:17:14 -07002152bool AudioFlinger::DirectOutputThread::threadLoop()
2153{
Eric Laurent059b4be2009-11-09 23:32:22 -08002154 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002155 sp<Track> trackToRemove;
2156 sp<Track> activeTrack;
2157 nsecs_t standbyTime = systemTime();
2158 int8_t *curBuf;
2159 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002160 uint32_t activeSleepTime = activeSleepTimeUs();
2161 uint32_t idleSleepTime = idleSleepTimeUs();
2162 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002163 // use shorter standby delay as on normal output to release
2164 // hardware resources as soon as possible
2165 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002166
Eric Laurenta553c252009-07-17 12:17:14 -07002167 while (!exitPending())
2168 {
Eric Laurent65b65452010-06-01 23:49:17 -07002169 bool rampVolume;
2170 uint16_t leftVol;
2171 uint16_t rightVol;
2172 Vector< sp<EffectChain> > effectChains;
2173
Eric Laurenta553c252009-07-17 12:17:14 -07002174 processConfigEvents();
2175
Eric Laurent059b4be2009-11-09 23:32:22 -08002176 mixerStatus = MIXER_IDLE;
2177
Eric Laurenta553c252009-07-17 12:17:14 -07002178 { // scope for the mLock
2179
2180 Mutex::Autolock _l(mLock);
2181
2182 if (checkForNewParameters_l()) {
2183 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002184 activeSleepTime = activeSleepTimeUs();
2185 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002186 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002187 }
2188
2189 // put audio hardware into standby after short delay
2190 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2191 mSuspended) {
2192 // wait until we have something to do...
2193 if (!mStandby) {
2194 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002195 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002196 mStandby = true;
2197 mBytesWritten = 0;
2198 }
2199
2200 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2201 // we're about to wait, flush the binder command buffer
2202 IPCThreadState::self()->flushCommands();
2203
2204 if (exitPending()) break;
2205
2206 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2207 mWaitWorkCV.wait(mLock);
2208 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2209
2210 if (mMasterMute == false) {
2211 char value[PROPERTY_VALUE_MAX];
2212 property_get("ro.audio.silent", value, "0");
2213 if (atoi(value)) {
2214 LOGD("Silence is golden");
2215 setMasterMute(true);
2216 }
2217 }
2218
Eric Laurentef9500f2010-03-11 14:47:00 -08002219 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002220 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002221 continue;
2222 }
2223 }
2224
Eric Laurent65b65452010-06-01 23:49:17 -07002225 effectChains = mEffectChains;
2226
Eric Laurenta553c252009-07-17 12:17:14 -07002227 // find out which tracks need to be processed
2228 if (mActiveTracks.size() != 0) {
2229 sp<Track> t = mActiveTracks[0].promote();
2230 if (t == 0) continue;
2231
2232 Track* const track = t.get();
2233 audio_track_cblk_t* cblk = track->cblk();
2234
2235 // The first time a track is added we wait
2236 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002237 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002238 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002239 {
2240 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2241
Eric Laurent65b65452010-06-01 23:49:17 -07002242 if (track->mFillingUpStatus == Track::FS_FILLED) {
2243 track->mFillingUpStatus = Track::FS_ACTIVE;
2244 mLeftVolFloat = mRightVolFloat = 0;
2245 mLeftVolShort = mRightVolShort = 0;
2246 if (track->mState == TrackBase::RESUMING) {
2247 track->mState = TrackBase::ACTIVE;
2248 rampVolume = true;
2249 }
2250 } else if (cblk->server != 0) {
2251 // If the track is stopped before the first frame was mixed,
2252 // do not apply ramp
2253 rampVolume = true;
2254 }
Eric Laurenta553c252009-07-17 12:17:14 -07002255 // compute volume for this track
2256 float left, right;
2257 if (track->isMuted() || mMasterMute || track->isPausing() ||
2258 mStreamTypes[track->type()].mute) {
2259 left = right = 0;
2260 if (track->isPausing()) {
2261 track->setPaused();
2262 }
2263 } else {
2264 float typeVolume = mStreamTypes[track->type()].volume;
2265 float v = mMasterVolume * typeVolume;
2266 float v_clamped = v * cblk->volume[0];
2267 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2268 left = v_clamped/MAX_GAIN;
2269 v_clamped = v * cblk->volume[1];
2270 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2271 right = v_clamped/MAX_GAIN;
2272 }
2273
Eric Laurent65b65452010-06-01 23:49:17 -07002274 if (left != mLeftVolFloat || right != mRightVolFloat) {
2275 mLeftVolFloat = left;
2276 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002277
Eric Laurent65b65452010-06-01 23:49:17 -07002278 // If audio HAL implements volume control,
2279 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002280 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002281 left = 1.0f;
2282 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002283 }
Eric Laurent65b65452010-06-01 23:49:17 -07002284
2285 // Convert volumes from float to 8.24
2286 uint32_t vl = (uint32_t)(left * (1 << 24));
2287 uint32_t vr = (uint32_t)(right * (1 << 24));
2288
2289 // Delegate volume control to effect in track effect chain if needed
2290 // only one effect chain can be present on DirectOutputThread, so if
2291 // there is one, the track is connected to it
2292 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002293 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002294 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002295 rampVolume = false;
2296 }
2297 }
2298
2299 // Convert volumes from 8.24 to 4.12 format
2300 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2301 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2302 leftVol = (uint16_t)v_clamped;
2303 v_clamped = (vr + (1 << 11)) >> 12;
2304 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2305 rightVol = (uint16_t)v_clamped;
2306 } else {
2307 leftVol = mLeftVolShort;
2308 rightVol = mRightVolShort;
2309 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002310 }
2311
2312 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002313 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002314 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002315 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002316 } else {
2317 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2318 if (track->isStopped()) {
2319 track->reset();
2320 }
2321 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2322 // We have consumed all the buffers of this track.
2323 // Remove it from the list of active tracks.
2324 trackToRemove = track;
2325 } else {
2326 // No buffers for this track. Give it a few chances to
2327 // fill a buffer, then remove it from active list.
2328 if (--(track->mRetryCount) <= 0) {
2329 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2330 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002331 } else {
2332 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002333 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002334 }
Eric Laurenta553c252009-07-17 12:17:14 -07002335 }
2336 }
2337
2338 // remove all the tracks that need to be...
2339 if (UNLIKELY(trackToRemove != 0)) {
2340 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002341 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002342 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2343 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002344 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002345 }
Eric Laurenta553c252009-07-17 12:17:14 -07002346 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002347 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002348 }
2349 }
Eric Laurent65b65452010-06-01 23:49:17 -07002350
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002351 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002352 }
2353
Eric Laurent059b4be2009-11-09 23:32:22 -08002354 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002355 AudioBufferProvider::Buffer buffer;
2356 size_t frameCount = mFrameCount;
2357 curBuf = (int8_t *)mMixBuffer;
2358 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002359 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002360 buffer.frameCount = frameCount;
2361 activeTrack->getNextBuffer(&buffer);
2362 if (UNLIKELY(buffer.raw == 0)) {
2363 memset(curBuf, 0, frameCount * mFrameSize);
2364 break;
2365 }
2366 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2367 frameCount -= buffer.frameCount;
2368 curBuf += buffer.frameCount * mFrameSize;
2369 activeTrack->releaseBuffer(&buffer);
2370 }
2371 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002372 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002373 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002374 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002375 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2376 sleepTime = activeSleepTime;
2377 } else {
2378 sleepTime = idleSleepTime;
2379 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002380 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002381 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002382 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002383 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002384 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002385
Eric Laurentf69a3f82009-09-22 00:35:48 -07002386 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002387 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002388 }
2389 // sleepTime == 0 means we must write to audio hardware
2390 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002391 if (mixerStatus == MIXER_TRACKS_READY) {
2392 applyVolume(leftVol, rightVol, rampVolume);
2393 }
2394 for (size_t i = 0; i < effectChains.size(); i ++) {
2395 effectChains[i]->process_l();
2396 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002397 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002398
Eric Laurentf69a3f82009-09-22 00:35:48 -07002399 mLastWriteTime = systemTime();
2400 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002401 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002402 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002403 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002404 mNumWrites++;
2405 mInWrite = false;
2406 mStandby = false;
2407 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002408 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002409 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002410 }
2411
2412 // finally let go of removed track, without the lock held
2413 // since we can't guarantee the destructors won't acquire that
2414 // same lock.
2415 trackToRemove.clear();
2416 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002417
2418 // Effect chains will be actually deleted here if they were removed from
2419 // mEffectChains list during mixing or effects processing
2420 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002421 }
2422
2423 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002424 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002425 }
Eric Laurenta553c252009-07-17 12:17:14 -07002426
2427 LOGV("DirectOutputThread %p exiting", this);
2428 return false;
2429}
2430
2431// getTrackName_l() must be called with ThreadBase::mLock held
2432int AudioFlinger::DirectOutputThread::getTrackName_l()
2433{
2434 return 0;
2435}
2436
2437// deleteTrackName_l() must be called with ThreadBase::mLock held
2438void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2439{
2440}
2441
2442// checkForNewParameters_l() must be called with ThreadBase::mLock held
2443bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2444{
2445 bool reconfig = false;
2446
Eric Laurent8fce46a2009-08-04 09:45:33 -07002447 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002448 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002449 String8 keyValuePair = mNewParameters[0];
2450 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002451 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002452
Eric Laurenta553c252009-07-17 12:17:14 -07002453 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2454 // do not accept frame count changes if tracks are open as the track buffer
2455 // size depends on frame count and correct behavior would not be garantied
2456 // if frame count is changed after track creation
2457 if (!mTracks.isEmpty()) {
2458 status = INVALID_OPERATION;
2459 } else {
2460 reconfig = true;
2461 }
2462 }
2463 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002464 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002465 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002466 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002467 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002468 mStandby = true;
2469 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002470 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002471 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002472 }
2473 if (status == NO_ERROR && reconfig) {
2474 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002475 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002476 }
2477 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002478
2479 mNewParameters.removeAt(0);
2480
Eric Laurenta553c252009-07-17 12:17:14 -07002481 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002482 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002483 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002484 }
2485 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002486}
2487
Eric Laurent059b4be2009-11-09 23:32:22 -08002488uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002489{
2490 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002491 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin31f188892011-04-18 16:57:27 -07002492 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002493 } else {
2494 time = 10000;
2495 }
2496 return time;
2497}
2498
2499uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2500{
2501 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002502 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002503 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002504 } else {
2505 time = 10000;
2506 }
2507 return time;
2508}
2509
Eric Laurent8448a792010-08-18 18:13:17 -07002510uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2511{
2512 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002513 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002514 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2515 } else {
2516 time = 10000;
2517 }
2518 return time;
2519}
2520
2521
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002522// ----------------------------------------------------------------------------
2523
Eric Laurent49f02be2009-11-19 09:00:56 -08002524AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002525 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002526{
2527 mType = PlaybackThread::DUPLICATING;
2528 addOutputTrack(mainThread);
2529}
2530
2531AudioFlinger::DuplicatingThread::~DuplicatingThread()
2532{
Eric Laurent0a080292009-12-07 10:53:10 -08002533 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2534 mOutputTracks[i]->destroy();
2535 }
Eric Laurenta553c252009-07-17 12:17:14 -07002536 mOutputTracks.clear();
2537}
2538
2539bool AudioFlinger::DuplicatingThread::threadLoop()
2540{
Eric Laurenta553c252009-07-17 12:17:14 -07002541 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002542 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002543 nsecs_t standbyTime = systemTime();
2544 size_t mixBufferSize = mFrameCount*mFrameSize;
2545 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002546 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002547 uint32_t activeSleepTime = activeSleepTimeUs();
2548 uint32_t idleSleepTime = idleSleepTimeUs();
2549 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002550 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002551
2552 while (!exitPending())
2553 {
2554 processConfigEvents();
2555
Eric Laurent059b4be2009-11-09 23:32:22 -08002556 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002557 { // scope for the mLock
2558
2559 Mutex::Autolock _l(mLock);
2560
2561 if (checkForNewParameters_l()) {
2562 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002563 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002564 activeSleepTime = activeSleepTimeUs();
2565 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002566 }
2567
2568 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2569
2570 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2571 outputTracks.add(mOutputTracks[i]);
2572 }
2573
2574 // put audio hardware into standby after short delay
2575 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2576 mSuspended) {
2577 if (!mStandby) {
2578 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002579 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002580 }
2581 mStandby = true;
2582 mBytesWritten = 0;
2583 }
2584
2585 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2586 // we're about to wait, flush the binder command buffer
2587 IPCThreadState::self()->flushCommands();
2588 outputTracks.clear();
2589
2590 if (exitPending()) break;
2591
2592 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2593 mWaitWorkCV.wait(mLock);
2594 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2595 if (mMasterMute == false) {
2596 char value[PROPERTY_VALUE_MAX];
2597 property_get("ro.audio.silent", value, "0");
2598 if (atoi(value)) {
2599 LOGD("Silence is golden");
2600 setMasterMute(true);
2601 }
2602 }
2603
2604 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002605 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002606 continue;
2607 }
2608 }
2609
Eric Laurent059b4be2009-11-09 23:32:22 -08002610 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002611
2612 // prevent any changes in effect chain list and in each effect chain
2613 // during mixing and effect process as the audio buffers could be deleted
2614 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002615 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002616 }
Eric Laurenta553c252009-07-17 12:17:14 -07002617
Eric Laurent059b4be2009-11-09 23:32:22 -08002618 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002619 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002620 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002621 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002622 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002623 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002624 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002625 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002626 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002627 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002628 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002629 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2630 sleepTime = activeSleepTime;
2631 } else {
2632 sleepTime = idleSleepTime;
2633 }
Eric Laurent62443f52009-10-05 20:29:18 -07002634 } else if (mBytesWritten != 0) {
2635 // flush remaining overflow buffers in output tracks
2636 for (size_t i = 0; i < outputTracks.size(); i++) {
2637 if (outputTracks[i]->isActive()) {
2638 sleepTime = 0;
2639 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002640 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002641 break;
2642 }
2643 }
Eric Laurenta553c252009-07-17 12:17:14 -07002644 }
2645 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002646
2647 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002648 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002649 }
2650 // sleepTime == 0 means we must write to audio hardware
2651 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002652 for (size_t i = 0; i < effectChains.size(); i ++) {
2653 effectChains[i]->process_l();
2654 }
2655 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002656 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002657
Eric Laurent62443f52009-10-05 20:29:18 -07002658 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002659 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002660 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002661 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002662 mStandby = false;
2663 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002664 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002665 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002666 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002667 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002668 }
2669
2670 // finally let go of all our tracks, without the lock held
2671 // since we can't guarantee the destructors won't acquire that
2672 // same lock.
2673 tracksToRemove.clear();
2674 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002675
2676 // Effect chains will be actually deleted here if they were removed from
2677 // mEffectChains list during mixing or effects processing
2678 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002679 }
2680
Eric Laurenta553c252009-07-17 12:17:14 -07002681 return false;
2682}
2683
2684void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2685{
2686 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2687 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002688 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002689 mSampleRate,
2690 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002691 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07002692 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002693 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002694 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07002695 mOutputTracks.add(outputTrack);
2696 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002697 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002698 }
Eric Laurenta553c252009-07-17 12:17:14 -07002699}
2700
2701void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2702{
2703 Mutex::Autolock _l(mLock);
2704 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2705 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002706 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002707 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002708 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002709 return;
2710 }
2711 }
2712 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2713}
2714
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002715void AudioFlinger::DuplicatingThread::updateWaitTime()
2716{
2717 mWaitTimeMs = UINT_MAX;
2718 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2719 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2720 if (strong != NULL) {
2721 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2722 if (waitTimeMs < mWaitTimeMs) {
2723 mWaitTimeMs = waitTimeMs;
2724 }
2725 }
2726 }
2727}
2728
2729
2730bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2731{
2732 for (size_t i = 0; i < outputTracks.size(); i++) {
2733 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2734 if (thread == 0) {
2735 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2736 return false;
2737 }
2738 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2739 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2740 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2741 return false;
2742 }
2743 }
2744 return true;
2745}
2746
2747uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2748{
2749 return (mWaitTimeMs * 1000) / 2;
2750}
2751
Eric Laurenta553c252009-07-17 12:17:14 -07002752// ----------------------------------------------------------------------------
2753
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002754// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002755AudioFlinger::ThreadBase::TrackBase::TrackBase(
2756 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002757 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002758 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002759 uint32_t format,
2760 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002761 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002763 const sp<IMemory>& sharedBuffer,
2764 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002765 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002766 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002767 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002768 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002769 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002770 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002771 mClientTid(-1),
2772 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002773 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2774 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002775{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002776 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2777
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002778 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002779 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002780 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002781 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2782 if (sharedBuffer == 0) {
2783 size += bufferSize;
2784 }
2785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 if (client != NULL) {
2787 mCblkMemory = client->heap()->allocate(size);
2788 if (mCblkMemory != 0) {
2789 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2790 if (mCblk) { // construct the shared structure in-place.
2791 new(mCblk) audio_track_cblk_t();
2792 // clear all buffers
2793 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002794 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002795 mChannelCount = channelCount;
2796 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 if (sharedBuffer == 0) {
2798 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2799 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2800 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002801 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002802 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 } else {
2804 mBuffer = sharedBuffer->pointer();
2805 }
2806 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 } else {
2809 LOGE("not enough memory for AudioTrack size=%u", size);
2810 client->heap()->dump("AudioTrack");
2811 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 } else {
2814 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2815 if (mCblk) { // construct the shared structure in-place.
2816 new(mCblk) audio_track_cblk_t();
2817 // clear all buffers
2818 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002819 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002820 mChannelCount = channelCount;
2821 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2823 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2824 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002825 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002826 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2828 }
2829 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002830}
2831
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002832AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002833{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002835 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2836 if (mClient == NULL) {
2837 delete mCblk;
2838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002840 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002841 if (mClient != NULL) {
2842 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2843 mClient.clear();
2844 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002845}
2846
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002847void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002848{
2849 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002850 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002851 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002852 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002853}
2854
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002855bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002856 bool result;
2857 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002858
2859 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002860 if (!result) {
2861 LOGV("stepServer failed acquiring cblk mutex");
2862 mFlags |= STEPSERVER_FAILED;
2863 }
2864 return result;
2865}
2866
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002867void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002868 audio_track_cblk_t* cblk = this->cblk();
2869
2870 cblk->user = 0;
2871 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002872 cblk->userBase = 0;
2873 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002875 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002876}
2877
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002878sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002879{
2880 return mCblkMemory;
2881}
2882
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002883int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002884 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002885}
2886
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002887int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002888 return (const int)mChannelCount;
2889}
2890
2891uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
2892 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002893}
2894
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002895void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002896 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002897 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2898 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002899
2900 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002901 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2902 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002903 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002904 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002905 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002906 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002907 return 0;
2908 }
2909
2910 return bufferStart;
2911}
2912
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002913// ----------------------------------------------------------------------------
2914
Eric Laurenta553c252009-07-17 12:17:14 -07002915// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2916AudioFlinger::PlaybackThread::Track::Track(
2917 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002918 const sp<Client>& client,
2919 int streamType,
2920 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002921 uint32_t format,
2922 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002923 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002924 const sp<IMemory>& sharedBuffer,
2925 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002926 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07002927 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2928 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002929{
Eric Laurent8a77a992009-09-09 05:16:08 -07002930 if (mCblk != NULL) {
2931 sp<ThreadBase> baseThread = thread.promote();
2932 if (baseThread != 0) {
2933 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2934 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002935 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002936 }
2937 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2938 if (mName < 0) {
2939 LOGE("no more track names available");
2940 }
2941 mVolume[0] = 1.0f;
2942 mVolume[1] = 1.0f;
2943 mStreamType = streamType;
2944 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2945 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002946 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002947 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002948}
2949
Eric Laurenta553c252009-07-17 12:17:14 -07002950AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002951{
Eric Laurenta553c252009-07-17 12:17:14 -07002952 LOGV("PlaybackThread::Track destructor");
2953 sp<ThreadBase> thread = mThread.promote();
2954 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002955 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002956 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002957 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002958}
2959
Eric Laurenta553c252009-07-17 12:17:14 -07002960void AudioFlinger::PlaybackThread::Track::destroy()
2961{
2962 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2963 // by removing it from mTracks vector, so there is a risk that this Tracks's
2964 // desctructor is called. As the destructor needs to lock mLock,
2965 // we must acquire a strong reference on this Track before locking mLock
2966 // here so that the destructor is called only when exiting this function.
2967 // On the other hand, as long as Track::destroy() is only called by
2968 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2969 // this Track with its member mTrack.
2970 sp<Track> keep(this);
2971 { // scope for mLock
2972 sp<ThreadBase> thread = mThread.promote();
2973 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002974 if (!isOutputTrack()) {
2975 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002976 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002977 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002978 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08002979
2980 // to track the speaker usage
2981 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08002982 }
2983 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002984 }
Eric Laurenta553c252009-07-17 12:17:14 -07002985 Mutex::Autolock _l(thread->mLock);
2986 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2987 playbackThread->destroyTrack_l(this);
2988 }
2989 }
2990}
2991
2992void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002993{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002994 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002995 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002997 mStreamType,
2998 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002999 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003000 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003001 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003002 mState,
3003 mMute,
3004 mFillingUpStatus,
3005 mCblk->sampleRate,
3006 mCblk->volume[0],
3007 mCblk->volume[1],
3008 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003009 mCblk->user,
3010 (int)mMainBuffer,
3011 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003012}
3013
Eric Laurenta553c252009-07-17 12:17:14 -07003014status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003015{
3016 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003017 uint32_t framesReady;
3018 uint32_t framesReq = buffer->frameCount;
3019
3020 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003021 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3022 if (!step()) goto getNextBuffer_exit;
3023 LOGV("stepServer recovered");
3024 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3025 }
3026
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003027 framesReady = cblk->framesReady();
3028
3029 if (LIKELY(framesReady)) {
3030 uint32_t s = cblk->server;
3031 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3032
3033 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3034 if (framesReq > framesReady) {
3035 framesReq = framesReady;
3036 }
3037 if (s + framesReq > bufferEnd) {
3038 framesReq = bufferEnd - s;
3039 }
3040
3041 buffer->raw = getBuffer(s, framesReq);
3042 if (buffer->raw == 0) goto getNextBuffer_exit;
3043
3044 buffer->frameCount = framesReq;
3045 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003046 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003047
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003048getNextBuffer_exit:
3049 buffer->raw = 0;
3050 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003051 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 -07003052 return NOT_ENOUGH_DATA;
3053}
3054
Eric Laurenta553c252009-07-17 12:17:14 -07003055bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003056 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003057
3058 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003059 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003060 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003061 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003062 return true;
3063 }
3064 return false;
3065}
3066
Eric Laurenta553c252009-07-17 12:17:14 -07003067status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003068{
Eric Laurent49f02be2009-11-19 09:00:56 -08003069 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003070 LOGV("start(%d), calling thread %d session %d",
3071 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003072 sp<ThreadBase> thread = mThread.promote();
3073 if (thread != 0) {
3074 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003075 int state = mState;
3076 // here the track could be either new, or restarted
3077 // in both cases "unstop" the track
3078 if (mState == PAUSED) {
3079 mState = TrackBase::RESUMING;
3080 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3081 } else {
3082 mState = TrackBase::ACTIVE;
3083 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3084 }
3085
3086 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3087 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003088 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003089 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003090 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003091 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003092
3093 // to track the speaker usage
3094 if (status == NO_ERROR) {
3095 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3096 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003097 }
3098 if (status == NO_ERROR) {
3099 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3100 playbackThread->addTrack_l(this);
3101 } else {
3102 mState = state;
3103 }
3104 } else {
3105 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003106 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003107 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003108}
3109
Eric Laurenta553c252009-07-17 12:17:14 -07003110void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003111{
Eric Laurenta553c252009-07-17 12:17:14 -07003112 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3113 sp<ThreadBase> thread = mThread.promote();
3114 if (thread != 0) {
3115 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003116 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003117 if (mState > STOPPED) {
3118 mState = STOPPED;
3119 // If the track is not active (PAUSED and buffers full), flush buffers
3120 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3121 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3122 reset();
3123 }
Eric Laurent62443f52009-10-05 20:29:18 -07003124 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003125 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003126 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3127 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003128 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003129 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003130 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003131 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003132
3133 // to track the speaker usage
3134 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003135 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003136 }
3137}
3138
Eric Laurenta553c252009-07-17 12:17:14 -07003139void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003140{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003142 sp<ThreadBase> thread = mThread.promote();
3143 if (thread != 0) {
3144 Mutex::Autolock _l(thread->mLock);
3145 if (mState == ACTIVE || mState == RESUMING) {
3146 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003147 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003148 if (!isOutputTrack()) {
3149 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003150 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003151 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003152 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003153 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003154
3155 // to track the speaker usage
3156 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003157 }
Eric Laurenta553c252009-07-17 12:17:14 -07003158 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003159 }
3160}
3161
Eric Laurenta553c252009-07-17 12:17:14 -07003162void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003163{
3164 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003165 sp<ThreadBase> thread = mThread.promote();
3166 if (thread != 0) {
3167 Mutex::Autolock _l(thread->mLock);
3168 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3169 return;
3170 }
3171 // No point remaining in PAUSED state after a flush => go to
3172 // STOPPED state
3173 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003174
Eric Laurentae29b762011-03-28 18:37:07 -07003175 // do not reset the track if it is still in the process of being stopped or paused.
3176 // this will be done by prepareTracks_l() when the track is stopped.
3177 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3178 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3179 reset();
3180 }
Eric Laurenta553c252009-07-17 12:17:14 -07003181 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003182}
3183
Eric Laurenta553c252009-07-17 12:17:14 -07003184void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003185{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003186 // Do not reset twice to avoid discarding data written just after a flush and before
3187 // the audioflinger thread detects the track is stopped.
3188 if (!mResetDone) {
3189 TrackBase::reset();
3190 // Force underrun condition to avoid false underrun callback until first data is
3191 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003192 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3193 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003194 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003195 mResetDone = true;
3196 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003197}
3198
Eric Laurenta553c252009-07-17 12:17:14 -07003199void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003200{
3201 mMute = muted;
3202}
3203
Eric Laurenta553c252009-07-17 12:17:14 -07003204void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003205{
3206 mVolume[0] = left;
3207 mVolume[1] = right;
3208}
3209
Eric Laurent65b65452010-06-01 23:49:17 -07003210status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3211{
3212 status_t status = DEAD_OBJECT;
3213 sp<ThreadBase> thread = mThread.promote();
3214 if (thread != 0) {
3215 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3216 status = playbackThread->attachAuxEffect(this, EffectId);
3217 }
3218 return status;
3219}
3220
3221void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3222{
3223 mAuxEffectId = EffectId;
3224 mAuxBuffer = buffer;
3225}
3226
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003227// ----------------------------------------------------------------------------
3228
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003229// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003230AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3231 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003234 uint32_t format,
3235 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003237 uint32_t flags,
3238 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003239 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003240 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003241 mOverflow(false)
3242{
Eric Laurent8a77a992009-09-09 05:16:08 -07003243 if (mCblk != NULL) {
3244 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003245 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003246 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003247 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003248 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003249 } else {
3250 mCblk->frameSize = sizeof(int8_t);
3251 }
3252 }
Eric Laurenta553c252009-07-17 12:17:14 -07003253}
3254
3255AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256{
Eric Laurent49f02be2009-11-19 09:00:56 -08003257 sp<ThreadBase> thread = mThread.promote();
3258 if (thread != 0) {
3259 AudioSystem::releaseInput(thread->id());
3260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261}
3262
Eric Laurenta553c252009-07-17 12:17:14 -07003263status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264{
3265 audio_track_cblk_t* cblk = this->cblk();
3266 uint32_t framesAvail;
3267 uint32_t framesReq = buffer->frameCount;
3268
3269 // Check if last stepServer failed, try to step now
3270 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3271 if (!step()) goto getNextBuffer_exit;
3272 LOGV("stepServer recovered");
3273 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3274 }
3275
3276 framesAvail = cblk->framesAvailable_l();
3277
3278 if (LIKELY(framesAvail)) {
3279 uint32_t s = cblk->server;
3280 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3281
3282 if (framesReq > framesAvail) {
3283 framesReq = framesAvail;
3284 }
3285 if (s + framesReq > bufferEnd) {
3286 framesReq = bufferEnd - s;
3287 }
3288
3289 buffer->raw = getBuffer(s, framesReq);
3290 if (buffer->raw == 0) goto getNextBuffer_exit;
3291
3292 buffer->frameCount = framesReq;
3293 return NO_ERROR;
3294 }
3295
3296getNextBuffer_exit:
3297 buffer->raw = 0;
3298 buffer->frameCount = 0;
3299 return NOT_ENOUGH_DATA;
3300}
3301
Eric Laurenta553c252009-07-17 12:17:14 -07003302status_t AudioFlinger::RecordThread::RecordTrack::start()
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 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003308 } else {
3309 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311}
3312
Eric Laurenta553c252009-07-17 12:17:14 -07003313void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314{
Eric Laurenta553c252009-07-17 12:17:14 -07003315 sp<ThreadBase> thread = mThread.promote();
3316 if (thread != 0) {
3317 RecordThread *recordThread = (RecordThread *)thread.get();
3318 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003319 TrackBase::reset();
3320 // Force overerrun condition to avoid false overrun callback until first data is
3321 // read from buffer
3322 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324}
3325
Eric Laurent3fdb1262009-11-07 00:01:32 -08003326void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3327{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003328 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003329 (mClient == NULL) ? getpid() : mClient->pid(),
3330 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003331 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003332 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003333 mFrameCount,
3334 mState,
3335 mCblk->sampleRate,
3336 mCblk->server,
3337 mCblk->user);
3338}
3339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340
3341// ----------------------------------------------------------------------------
3342
Eric Laurenta553c252009-07-17 12:17:14 -07003343AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3344 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003345 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003347 uint32_t format,
3348 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003350 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003351 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352{
Eric Laurenta553c252009-07-17 12:17:14 -07003353
3354 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003355 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003356 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003357 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3358 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3359 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003360 playbackThread->mTracks.add(this);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003361 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3362 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3363 mCblk, mBuffer, mCblk->buffers,
3364 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003365 } else {
3366 LOGW("Error creating output track on thread %p", playbackThread);
3367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368}
3369
Eric Laurenta553c252009-07-17 12:17:14 -07003370AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371{
Eric Laurent6c30a712009-08-10 23:22:32 -07003372 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373}
3374
Eric Laurenta553c252009-07-17 12:17:14 -07003375status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376{
3377 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003378 if (status != NO_ERROR) {
3379 return status;
3380 }
3381
3382 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 mRetryCount = 127;
3384 return status;
3385}
3386
Eric Laurenta553c252009-07-17 12:17:14 -07003387void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388{
3389 Track::stop();
3390 clearBufferQueue();
3391 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003392 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393}
3394
Eric Laurenta553c252009-07-17 12:17:14 -07003395bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396{
3397 Buffer *pInBuffer;
3398 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003399 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003400 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 inBuffer.frameCount = frames;
3402 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003403
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003404 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003405
Eric Laurent62443f52009-10-05 20:29:18 -07003406 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003407 start();
3408 sp<ThreadBase> thread = mThread.promote();
3409 if (thread != 0) {
3410 MixerThread *mixerThread = (MixerThread *)thread.get();
3411 if (mCblk->frameCount > frames){
3412 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3413 uint32_t startFrames = (mCblk->frameCount - frames);
3414 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003415 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003416 pInBuffer->frameCount = startFrames;
3417 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003418 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003419 mBufferQueue.add(pInBuffer);
3420 } else {
3421 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 }
Eric Laurenta553c252009-07-17 12:17:14 -07003424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 }
3426
Eric Laurenta553c252009-07-17 12:17:14 -07003427 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 // First write pending buffers, then new data
3429 if (mBufferQueue.size()) {
3430 pInBuffer = mBufferQueue.itemAt(0);
3431 } else {
3432 pInBuffer = &inBuffer;
3433 }
Eric Laurenta553c252009-07-17 12:17:14 -07003434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 if (pInBuffer->frameCount == 0) {
3436 break;
3437 }
Eric Laurenta553c252009-07-17 12:17:14 -07003438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 if (mOutBuffer.frameCount == 0) {
3440 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003441 nsecs_t startTime = systemTime();
3442 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003443 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003444 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 break;
3446 }
Eric Laurenta553c252009-07-17 12:17:14 -07003447 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003448 if (waitTimeLeftMs >= waitTimeMs) {
3449 waitTimeLeftMs -= waitTimeMs;
3450 } else {
3451 waitTimeLeftMs = 0;
3452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 }
Eric Laurenta553c252009-07-17 12:17:14 -07003454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003456 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 mCblk->stepUser(outFrames);
3458 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003459 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003461 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 if (pInBuffer->frameCount == 0) {
3464 if (mBufferQueue.size()) {
3465 mBufferQueue.removeAt(0);
3466 delete [] pInBuffer->mBuffer;
3467 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003468 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 -08003469 } else {
3470 break;
3471 }
3472 }
3473 }
Eric Laurenta553c252009-07-17 12:17:14 -07003474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 // If we could not write all frames, allocate a buffer and queue it for next time.
3476 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003477 sp<ThreadBase> thread = mThread.promote();
3478 if (thread != 0 && !thread->standby()) {
3479 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3480 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003481 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003482 pInBuffer->frameCount = inBuffer.frameCount;
3483 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003484 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003485 mBufferQueue.add(pInBuffer);
3486 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3487 } else {
3488 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 }
3491 }
Eric Laurenta553c252009-07-17 12:17:14 -07003492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003494 // 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 -08003495 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003496 if (frames == 0 && mBufferQueue.size() == 0) {
3497 if (mCblk->user < mCblk->frameCount) {
3498 frames = mCblk->frameCount - mCblk->user;
3499 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003500 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003501 pInBuffer->frameCount = frames;
3502 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003503 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003504 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003505 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003506 stop();
3507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 }
3509
Eric Laurenta553c252009-07-17 12:17:14 -07003510 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511}
3512
Eric Laurenta553c252009-07-17 12:17:14 -07003513status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514{
3515 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 status_t result;
3517 audio_track_cblk_t* cblk = mCblk;
3518 uint32_t framesReq = buffer->frameCount;
3519
Eric Laurenta553c252009-07-17 12:17:14 -07003520// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 uint32_t framesAvail = cblk->framesAvailable();
3524
Eric Laurenta553c252009-07-17 12:17:14 -07003525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003527 Mutex::Autolock _l(cblk->lock);
3528 goto start_loop_here;
3529 while (framesAvail == 0) {
3530 active = mActive;
3531 if (UNLIKELY(!active)) {
3532 LOGV("Not active and NO_MORE_BUFFERS");
3533 return AudioTrack::NO_MORE_BUFFERS;
3534 }
3535 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3536 if (result != NO_ERROR) {
3537 return AudioTrack::NO_MORE_BUFFERS;
3538 }
3539 // read the server count again
3540 start_loop_here:
3541 framesAvail = cblk->framesAvailable_l();
3542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 }
3544
Eric Laurenta553c252009-07-17 12:17:14 -07003545// if (framesAvail < framesReq) {
3546// return AudioTrack::NO_MORE_BUFFERS;
3547// }
3548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 if (framesReq > framesAvail) {
3550 framesReq = framesAvail;
3551 }
3552
3553 uint32_t u = cblk->user;
3554 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3555
3556 if (u + framesReq > bufferEnd) {
3557 framesReq = bufferEnd - u;
3558 }
3559
3560 buffer->frameCount = framesReq;
3561 buffer->raw = (void *)cblk->buffer(u);
3562 return NO_ERROR;
3563}
3564
3565
Eric Laurenta553c252009-07-17 12:17:14 -07003566void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567{
3568 size_t size = mBufferQueue.size();
3569 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 for (size_t i = 0; i < size; i++) {
3572 pBuffer = mBufferQueue.itemAt(i);
3573 delete [] pBuffer->mBuffer;
3574 delete pBuffer;
3575 }
3576 mBufferQueue.clear();
3577}
3578
3579// ----------------------------------------------------------------------------
3580
3581AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3582 : RefBase(),
3583 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003584 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 mPid(pid)
3586{
3587 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3588}
3589
Eric Laurentb9481d82009-09-17 05:12:56 -07003590// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591AudioFlinger::Client::~Client()
3592{
Eric Laurentb9481d82009-09-17 05:12:56 -07003593 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594}
3595
3596const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3597{
3598 return mMemoryDealer;
3599}
3600
3601// ----------------------------------------------------------------------------
3602
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003603AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3604 const sp<IAudioFlingerClient>& client,
3605 pid_t pid)
3606 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3607{
3608}
3609
3610AudioFlinger::NotificationClient::~NotificationClient()
3611{
3612 mClient.clear();
3613}
3614
3615void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3616{
3617 sp<NotificationClient> keep(this);
3618 {
3619 mAudioFlinger->removeNotificationClient(mPid);
3620 }
3621}
3622
3623// ----------------------------------------------------------------------------
3624
Eric Laurenta553c252009-07-17 12:17:14 -07003625AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003626 : BnAudioTrack(),
3627 mTrack(track)
3628{
3629}
3630
3631AudioFlinger::TrackHandle::~TrackHandle() {
3632 // just stop the track on deletion, associated resources
3633 // will be freed from the main thread once all pending buffers have
3634 // been played. Unless it's not in the active track list, in which
3635 // case we free everything now...
3636 mTrack->destroy();
3637}
3638
3639status_t AudioFlinger::TrackHandle::start() {
3640 return mTrack->start();
3641}
3642
3643void AudioFlinger::TrackHandle::stop() {
3644 mTrack->stop();
3645}
3646
3647void AudioFlinger::TrackHandle::flush() {
3648 mTrack->flush();
3649}
3650
3651void AudioFlinger::TrackHandle::mute(bool e) {
3652 mTrack->mute(e);
3653}
3654
3655void AudioFlinger::TrackHandle::pause() {
3656 mTrack->pause();
3657}
3658
3659void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3660 mTrack->setVolume(left, right);
3661}
3662
3663sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3664 return mTrack->getCblk();
3665}
3666
Eric Laurent65b65452010-06-01 23:49:17 -07003667status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3668{
3669 return mTrack->attachAuxEffect(EffectId);
3670}
3671
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003672status_t AudioFlinger::TrackHandle::onTransact(
3673 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3674{
3675 return BnAudioTrack::onTransact(code, data, reply, flags);
3676}
3677
3678// ----------------------------------------------------------------------------
3679
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003680sp<IAudioRecord> AudioFlinger::openRecord(
3681 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003682 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003683 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003684 uint32_t format,
3685 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003686 int frameCount,
3687 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003688 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003689 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003690{
Eric Laurenta553c252009-07-17 12:17:14 -07003691 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003692 sp<RecordHandle> recordHandle;
3693 sp<Client> client;
3694 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003695 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003696 RecordThread *thread;
3697 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003698 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003699
3700 // check calling permissions
3701 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003702 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003703 goto Exit;
3704 }
3705
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003706 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003707 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003708 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003709 thread = checkRecordThread_l(input);
3710 if (thread == NULL) {
3711 lStatus = BAD_VALUE;
3712 goto Exit;
3713 }
3714
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003715 wclient = mClients.valueFor(pid);
3716 if (wclient != NULL) {
3717 client = wclient.promote();
3718 } else {
3719 client = new Client(this, pid);
3720 mClients.add(pid, client);
3721 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003722
Eric Laurent65b65452010-06-01 23:49:17 -07003723 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003724 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003725 lSessionId = *sessionId;
3726 } else {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08003727 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003728 if (sessionId != NULL) {
3729 *sessionId = lSessionId;
3730 }
3731 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003732 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003733 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003734 format, channelMask, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003737 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3738 // destructor is called by the TrackBase destructor with mLock held
3739 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 recordTrack.clear();
3741 lStatus = NO_MEMORY;
3742 goto Exit;
3743 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003744
3745 // return to handle to client
3746 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003747 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003748
3749Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003750 if (status) {
3751 *status = lStatus;
3752 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003753 return recordHandle;
3754}
3755
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003756// ----------------------------------------------------------------------------
3757
Eric Laurenta553c252009-07-17 12:17:14 -07003758AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003759 : BnAudioRecord(),
3760 mRecordTrack(recordTrack)
3761{
3762}
3763
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003764AudioFlinger::RecordHandle::~RecordHandle() {
3765 stop();
3766}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003767
3768status_t AudioFlinger::RecordHandle::start() {
3769 LOGV("RecordHandle::start()");
3770 return mRecordTrack->start();
3771}
3772
3773void AudioFlinger::RecordHandle::stop() {
3774 LOGV("RecordHandle::stop()");
3775 mRecordTrack->stop();
3776}
3777
3778sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3779 return mRecordTrack->getCblk();
3780}
3781
3782status_t AudioFlinger::RecordHandle::onTransact(
3783 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3784{
3785 return BnAudioRecord::onTransact(code, data, reply, flags);
3786}
3787
3788// ----------------------------------------------------------------------------
3789
Dima Zavin31f188892011-04-18 16:57:27 -07003790AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
Eric Laurent49f02be2009-11-19 09:00:56 -08003791 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003792 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003793{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003794 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07003795 mReqSampleRate = sampleRate;
3796 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003797}
3798
Eric Laurenta553c252009-07-17 12:17:14 -07003799
3800AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003801{
Eric Laurenta553c252009-07-17 12:17:14 -07003802 delete[] mRsmpInBuffer;
3803 if (mResampler != 0) {
3804 delete mResampler;
3805 delete[] mRsmpOutBuffer;
3806 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003807}
3808
Eric Laurenta553c252009-07-17 12:17:14 -07003809void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003810{
Eric Laurenta553c252009-07-17 12:17:14 -07003811 const size_t SIZE = 256;
3812 char buffer[SIZE];
3813
3814 snprintf(buffer, SIZE, "Record Thread %p", this);
3815
3816 run(buffer, PRIORITY_URGENT_AUDIO);
3817}
Eric Laurent49f02be2009-11-19 09:00:56 -08003818
Eric Laurenta553c252009-07-17 12:17:14 -07003819bool AudioFlinger::RecordThread::threadLoop()
3820{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003821 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003822 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003823
Eric Laurent4712baa2010-09-30 16:12:31 -07003824 nsecs_t lastWarning = 0;
3825
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003826 // start recording
3827 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003828
Eric Laurenta553c252009-07-17 12:17:14 -07003829 processConfigEvents();
3830
3831 { // scope for mLock
3832 Mutex::Autolock _l(mLock);
3833 checkForNewParameters_l();
3834 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3835 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07003836 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07003837 mStandby = true;
3838 }
3839
3840 if (exitPending()) break;
3841
3842 LOGV("RecordThread: loop stopping");
3843 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003844 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003845 LOGV("RecordThread: loop starting");
3846 continue;
3847 }
3848 if (mActiveTrack != 0) {
3849 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003850 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07003851 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003852 mStandby = true;
3853 }
Eric Laurenta553c252009-07-17 12:17:14 -07003854 mActiveTrack.clear();
3855 mStartStopCond.broadcast();
3856 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003857 if (mReqChannelCount != mActiveTrack->channelCount()) {
3858 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003859 mStartStopCond.broadcast();
3860 } else if (mBytesRead != 0) {
3861 // record start succeeds only if first read from audio input
3862 // succeeds
3863 if (mBytesRead > 0) {
3864 mActiveTrack->mState = TrackBase::ACTIVE;
3865 } else {
3866 mActiveTrack.clear();
3867 }
3868 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003869 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003870 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003871 }
Eric Laurenta553c252009-07-17 12:17:14 -07003872 }
3873 }
3874
3875 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003876 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3877 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003878 usleep(5000);
3879 continue;
3880 }
Eric Laurenta553c252009-07-17 12:17:14 -07003881 buffer.frameCount = mFrameCount;
3882 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3883 size_t framesOut = buffer.frameCount;
3884 if (mResampler == 0) {
3885 // no resampling
3886 while (framesOut) {
3887 size_t framesIn = mFrameCount - mRsmpInIndex;
3888 if (framesIn) {
3889 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3890 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3891 if (framesIn > framesOut)
3892 framesIn = framesOut;
3893 mRsmpInIndex += framesIn;
3894 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003895 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003896 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07003897 memcpy(dst, src, framesIn * mFrameSize);
3898 } else {
3899 int16_t *src16 = (int16_t *)src;
3900 int16_t *dst16 = (int16_t *)dst;
3901 if (mChannelCount == 1) {
3902 while (framesIn--) {
3903 *dst16++ = *src16;
3904 *dst16++ = *src16++;
3905 }
3906 } else {
3907 while (framesIn--) {
3908 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3909 src16 += 2;
3910 }
3911 }
3912 }
3913 }
3914 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003915 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003916 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07003917 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003918 framesOut = 0;
3919 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07003920 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003921 mRsmpInIndex = 0;
3922 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003923 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003924 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003925 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003926 // Force input into standby so that it tries to
3927 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07003928 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurentba8811f2010-03-02 18:38:06 -08003929 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003930 }
Eric Laurenta553c252009-07-17 12:17:14 -07003931 mRsmpInIndex = mFrameCount;
3932 framesOut = 0;
3933 buffer.frameCount = 0;
3934 }
3935 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003936 }
3937 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003938 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003939
Eric Laurenta553c252009-07-17 12:17:14 -07003940 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3941 // alter output frame count as if we were expecting stereo samples
3942 if (mChannelCount == 1 && mReqChannelCount == 1) {
3943 framesOut >>= 1;
3944 }
3945 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3946 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3947 // are 32 bit aligned which should be always true.
3948 if (mChannelCount == 2 && mReqChannelCount == 1) {
3949 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3950 // the resampler always outputs stereo samples: do post stereo to mono conversion
3951 int16_t *src = (int16_t *)mRsmpOutBuffer;
3952 int16_t *dst = buffer.i16;
3953 while (framesOut--) {
3954 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3955 src += 2;
3956 }
3957 } else {
3958 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3959 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003960
Eric Laurenta553c252009-07-17 12:17:14 -07003961 }
3962 mActiveTrack->releaseBuffer(&buffer);
3963 mActiveTrack->overflow();
3964 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003965 // client isn't retrieving buffers fast enough
3966 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07003967 if (!mActiveTrack->setOverflow()) {
3968 nsecs_t now = systemTime();
3969 if ((now - lastWarning) > kWarningThrottle) {
3970 LOGW("RecordThread: buffer overflow");
3971 lastWarning = now;
3972 }
3973 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003974 // Release the processor for a while before asking for a new buffer.
3975 // This will give the application more chance to read from the buffer and
3976 // clear the overflow.
3977 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003978 }
3979 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003980 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003981
Eric Laurenta553c252009-07-17 12:17:14 -07003982 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07003983 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003984 }
Eric Laurenta553c252009-07-17 12:17:14 -07003985 mActiveTrack.clear();
3986
Eric Laurent49f02be2009-11-19 09:00:56 -08003987 mStartStopCond.broadcast();
3988
Eric Laurenta553c252009-07-17 12:17:14 -07003989 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003990 return false;
3991}
3992
Eric Laurenta553c252009-07-17 12:17:14 -07003993status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003994{
Eric Laurenta553c252009-07-17 12:17:14 -07003995 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003996 sp <ThreadBase> strongMe = this;
3997 status_t status = NO_ERROR;
3998 {
3999 AutoMutex lock(&mLock);
4000 if (mActiveTrack != 0) {
4001 if (recordTrack != mActiveTrack.get()) {
4002 status = -EBUSY;
4003 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004004 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004005 }
4006 return status;
4007 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004008
Eric Laurent49f02be2009-11-19 09:00:56 -08004009 recordTrack->mState = TrackBase::IDLE;
4010 mActiveTrack = recordTrack;
4011 mLock.unlock();
4012 status_t status = AudioSystem::startInput(mId);
4013 mLock.lock();
4014 if (status != NO_ERROR) {
4015 mActiveTrack.clear();
4016 return status;
4017 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004018 mRsmpInIndex = mFrameCount;
4019 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004020 if (mResampler != NULL) {
4021 mResampler->reset();
4022 }
4023 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004024 // signal thread to start
4025 LOGV("Signal record thread");
4026 mWaitWorkCV.signal();
4027 // do not wait for mStartStopCond if exiting
4028 if (mExiting) {
4029 mActiveTrack.clear();
4030 status = INVALID_OPERATION;
4031 goto startError;
4032 }
4033 mStartStopCond.wait(mLock);
4034 if (mActiveTrack == 0) {
4035 LOGV("Record failed to start");
4036 status = BAD_VALUE;
4037 goto startError;
4038 }
Eric Laurenta553c252009-07-17 12:17:14 -07004039 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004040 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004041 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004042startError:
4043 AudioSystem::stopInput(mId);
4044 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004045}
4046
Eric Laurenta553c252009-07-17 12:17:14 -07004047void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4048 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004049 sp <ThreadBase> strongMe = this;
4050 {
4051 AutoMutex lock(&mLock);
4052 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4053 mActiveTrack->mState = TrackBase::PAUSING;
4054 // do not wait for mStartStopCond if exiting
4055 if (mExiting) {
4056 return;
4057 }
4058 mStartStopCond.wait(mLock);
4059 // if we have been restarted, recordTrack == mActiveTrack.get() here
4060 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4061 mLock.unlock();
4062 AudioSystem::stopInput(mId);
4063 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004064 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004065 }
4066 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004067 }
4068}
4069
Eric Laurenta553c252009-07-17 12:17:14 -07004070status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071{
4072 const size_t SIZE = 256;
4073 char buffer[SIZE];
4074 String8 result;
4075 pid_t pid = 0;
4076
Eric Laurent3fdb1262009-11-07 00:01:32 -08004077 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4078 result.append(buffer);
4079
4080 if (mActiveTrack != 0) {
4081 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004082 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004083 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004085
4086 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4087 result.append(buffer);
4088 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4089 result.append(buffer);
4090 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4091 result.append(buffer);
4092 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4093 result.append(buffer);
4094 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4095 result.append(buffer);
4096
4097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 } else {
4099 result.append("No record client\n");
4100 }
4101 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004102
4103 dumpBase(fd, args);
4104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 return NO_ERROR;
4106}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004107
Eric Laurenta553c252009-07-17 12:17:14 -07004108status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4109{
4110 size_t framesReq = buffer->frameCount;
4111 size_t framesReady = mFrameCount - mRsmpInIndex;
4112 int channelCount;
4113
4114 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004115 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004116 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004117 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004118 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004119 // Force input into standby so that it tries to
4120 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004121 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurentba8811f2010-03-02 18:38:06 -08004122 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004123 }
Eric Laurenta553c252009-07-17 12:17:14 -07004124 buffer->raw = 0;
4125 buffer->frameCount = 0;
4126 return NOT_ENOUGH_DATA;
4127 }
4128 mRsmpInIndex = 0;
4129 framesReady = mFrameCount;
4130 }
4131
4132 if (framesReq > framesReady) {
4133 framesReq = framesReady;
4134 }
4135
4136 if (mChannelCount == 1 && mReqChannelCount == 2) {
4137 channelCount = 1;
4138 } else {
4139 channelCount = 2;
4140 }
4141 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4142 buffer->frameCount = framesReq;
4143 return NO_ERROR;
4144}
4145
4146void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4147{
4148 mRsmpInIndex += buffer->frameCount;
4149 buffer->frameCount = 0;
4150}
4151
4152bool AudioFlinger::RecordThread::checkForNewParameters_l()
4153{
4154 bool reconfig = false;
4155
Eric Laurent8fce46a2009-08-04 09:45:33 -07004156 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004157 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004158 String8 keyValuePair = mNewParameters[0];
4159 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004160 int value;
4161 int reqFormat = mFormat;
4162 int reqSamplingRate = mReqSampleRate;
4163 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004164
Eric Laurenta553c252009-07-17 12:17:14 -07004165 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4166 reqSamplingRate = value;
4167 reconfig = true;
4168 }
4169 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4170 reqFormat = value;
4171 reconfig = true;
4172 }
4173 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004174 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004175 reconfig = true;
4176 }
4177 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4178 // do not accept frame count changes if tracks are open as the track buffer
4179 // size depends on frame count and correct behavior would not be garantied
4180 // if frame count is changed after track creation
4181 if (mActiveTrack != 0) {
4182 status = INVALID_OPERATION;
4183 } else {
4184 reconfig = true;
4185 }
4186 }
4187 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004188 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004189 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004190 mInput->stream->common.standby(&mInput->stream->common);
4191 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004192 }
4193 if (reconfig) {
4194 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004195 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004196 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004197 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4198 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004199 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004200 status = NO_ERROR;
4201 }
4202 if (status == NO_ERROR) {
4203 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004204 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004205 }
4206 }
4207 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004208
4209 mNewParameters.removeAt(0);
4210
Eric Laurenta553c252009-07-17 12:17:14 -07004211 mParamStatus = status;
4212 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004213 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004214 }
4215 return reconfig;
4216}
4217
4218String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4219{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004220 char *s;
4221 String8 out_s8;
4222
Dima Zavin31f188892011-04-18 16:57:27 -07004223 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004224 out_s8 = String8(s);
4225 free(s);
4226 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004227}
4228
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004229void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004230 AudioSystem::OutputDescriptor desc;
4231 void *param2 = 0;
4232
4233 switch (event) {
4234 case AudioSystem::INPUT_OPENED:
4235 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004236 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004237 desc.samplingRate = mSampleRate;
4238 desc.format = mFormat;
4239 desc.frameCount = mFrameCount;
4240 desc.latency = 0;
4241 param2 = &desc;
4242 break;
4243
4244 case AudioSystem::INPUT_CLOSED:
4245 default:
4246 break;
4247 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004248 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004249}
4250
4251void AudioFlinger::RecordThread::readInputParameters()
4252{
4253 if (mRsmpInBuffer) delete mRsmpInBuffer;
4254 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4255 if (mResampler) delete mResampler;
4256 mResampler = 0;
4257
Dima Zavin31f188892011-04-18 16:57:27 -07004258 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004259 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4260 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004261 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4262 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4263 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004264 mFrameCount = mInputBytes / mFrameSize;
4265 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4266
4267 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4268 {
4269 int channelCount;
4270 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4271 // stereo to mono post process as the resampler always outputs stereo.
4272 if (mChannelCount == 1 && mReqChannelCount == 2) {
4273 channelCount = 1;
4274 } else {
4275 channelCount = 2;
4276 }
4277 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4278 mResampler->setSampleRate(mSampleRate);
4279 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4280 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4281
4282 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4283 if (mChannelCount == 1 && mReqChannelCount == 1) {
4284 mFrameCount >>= 1;
4285 }
4286
4287 }
4288 mRsmpInIndex = mFrameCount;
4289}
4290
Eric Laurent47d0a922010-02-26 02:47:27 -08004291unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4292{
Dima Zavin31f188892011-04-18 16:57:27 -07004293 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004294}
4295
Eric Laurenta553c252009-07-17 12:17:14 -07004296// ----------------------------------------------------------------------------
4297
Eric Laurentddb78e72009-07-28 08:44:33 -07004298int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004299 uint32_t *pSamplingRate,
4300 uint32_t *pFormat,
4301 uint32_t *pChannels,
4302 uint32_t *pLatencyMs,
4303 uint32_t flags)
4304{
4305 status_t status;
4306 PlaybackThread *thread = NULL;
4307 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4308 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4309 uint32_t format = pFormat ? *pFormat : 0;
4310 uint32_t channels = pChannels ? *pChannels : 0;
4311 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004312 audio_stream_out_t *outStream;
4313 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004314
4315 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4316 pDevices ? *pDevices : 0,
4317 samplingRate,
4318 format,
4319 channels,
4320 flags);
4321
4322 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004323 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004324 }
Dima Zavin31f188892011-04-18 16:57:27 -07004325
Eric Laurenta553c252009-07-17 12:17:14 -07004326 Mutex::Autolock _l(mLock);
4327
Dima Zavin31f188892011-04-18 16:57:27 -07004328 outHwDev = findSuitableHwDev_l(*pDevices);
4329 if (outHwDev == NULL)
4330 return 0;
4331
4332 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4333 &channels, &samplingRate, &outStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004334 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004335 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004336 samplingRate,
4337 format,
4338 channels,
4339 status);
4340
4341 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004342 if (outStream != NULL) {
4343 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004344 int id = nextUniqueId_l();
Dima Zavin31f188892011-04-18 16:57:27 -07004345
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004346 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4347 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4348 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004349 thread = new DirectOutputThread(this, output, id, *pDevices);
4350 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004351 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004352 thread = new MixerThread(this, output, id, *pDevices);
4353 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004354 }
Eric Laurent65b65452010-06-01 23:49:17 -07004355 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004356
4357 if (pSamplingRate) *pSamplingRate = samplingRate;
4358 if (pFormat) *pFormat = format;
4359 if (pChannels) *pChannels = channels;
4360 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004361
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004362 // notify client processes of the new output creation
4363 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004364 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004365 }
4366
Eric Laurent9cc489a22009-12-05 05:20:01 -08004367 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004368}
4369
Eric Laurentddb78e72009-07-28 08:44:33 -07004370int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004371{
4372 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004373 MixerThread *thread1 = checkMixerThread_l(output1);
4374 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004375
Eric Laurentddb78e72009-07-28 08:44:33 -07004376 if (thread1 == NULL || thread2 == NULL) {
4377 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4378 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004379 }
4380
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004381 int id = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004382 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004383 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004384 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004385 // notify client processes of the new output creation
4386 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004387 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004388}
4389
Eric Laurentddb78e72009-07-28 08:44:33 -07004390status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004391{
Eric Laurent49018a52009-08-04 08:37:05 -07004392 // keep strong reference on the playback thread so that
4393 // it is not destroyed while exit() is executed
4394 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004395 {
4396 Mutex::Autolock _l(mLock);
4397 thread = checkPlaybackThread_l(output);
4398 if (thread == NULL) {
4399 return BAD_VALUE;
4400 }
4401
Eric Laurentddb78e72009-07-28 08:44:33 -07004402 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004403
4404 if (thread->type() == PlaybackThread::MIXER) {
4405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004406 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4407 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004408 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004409 }
4410 }
4411 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004412 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004413 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004414 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004415 }
4416 thread->exit();
4417
Eric Laurent49018a52009-08-04 08:37:05 -07004418 if (thread->type() != PlaybackThread::DUPLICATING) {
Dima Zavin31f188892011-04-18 16:57:27 -07004419 AudioStreamOut *out = thread->getOutput();
4420 out->hwDev->close_output_stream(out->hwDev, out->stream);
4421 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07004422 }
Eric Laurenta553c252009-07-17 12:17:14 -07004423 return NO_ERROR;
4424}
4425
Eric Laurentddb78e72009-07-28 08:44:33 -07004426status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004427{
4428 Mutex::Autolock _l(mLock);
4429 PlaybackThread *thread = checkPlaybackThread_l(output);
4430
4431 if (thread == NULL) {
4432 return BAD_VALUE;
4433 }
4434
Eric Laurentddb78e72009-07-28 08:44:33 -07004435 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004436 thread->suspend();
4437
4438 return NO_ERROR;
4439}
4440
Eric Laurentddb78e72009-07-28 08:44:33 -07004441status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004442{
4443 Mutex::Autolock _l(mLock);
4444 PlaybackThread *thread = checkPlaybackThread_l(output);
4445
4446 if (thread == NULL) {
4447 return BAD_VALUE;
4448 }
4449
Eric Laurentddb78e72009-07-28 08:44:33 -07004450 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004451
4452 thread->restore();
4453
4454 return NO_ERROR;
4455}
4456
Eric Laurentddb78e72009-07-28 08:44:33 -07004457int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004458 uint32_t *pSamplingRate,
4459 uint32_t *pFormat,
4460 uint32_t *pChannels,
4461 uint32_t acoustics)
4462{
4463 status_t status;
4464 RecordThread *thread = NULL;
4465 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4466 uint32_t format = pFormat ? *pFormat : 0;
4467 uint32_t channels = pChannels ? *pChannels : 0;
4468 uint32_t reqSamplingRate = samplingRate;
4469 uint32_t reqFormat = format;
4470 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07004471 audio_stream_in_t *inStream;
4472 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004473
4474 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004475 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004476 }
Dima Zavin31f188892011-04-18 16:57:27 -07004477
Eric Laurenta553c252009-07-17 12:17:14 -07004478 Mutex::Autolock _l(mLock);
4479
Dima Zavin31f188892011-04-18 16:57:27 -07004480 inHwDev = findSuitableHwDev_l(*pDevices);
4481 if (inHwDev == NULL)
4482 return 0;
4483
4484 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4485 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004486 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07004487 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004488 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004489 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004490 samplingRate,
4491 format,
4492 channels,
4493 acoustics,
4494 status);
4495
4496 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4497 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4498 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07004499 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004500 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07004501 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004502 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004503 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07004504 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4505 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004506 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07004507 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004508 }
4509
Dima Zavin31f188892011-04-18 16:57:27 -07004510 if (inStream != NULL) {
4511 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4512
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004513 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004514 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004515 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4516 mRecordThreads.add(id, thread);
4517 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004518 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4519 if (pFormat) *pFormat = format;
4520 if (pChannels) *pChannels = reqChannels;
4521
Dima Zavin31f188892011-04-18 16:57:27 -07004522 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004523
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004524 // notify client processes of the new input creation
4525 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004526 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004527 }
4528
Eric Laurent9cc489a22009-12-05 05:20:01 -08004529 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004530}
4531
Eric Laurentddb78e72009-07-28 08:44:33 -07004532status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004533{
Eric Laurent49018a52009-08-04 08:37:05 -07004534 // keep strong reference on the record thread so that
4535 // it is not destroyed while exit() is executed
4536 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004537 {
4538 Mutex::Autolock _l(mLock);
4539 thread = checkRecordThread_l(input);
4540 if (thread == NULL) {
4541 return BAD_VALUE;
4542 }
4543
Eric Laurentddb78e72009-07-28 08:44:33 -07004544 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004545 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004546 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004547 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004548 }
4549 thread->exit();
4550
Dima Zavin31f188892011-04-18 16:57:27 -07004551 AudioStreamIn *in = thread->getInput();
4552 in->hwDev->close_input_stream(in->hwDev, in->stream);
4553 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07004554
Eric Laurenta553c252009-07-17 12:17:14 -07004555 return NO_ERROR;
4556}
4557
Eric Laurentddb78e72009-07-28 08:44:33 -07004558status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004559{
4560 Mutex::Autolock _l(mLock);
4561 MixerThread *dstThread = checkMixerThread_l(output);
4562 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004563 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004564 return BAD_VALUE;
4565 }
4566
Eric Laurentddb78e72009-07-28 08:44:33 -07004567 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004568 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004569
4570 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004571 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004572 if (thread != dstThread &&
4573 thread->type() != PlaybackThread::DIRECT) {
4574 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004575 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004576 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004577 }
Eric Laurentd069f322009-09-01 05:56:26 -07004578
Eric Laurenta553c252009-07-17 12:17:14 -07004579 return NO_ERROR;
4580}
4581
Eric Laurent65b65452010-06-01 23:49:17 -07004582
4583int AudioFlinger::newAudioSessionId()
4584{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004585 AutoMutex _l(mLock);
4586 return nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004587}
4588
Eric Laurenta553c252009-07-17 12:17:14 -07004589// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004590AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004591{
4592 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004593 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4594 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004595 }
Eric Laurenta553c252009-07-17 12:17:14 -07004596 return thread;
4597}
4598
4599// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004600AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004601{
4602 PlaybackThread *thread = checkPlaybackThread_l(output);
4603 if (thread != NULL) {
4604 if (thread->type() == PlaybackThread::DIRECT) {
4605 thread = NULL;
4606 }
4607 }
4608 return (MixerThread *)thread;
4609}
4610
4611// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004612AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004613{
4614 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004615 if (mRecordThreads.indexOfKey(input) >= 0) {
4616 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004617 }
Eric Laurenta553c252009-07-17 12:17:14 -07004618 return thread;
4619}
4620
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004621// nextUniqueId_l() must be called with AudioFlinger::mLock held
4622int AudioFlinger::nextUniqueId_l()
Eric Laurent65b65452010-06-01 23:49:17 -07004623{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004624 return mNextUniqueId++;
Eric Laurent65b65452010-06-01 23:49:17 -07004625}
4626
4627// ----------------------------------------------------------------------------
4628// Effect management
4629// ----------------------------------------------------------------------------
4630
4631
Eric Laurent65b65452010-06-01 23:49:17 -07004632status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4633{
4634 Mutex::Autolock _l(mLock);
4635 return EffectQueryNumberEffects(numEffects);
4636}
4637
Eric Laurent53334cd2010-06-23 17:38:20 -07004638status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004639{
4640 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004641 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004642}
4643
4644status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4645{
4646 Mutex::Autolock _l(mLock);
4647 return EffectGetDescriptor(pUuid, descriptor);
4648}
4649
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004650
4651// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4652static const effect_uuid_t VISUALIZATION_UUID_ =
4653 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4654
Eric Laurent65b65452010-06-01 23:49:17 -07004655sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4656 effect_descriptor_t *pDesc,
4657 const sp<IEffectClient>& effectClient,
4658 int32_t priority,
4659 int output,
4660 int sessionId,
4661 status_t *status,
4662 int *id,
4663 int *enabled)
4664{
4665 status_t lStatus = NO_ERROR;
4666 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07004667 effect_descriptor_t desc;
4668 sp<Client> client;
4669 wp<Client> wclient;
4670
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004671 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4672 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004673
4674 if (pDesc == NULL) {
4675 lStatus = BAD_VALUE;
4676 goto Exit;
4677 }
4678
Eric Laurent98c92592010-09-23 16:10:16 -07004679 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004680 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07004681 lStatus = PERMISSION_DENIED;
4682 goto Exit;
4683 }
4684
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004685 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07004686 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004687 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07004688 lStatus = PERMISSION_DENIED;
4689 goto Exit;
4690 }
4691
4692 // check recording permission for visualizer
4693 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4694 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4695 !recordingAllowed()) {
4696 lStatus = PERMISSION_DENIED;
4697 goto Exit;
4698 }
4699
4700 if (output == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004701 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07004702 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004703 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07004704 lStatus = BAD_VALUE;
4705 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004706 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07004707 // if the output returned by getOutputForEffect() is removed before we lock the
4708 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4709 // and we will exit safely
4710 output = AudioSystem::getOutputForEffect(&desc);
4711 }
4712 }
4713
Eric Laurent65b65452010-06-01 23:49:17 -07004714 {
4715 Mutex::Autolock _l(mLock);
4716
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004717
Eric Laurent65b65452010-06-01 23:49:17 -07004718 if (!EffectIsNullUuid(&pDesc->uuid)) {
4719 // if uuid is specified, request effect descriptor
4720 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4721 if (lStatus < 0) {
4722 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4723 goto Exit;
4724 }
4725 } else {
4726 // if uuid is not specified, look for an available implementation
4727 // of the required type in effect factory
4728 if (EffectIsNullUuid(&pDesc->type)) {
4729 LOGW("createEffect() no effect type");
4730 lStatus = BAD_VALUE;
4731 goto Exit;
4732 }
4733 uint32_t numEffects = 0;
4734 effect_descriptor_t d;
4735 bool found = false;
4736
4737 lStatus = EffectQueryNumberEffects(&numEffects);
4738 if (lStatus < 0) {
4739 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4740 goto Exit;
4741 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004742 for (uint32_t i = 0; i < numEffects; i++) {
4743 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004744 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004745 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004746 continue;
4747 }
4748 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4749 // If matching type found save effect descriptor. If the session is
4750 // 0 and the effect is not auxiliary, continue enumeration in case
4751 // an auxiliary version of this effect type is available
4752 found = true;
4753 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004754 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004755 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4756 break;
4757 }
4758 }
4759 }
4760 if (!found) {
4761 lStatus = BAD_VALUE;
4762 LOGW("createEffect() effect not found");
4763 goto Exit;
4764 }
4765 // For same effect type, chose auxiliary version over insert version if
4766 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004767 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004768 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4769 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4770 }
4771 }
4772
4773 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004774 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004775 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4776 lStatus = INVALID_OPERATION;
4777 goto Exit;
4778 }
4779
4780 // return effect descriptor
4781 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4782
4783 // If output is not specified try to find a matching audio session ID in one of the
4784 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07004785 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4786 // because of code checking output when entering the function.
Eric Laurent65b65452010-06-01 23:49:17 -07004787 if (output == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07004788 // look for the thread where the specified audio session is present
4789 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4790 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4791 output = mPlaybackThreads.keyAt(i);
4792 break;
Eric Laurent493941b2010-07-28 01:32:47 -07004793 }
Eric Laurent65b65452010-06-01 23:49:17 -07004794 }
Eric Laurent98c92592010-09-23 16:10:16 -07004795 // If no output thread contains the requested session ID, default to
4796 // first output. The effect chain will be moved to the correct output
4797 // thread when a track with the same session ID is created
4798 if (output == 0 && mPlaybackThreads.size()) {
4799 output = mPlaybackThreads.keyAt(0);
4800 }
Eric Laurent65b65452010-06-01 23:49:17 -07004801 }
Eric Laurent98c92592010-09-23 16:10:16 -07004802 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004803 PlaybackThread *thread = checkPlaybackThread_l(output);
4804 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004805 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004806 lStatus = BAD_VALUE;
4807 goto Exit;
4808 }
4809
Eric Laurent98c92592010-09-23 16:10:16 -07004810 // TODO: allow attachment of effect to inputs
4811
Eric Laurent65b65452010-06-01 23:49:17 -07004812 wclient = mClients.valueFor(pid);
4813
4814 if (wclient != NULL) {
4815 client = wclient.promote();
4816 } else {
4817 client = new Client(this, pid);
4818 mClients.add(pid, client);
4819 }
4820
4821 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004822 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4823 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004824 if (handle != 0 && id != NULL) {
4825 *id = handle->id();
4826 }
4827 }
4828
4829Exit:
4830 if(status) {
4831 *status = lStatus;
4832 }
4833 return handle;
4834}
4835
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004836status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4837{
4838 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4839 session, srcOutput, dstOutput);
4840 Mutex::Autolock _l(mLock);
4841 if (srcOutput == dstOutput) {
4842 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4843 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004844 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004845 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4846 if (srcThread == NULL) {
4847 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4848 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004849 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004850 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4851 if (dstThread == NULL) {
4852 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4853 return BAD_VALUE;
4854 }
4855
4856 Mutex::Autolock _dl(dstThread->mLock);
4857 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07004858 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004859
Eric Laurent53334cd2010-06-23 17:38:20 -07004860 return NO_ERROR;
4861}
4862
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004863// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4864status_t AudioFlinger::moveEffectChain_l(int session,
4865 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07004866 AudioFlinger::PlaybackThread *dstThread,
4867 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004868{
4869 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4870 session, srcThread, dstThread);
4871
4872 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4873 if (chain == 0) {
4874 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4875 session, srcThread);
4876 return INVALID_OPERATION;
4877 }
4878
Eric Laurent493941b2010-07-28 01:32:47 -07004879 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004880 // so that a new chain is created with correct parameters when first effect is added. This is
4881 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4882 // removed.
4883 srcThread->removeEffectChain_l(chain);
4884
4885 // transfer all effects one by one so that new effect chain is created on new thread with
4886 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07004887 int dstOutput = dstThread->id();
4888 sp<EffectChain> dstChain;
4889 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004890 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4891 while (effect != 0) {
4892 srcThread->removeEffect_l(effect);
4893 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07004894 // if the move request is not received from audio policy manager, the effect must be
4895 // re-registered with the new strategy and output
4896 if (dstChain == 0) {
4897 dstChain = effect->chain().promote();
4898 if (dstChain == 0) {
4899 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4900 srcThread->addEffect_l(effect);
4901 return NO_INIT;
4902 }
4903 strategy = dstChain->strategy();
4904 }
4905 if (reRegister) {
4906 AudioSystem::unregisterEffect(effect->id());
4907 AudioSystem::registerEffect(&effect->desc(),
4908 dstOutput,
4909 strategy,
4910 session,
4911 effect->id());
4912 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004913 effect = chain->getEffectFromId_l(0);
4914 }
4915
4916 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004917}
4918
Eric Laurent65b65452010-06-01 23:49:17 -07004919// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4920sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4921 const sp<AudioFlinger::Client>& client,
4922 const sp<IEffectClient>& effectClient,
4923 int32_t priority,
4924 int sessionId,
4925 effect_descriptor_t *desc,
4926 int *enabled,
4927 status_t *status
4928 )
4929{
4930 sp<EffectModule> effect;
4931 sp<EffectHandle> handle;
4932 status_t lStatus;
4933 sp<Track> track;
4934 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004935 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004936 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004937 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004938
4939 if (mOutput == 0) {
4940 LOGW("createEffect_l() Audio driver not initialized.");
4941 lStatus = NO_INIT;
4942 goto Exit;
4943 }
4944
4945 // Do not allow auxiliary effect on session other than 0
4946 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004947 sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004948 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4949 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004950 lStatus = BAD_VALUE;
4951 goto Exit;
4952 }
4953
4954 // Do not allow effects with session ID 0 on direct output or duplicating threads
4955 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004956 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004957 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4958 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004959 lStatus = BAD_VALUE;
4960 goto Exit;
4961 }
4962
4963 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4964
4965 { // scope for mLock
4966 Mutex::Autolock _l(mLock);
4967
4968 // check for existing effect chain with the requested audio session
4969 chain = getEffectChain_l(sessionId);
4970 if (chain == 0) {
4971 // create a new chain for this session
4972 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4973 chain = new EffectChain(this, sessionId);
4974 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004975 chain->setStrategy(getStrategyForSession_l(sessionId));
4976 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004977 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004978 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004979 }
4980
4981 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4982
4983 if (effect == 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004984 int id = mAudioFlinger->nextUniqueId_l();
Eric Laurent53334cd2010-06-23 17:38:20 -07004985 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004986 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07004987 if (lStatus != NO_ERROR) {
4988 goto Exit;
4989 }
4990 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004991 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004992 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004993 lStatus = effect->status();
4994 if (lStatus != NO_ERROR) {
4995 goto Exit;
4996 }
Eric Laurent76c40f72010-07-15 12:50:15 -07004997 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004998 if (lStatus != NO_ERROR) {
4999 goto Exit;
5000 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005001 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005002
5003 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005004 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005005 }
5006 // create effect handle and connect it to effect module
5007 handle = new EffectHandle(effect, client, effectClient, priority);
5008 lStatus = effect->addHandle(handle);
5009 if (enabled) {
5010 *enabled = (int)effect->isEnabled();
5011 }
5012 }
5013
5014Exit:
5015 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005016 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005017 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005018 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005019 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005020 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005021 AudioSystem::unregisterEffect(effect->id());
5022 }
5023 if (chainCreated) {
5024 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005025 }
Eric Laurent65b65452010-06-01 23:49:17 -07005026 handle.clear();
5027 }
5028
5029 if(status) {
5030 *status = lStatus;
5031 }
5032 return handle;
5033}
5034
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005035// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5036// PlaybackThread::mLock held
5037status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5038{
5039 // check for existing effect chain with the requested audio session
5040 int sessionId = effect->sessionId();
5041 sp<EffectChain> chain = getEffectChain_l(sessionId);
5042 bool chainCreated = false;
5043
5044 if (chain == 0) {
5045 // create a new chain for this session
5046 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5047 chain = new EffectChain(this, sessionId);
5048 addEffectChain_l(chain);
5049 chain->setStrategy(getStrategyForSession_l(sessionId));
5050 chainCreated = true;
5051 }
5052 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5053
5054 if (chain->getEffectFromId_l(effect->id()) != 0) {
5055 LOGW("addEffect_l() %p effect %s already present in chain %p",
5056 this, effect->desc().name, chain.get());
5057 return BAD_VALUE;
5058 }
5059
5060 status_t status = chain->addEffect_l(effect);
5061 if (status != NO_ERROR) {
5062 if (chainCreated) {
5063 removeEffectChain_l(chain);
5064 }
5065 return status;
5066 }
5067
5068 effect->setDevice(mDevice);
5069 effect->setMode(mAudioFlinger->getMode());
5070 return NO_ERROR;
5071}
5072
5073void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5074
5075 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005076 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005077 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5078 detachAuxEffect_l(effect->id());
5079 }
5080
5081 sp<EffectChain> chain = effect->chain().promote();
5082 if (chain != 0) {
5083 // remove effect chain if removing last effect
5084 if (chain->removeEffect_l(effect) == 0) {
5085 removeEffectChain_l(chain);
5086 }
5087 } else {
5088 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5089 }
5090}
5091
5092void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5093 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005094 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005095 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005096 // delete the effect module if removing last handle on it
5097 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005098 removeEffect_l(effect);
5099 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07005100 }
5101}
5102
Eric Laurent65b65452010-06-01 23:49:17 -07005103status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5104{
5105 int session = chain->sessionId();
5106 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005107 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005108
5109 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005110 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005111 // Only one effect chain can be present in direct output thread and it uses
5112 // the mix buffer as input
5113 if (mType != DIRECT) {
5114 size_t numSamples = mFrameCount * mChannelCount;
5115 buffer = new int16_t[numSamples];
5116 memset(buffer, 0, numSamples * sizeof(int16_t));
5117 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5118 ownsBuffer = true;
5119 }
Eric Laurent65b65452010-06-01 23:49:17 -07005120
Eric Laurent53334cd2010-06-23 17:38:20 -07005121 // Attach all tracks with same session ID to this chain.
5122 for (size_t i = 0; i < mTracks.size(); ++i) {
5123 sp<Track> track = mTracks[i];
5124 if (session == track->sessionId()) {
5125 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5126 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005127 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005128 }
5129 }
5130
5131 // indicate all active tracks in the chain
5132 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5133 sp<Track> track = mActiveTracks[i].promote();
5134 if (track == 0) continue;
5135 if (session == track->sessionId()) {
5136 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005137 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005138 }
Eric Laurent65b65452010-06-01 23:49:17 -07005139 }
5140 }
5141
Eric Laurent53334cd2010-06-23 17:38:20 -07005142 chain->setInBuffer(buffer, ownsBuffer);
5143 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005144 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005145 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005146 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5147 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005148 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005149 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5150 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005151 // Effect chain for other sessions are inserted at beginning of effect
5152 // chains list to be processed before output mix effects. Relative order between other
5153 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005154 size_t size = mEffectChains.size();
5155 size_t i = 0;
5156 for (i = 0; i < size; i++) {
5157 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005158 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005159 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005160
5161 return NO_ERROR;
5162}
5163
5164size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5165{
5166 int session = chain->sessionId();
5167
5168 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5169
5170 for (size_t i = 0; i < mEffectChains.size(); i++) {
5171 if (chain == mEffectChains[i]) {
5172 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005173 // detach all active tracks from the chain
5174 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5175 sp<Track> track = mActiveTracks[i].promote();
5176 if (track == 0) continue;
5177 if (session == track->sessionId()) {
5178 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5179 chain.get(), session);
5180 chain->decActiveTrackCnt();
5181 }
5182 }
5183
Eric Laurent65b65452010-06-01 23:49:17 -07005184 // detach all tracks with same session ID from this chain
5185 for (size_t i = 0; i < mTracks.size(); ++i) {
5186 sp<Track> track = mTracks[i];
5187 if (session == track->sessionId()) {
5188 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005189 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005190 }
5191 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005192 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005193 }
5194 }
5195 return mEffectChains.size();
5196}
5197
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005198void AudioFlinger::PlaybackThread::lockEffectChains_l(
5199 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005200{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005201 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005202 for (size_t i = 0; i < mEffectChains.size(); i++) {
5203 mEffectChains[i]->lock();
5204 }
5205}
5206
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005207void AudioFlinger::PlaybackThread::unlockEffectChains(
5208 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005209{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005210 for (size_t i = 0; i < effectChains.size(); i++) {
5211 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005212 }
5213}
5214
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005215
Eric Laurent65b65452010-06-01 23:49:17 -07005216sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5217{
5218 sp<EffectModule> effect;
5219
5220 sp<EffectChain> chain = getEffectChain_l(sessionId);
5221 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005222 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005223 }
5224 return effect;
5225}
5226
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005227status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5228 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005229{
5230 Mutex::Autolock _l(mLock);
5231 return attachAuxEffect_l(track, EffectId);
5232}
5233
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005234status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5235 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005236{
5237 status_t status = NO_ERROR;
5238
5239 if (EffectId == 0) {
5240 track->setAuxBuffer(0, NULL);
5241 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005242 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5243 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005244 if (effect != 0) {
5245 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5246 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5247 } else {
5248 status = INVALID_OPERATION;
5249 }
5250 } else {
5251 status = BAD_VALUE;
5252 }
5253 }
5254 return status;
5255}
5256
5257void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5258{
5259 for (size_t i = 0; i < mTracks.size(); ++i) {
5260 sp<Track> track = mTracks[i];
5261 if (track->auxEffectId() == effectId) {
5262 attachAuxEffect_l(track, 0);
5263 }
5264 }
5265}
5266
5267// ----------------------------------------------------------------------------
5268// EffectModule implementation
5269// ----------------------------------------------------------------------------
5270
5271#undef LOG_TAG
5272#define LOG_TAG "AudioFlinger::EffectModule"
5273
5274AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5275 const wp<AudioFlinger::EffectChain>& chain,
5276 effect_descriptor_t *desc,
5277 int id,
5278 int sessionId)
5279 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5280 mStatus(NO_INIT), mState(IDLE)
5281{
5282 LOGV("Constructor %p", this);
5283 int lStatus;
5284 sp<ThreadBase> thread = mThread.promote();
5285 if (thread == 0) {
5286 return;
5287 }
5288 PlaybackThread *p = (PlaybackThread *)thread.get();
5289
5290 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5291
5292 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005293 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5294
Eric Laurent65b65452010-06-01 23:49:17 -07005295 if (mStatus != NO_ERROR) {
5296 return;
5297 }
5298 lStatus = init();
5299 if (lStatus < 0) {
5300 mStatus = lStatus;
5301 goto Error;
5302 }
5303
5304 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5305 return;
5306Error:
5307 EffectRelease(mEffectInterface);
5308 mEffectInterface = NULL;
5309 LOGV("Constructor Error %d", mStatus);
5310}
5311
5312AudioFlinger::EffectModule::~EffectModule()
5313{
5314 LOGV("Destructor %p", this);
5315 if (mEffectInterface != NULL) {
5316 // release effect engine
5317 EffectRelease(mEffectInterface);
5318 }
5319}
5320
5321status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5322{
5323 status_t status;
5324
5325 Mutex::Autolock _l(mLock);
5326 // First handle in mHandles has highest priority and controls the effect module
5327 int priority = handle->priority();
5328 size_t size = mHandles.size();
5329 sp<EffectHandle> h;
5330 size_t i;
5331 for (i = 0; i < size; i++) {
5332 h = mHandles[i].promote();
5333 if (h == 0) continue;
5334 if (h->priority() <= priority) break;
5335 }
5336 // if inserted in first place, move effect control from previous owner to this handle
5337 if (i == 0) {
5338 if (h != 0) {
5339 h->setControl(false, true);
5340 }
5341 handle->setControl(true, false);
5342 status = NO_ERROR;
5343 } else {
5344 status = ALREADY_EXISTS;
5345 }
5346 mHandles.insertAt(handle, i);
5347 return status;
5348}
5349
5350size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5351{
5352 Mutex::Autolock _l(mLock);
5353 size_t size = mHandles.size();
5354 size_t i;
5355 for (i = 0; i < size; i++) {
5356 if (mHandles[i] == handle) break;
5357 }
5358 if (i == size) {
5359 return size;
5360 }
5361 mHandles.removeAt(i);
5362 size = mHandles.size();
5363 // if removed from first place, move effect control from this handle to next in line
5364 if (i == 0 && size != 0) {
5365 sp<EffectHandle> h = mHandles[0].promote();
5366 if (h != 0) {
5367 h->setControl(true, true);
5368 }
5369 }
5370
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005371 // Release effect engine here so that it is done immediately. Otherwise it will be released
5372 // by the destructor when the last strong reference on the this object is released which can
5373 // happen after next process is called on this effect.
5374 if (size == 0 && mEffectInterface != NULL) {
5375 // release effect engine
5376 EffectRelease(mEffectInterface);
5377 mEffectInterface = NULL;
5378 }
5379
Eric Laurent65b65452010-06-01 23:49:17 -07005380 return size;
5381}
5382
5383void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5384{
5385 // keep a strong reference on this EffectModule to avoid calling the
5386 // destructor before we exit
5387 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005388 {
5389 sp<ThreadBase> thread = mThread.promote();
5390 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005391 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005392 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005393 }
5394 }
5395}
5396
Eric Laurent7d850f22010-07-09 13:34:17 -07005397void AudioFlinger::EffectModule::updateState() {
5398 Mutex::Autolock _l(mLock);
5399
5400 switch (mState) {
5401 case RESTART:
5402 reset_l();
5403 // FALL THROUGH
5404
5405 case STARTING:
5406 // clear auxiliary effect input buffer for next accumulation
5407 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5408 memset(mConfig.inputCfg.buffer.raw,
5409 0,
5410 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5411 }
5412 start_l();
5413 mState = ACTIVE;
5414 break;
5415 case STOPPING:
5416 stop_l();
5417 mDisableWaitCnt = mMaxDisableWaitCnt;
5418 mState = STOPPED;
5419 break;
5420 case STOPPED:
5421 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5422 // turn off sequence.
5423 if (--mDisableWaitCnt == 0) {
5424 reset_l();
5425 mState = IDLE;
5426 }
5427 break;
5428 default: //IDLE , ACTIVE
5429 break;
5430 }
5431}
5432
Eric Laurent65b65452010-06-01 23:49:17 -07005433void AudioFlinger::EffectModule::process()
5434{
5435 Mutex::Autolock _l(mLock);
5436
Eric Laurent7d850f22010-07-09 13:34:17 -07005437 if (mEffectInterface == NULL ||
5438 mConfig.inputCfg.buffer.raw == NULL ||
5439 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005440 return;
5441 }
5442
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005443 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005444 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5445 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5446 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5447 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005448 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005449 }
5450
Eric Laurent65b65452010-06-01 23:49:17 -07005451 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005452 int ret = (*mEffectInterface)->process(mEffectInterface,
5453 &mConfig.inputCfg.buffer,
5454 &mConfig.outputCfg.buffer);
5455
5456 // force transition to IDLE state when engine is ready
5457 if (mState == STOPPED && ret == -ENODATA) {
5458 mDisableWaitCnt = 1;
5459 }
Eric Laurent65b65452010-06-01 23:49:17 -07005460
5461 // clear auxiliary effect input buffer for next accumulation
5462 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005463 memset(mConfig.inputCfg.buffer.raw, 0,
5464 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07005465 }
5466 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08005467 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5468 // If an insert effect is idle and input buffer is different from output buffer,
5469 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07005470 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07005471 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005472 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5473 int16_t *in = mConfig.inputCfg.buffer.s16;
5474 int16_t *out = mConfig.outputCfg.buffer.s16;
5475 for (size_t i = 0; i < frameCnt; i++) {
5476 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07005477 }
Eric Laurent65b65452010-06-01 23:49:17 -07005478 }
5479 }
5480}
5481
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005482void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005483{
5484 if (mEffectInterface == NULL) {
5485 return;
5486 }
5487 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5488}
5489
5490status_t AudioFlinger::EffectModule::configure()
5491{
5492 uint32_t channels;
5493 if (mEffectInterface == NULL) {
5494 return NO_INIT;
5495 }
5496
5497 sp<ThreadBase> thread = mThread.promote();
5498 if (thread == 0) {
5499 return DEAD_OBJECT;
5500 }
5501
5502 // TODO: handle configuration of effects replacing track process
5503 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07005504 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07005505 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07005506 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07005507 }
5508
5509 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07005510 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07005511 } else {
5512 mConfig.inputCfg.channels = channels;
5513 }
5514 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07005515 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5516 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07005517 mConfig.inputCfg.samplingRate = thread->sampleRate();
5518 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5519 mConfig.inputCfg.bufferProvider.cookie = NULL;
5520 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5521 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5522 mConfig.outputCfg.bufferProvider.cookie = NULL;
5523 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5524 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5525 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5526 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005527 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005528 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005529 // - in other sessions:
5530 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5531 // other effect: overwrites output buffer: input buffer == output buffer
5532 // Auxiliary effect:
5533 // accumulates in output buffer: input buffer != output buffer
5534 // Therefore: accumulate <=> input buffer != output buffer
5535 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5536 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5537 } else {
5538 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5539 }
5540 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5541 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5542 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5543 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5544
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005545 LOGV("configure() %p thread %p buffer %p framecount %d",
5546 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5547
Eric Laurent65b65452010-06-01 23:49:17 -07005548 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005549 uint32_t size = sizeof(int);
5550 status_t status = (*mEffectInterface)->command(mEffectInterface,
5551 EFFECT_CMD_CONFIGURE,
5552 sizeof(effect_config_t),
5553 &mConfig,
5554 &size,
5555 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005556 if (status == 0) {
5557 status = cmdStatus;
5558 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005559
5560 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5561 (1000 * mConfig.outputCfg.buffer.frameCount);
5562
Eric Laurent65b65452010-06-01 23:49:17 -07005563 return status;
5564}
5565
5566status_t AudioFlinger::EffectModule::init()
5567{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005568 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005569 if (mEffectInterface == NULL) {
5570 return NO_INIT;
5571 }
5572 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005573 uint32_t size = sizeof(status_t);
5574 status_t status = (*mEffectInterface)->command(mEffectInterface,
5575 EFFECT_CMD_INIT,
5576 0,
5577 NULL,
5578 &size,
5579 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005580 if (status == 0) {
5581 status = cmdStatus;
5582 }
5583 return status;
5584}
5585
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005586status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005587{
5588 if (mEffectInterface == NULL) {
5589 return NO_INIT;
5590 }
5591 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005592 uint32_t size = sizeof(status_t);
5593 status_t status = (*mEffectInterface)->command(mEffectInterface,
5594 EFFECT_CMD_ENABLE,
5595 0,
5596 NULL,
5597 &size,
5598 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005599 if (status == 0) {
5600 status = cmdStatus;
5601 }
5602 return status;
5603}
5604
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005605status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005606{
5607 if (mEffectInterface == NULL) {
5608 return NO_INIT;
5609 }
5610 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005611 uint32_t size = sizeof(status_t);
5612 status_t status = (*mEffectInterface)->command(mEffectInterface,
5613 EFFECT_CMD_DISABLE,
5614 0,
5615 NULL,
5616 &size,
5617 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005618 if (status == 0) {
5619 status = cmdStatus;
5620 }
5621 return status;
5622}
5623
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005624status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5625 uint32_t cmdSize,
5626 void *pCmdData,
5627 uint32_t *replySize,
5628 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005629{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005630 Mutex::Autolock _l(mLock);
5631// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005632
5633 if (mEffectInterface == NULL) {
5634 return NO_INIT;
5635 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005636 status_t status = (*mEffectInterface)->command(mEffectInterface,
5637 cmdCode,
5638 cmdSize,
5639 pCmdData,
5640 replySize,
5641 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07005642 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005643 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005644 for (size_t i = 1; i < mHandles.size(); i++) {
5645 sp<EffectHandle> h = mHandles[i].promote();
5646 if (h != 0) {
5647 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5648 }
5649 }
5650 }
5651 return status;
5652}
5653
5654status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5655{
5656 Mutex::Autolock _l(mLock);
5657 LOGV("setEnabled %p enabled %d", this, enabled);
5658
5659 if (enabled != isEnabled()) {
5660 switch (mState) {
5661 // going from disabled to enabled
5662 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005663 mState = STARTING;
5664 break;
5665 case STOPPED:
5666 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005667 break;
5668 case STOPPING:
5669 mState = ACTIVE;
5670 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005671
5672 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005673 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005674 mState = STOPPED;
5675 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005676 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005677 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005678 break;
5679 case ACTIVE:
5680 mState = STOPPING;
5681 break;
5682 }
5683 for (size_t i = 1; i < mHandles.size(); i++) {
5684 sp<EffectHandle> h = mHandles[i].promote();
5685 if (h != 0) {
5686 h->setEnabled(enabled);
5687 }
5688 }
5689 }
5690 return NO_ERROR;
5691}
5692
5693bool AudioFlinger::EffectModule::isEnabled()
5694{
5695 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005696 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005697 case STARTING:
5698 case ACTIVE:
5699 return true;
5700 case IDLE:
5701 case STOPPING:
5702 case STOPPED:
5703 default:
5704 return false;
5705 }
5706}
5707
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005708bool AudioFlinger::EffectModule::isProcessEnabled()
5709{
5710 switch (mState) {
5711 case RESTART:
5712 case ACTIVE:
5713 case STOPPING:
5714 case STOPPED:
5715 return true;
5716 case IDLE:
5717 case STARTING:
5718 default:
5719 return false;
5720 }
5721}
5722
Eric Laurent65b65452010-06-01 23:49:17 -07005723status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5724{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005725 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005726 status_t status = NO_ERROR;
5727
5728 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5729 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005730 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07005731 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5732 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005733 status_t cmdStatus;
5734 uint32_t volume[2];
5735 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005736 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07005737 volume[0] = *left;
5738 volume[1] = *right;
5739 if (controller) {
5740 pVolume = volume;
5741 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005742 status = (*mEffectInterface)->command(mEffectInterface,
5743 EFFECT_CMD_SET_VOLUME,
5744 size,
5745 volume,
5746 &size,
5747 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07005748 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5749 *left = volume[0];
5750 *right = volume[1];
5751 }
5752 }
5753 return status;
5754}
5755
5756status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5757{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005758 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005759 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005760 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurent65b65452010-06-01 23:49:17 -07005761 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005762 uint32_t size = sizeof(status_t);
5763 status = (*mEffectInterface)->command(mEffectInterface,
5764 EFFECT_CMD_SET_DEVICE,
5765 sizeof(uint32_t),
5766 &device,
5767 &size,
5768 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005769 if (status == NO_ERROR) {
5770 status = cmdStatus;
5771 }
5772 }
5773 return status;
5774}
5775
Eric Laurent53334cd2010-06-23 17:38:20 -07005776status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5777{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005778 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005779 status_t status = NO_ERROR;
5780 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005781 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005782 uint32_t size = sizeof(status_t);
5783 status = (*mEffectInterface)->command(mEffectInterface,
5784 EFFECT_CMD_SET_AUDIO_MODE,
5785 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07005786 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005787 &size,
5788 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07005789 if (status == NO_ERROR) {
5790 status = cmdStatus;
5791 }
5792 }
5793 return status;
5794}
5795
Eric Laurent65b65452010-06-01 23:49:17 -07005796status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5797{
5798 const size_t SIZE = 256;
5799 char buffer[SIZE];
5800 String8 result;
5801
5802 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5803 result.append(buffer);
5804
5805 bool locked = tryLock(mLock);
5806 // failed to lock - AudioFlinger is probably deadlocked
5807 if (!locked) {
5808 result.append("\t\tCould not lock Fx mutex:\n");
5809 }
5810
5811 result.append("\t\tSession Status State Engine:\n");
5812 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5813 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5814 result.append(buffer);
5815
5816 result.append("\t\tDescriptor:\n");
5817 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5818 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5819 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5820 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5821 result.append(buffer);
5822 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5823 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5824 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5825 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5826 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07005827 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07005828 mDescriptor.apiVersion,
5829 mDescriptor.flags);
5830 result.append(buffer);
5831 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5832 mDescriptor.name);
5833 result.append(buffer);
5834 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5835 mDescriptor.implementor);
5836 result.append(buffer);
5837
5838 result.append("\t\t- Input configuration:\n");
5839 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5840 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5841 (uint32_t)mConfig.inputCfg.buffer.raw,
5842 mConfig.inputCfg.buffer.frameCount,
5843 mConfig.inputCfg.samplingRate,
5844 mConfig.inputCfg.channels,
5845 mConfig.inputCfg.format);
5846 result.append(buffer);
5847
5848 result.append("\t\t- Output configuration:\n");
5849 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5850 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5851 (uint32_t)mConfig.outputCfg.buffer.raw,
5852 mConfig.outputCfg.buffer.frameCount,
5853 mConfig.outputCfg.samplingRate,
5854 mConfig.outputCfg.channels,
5855 mConfig.outputCfg.format);
5856 result.append(buffer);
5857
5858 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5859 result.append(buffer);
5860 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5861 for (size_t i = 0; i < mHandles.size(); ++i) {
5862 sp<EffectHandle> handle = mHandles[i].promote();
5863 if (handle != 0) {
5864 handle->dump(buffer, SIZE);
5865 result.append(buffer);
5866 }
5867 }
5868
5869 result.append("\n");
5870
5871 write(fd, result.string(), result.length());
5872
5873 if (locked) {
5874 mLock.unlock();
5875 }
5876
5877 return NO_ERROR;
5878}
5879
5880// ----------------------------------------------------------------------------
5881// EffectHandle implementation
5882// ----------------------------------------------------------------------------
5883
5884#undef LOG_TAG
5885#define LOG_TAG "AudioFlinger::EffectHandle"
5886
5887AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5888 const sp<AudioFlinger::Client>& client,
5889 const sp<IEffectClient>& effectClient,
5890 int32_t priority)
5891 : BnEffect(),
5892 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5893{
5894 LOGV("constructor %p", this);
5895
5896 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5897 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5898 if (mCblkMemory != 0) {
5899 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5900
5901 if (mCblk) {
5902 new(mCblk) effect_param_cblk_t();
5903 mBuffer = (uint8_t *)mCblk + bufOffset;
5904 }
5905 } else {
5906 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5907 return;
5908 }
5909}
5910
5911AudioFlinger::EffectHandle::~EffectHandle()
5912{
5913 LOGV("Destructor %p", this);
5914 disconnect();
5915}
5916
5917status_t AudioFlinger::EffectHandle::enable()
5918{
5919 if (!mHasControl) return INVALID_OPERATION;
5920 if (mEffect == 0) return DEAD_OBJECT;
5921
5922 return mEffect->setEnabled(true);
5923}
5924
5925status_t AudioFlinger::EffectHandle::disable()
5926{
5927 if (!mHasControl) return INVALID_OPERATION;
5928 if (mEffect == NULL) return DEAD_OBJECT;
5929
5930 return mEffect->setEnabled(false);
5931}
5932
5933void AudioFlinger::EffectHandle::disconnect()
5934{
5935 if (mEffect == 0) {
5936 return;
5937 }
5938 mEffect->disconnect(this);
5939 // release sp on module => module destructor can be called now
5940 mEffect.clear();
5941 if (mCblk) {
5942 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5943 }
5944 mCblkMemory.clear(); // and free the shared memory
5945 if (mClient != 0) {
5946 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5947 mClient.clear();
5948 }
5949}
5950
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005951status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5952 uint32_t cmdSize,
5953 void *pCmdData,
5954 uint32_t *replySize,
5955 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005956{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005957// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5958// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005959
5960 // only get parameter command is permitted for applications not controlling the effect
5961 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5962 return INVALID_OPERATION;
5963 }
5964 if (mEffect == 0) return DEAD_OBJECT;
5965
5966 // handle commands that are not forwarded transparently to effect engine
5967 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5968 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5969 // no risk to block the whole media server process or mixer threads is we are stuck here
5970 Mutex::Autolock _l(mCblk->lock);
5971 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5972 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5973 mCblk->serverIndex = 0;
5974 mCblk->clientIndex = 0;
5975 return BAD_VALUE;
5976 }
5977 status_t status = NO_ERROR;
5978 while (mCblk->serverIndex < mCblk->clientIndex) {
5979 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005980 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07005981 int *p = (int *)(mBuffer + mCblk->serverIndex);
5982 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07005983 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5984 LOGW("command(): invalid parameter block size");
5985 break;
5986 }
Eric Laurent65b65452010-06-01 23:49:17 -07005987 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07005988 if (param->psize == 0 || param->vsize == 0) {
5989 LOGW("command(): null parameter or value size");
5990 mCblk->serverIndex += size;
5991 continue;
5992 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005993 uint32_t psize = sizeof(effect_param_t) +
5994 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
5995 param->vsize;
5996 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
5997 psize,
5998 p,
5999 &rsize,
6000 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006001 // stop at first error encountered
6002 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006003 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006004 *(int *)pReplyData = reply;
6005 break;
6006 } else if (reply != NO_ERROR) {
6007 *(int *)pReplyData = reply;
6008 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006009 }
6010 mCblk->serverIndex += size;
6011 }
6012 mCblk->serverIndex = 0;
6013 mCblk->clientIndex = 0;
6014 return status;
6015 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006016 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006017 return enable();
6018 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006019 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006020 return disable();
6021 }
6022
6023 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6024}
6025
6026sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6027 return mCblkMemory;
6028}
6029
6030void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6031{
6032 LOGV("setControl %p control %d", this, hasControl);
6033
6034 mHasControl = hasControl;
6035 if (signal && mEffectClient != 0) {
6036 mEffectClient->controlStatusChanged(hasControl);
6037 }
6038}
6039
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006040void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6041 uint32_t cmdSize,
6042 void *pCmdData,
6043 uint32_t replySize,
6044 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006045{
6046 if (mEffectClient != 0) {
6047 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6048 }
6049}
6050
6051
6052
6053void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6054{
6055 if (mEffectClient != 0) {
6056 mEffectClient->enableStatusChanged(enabled);
6057 }
6058}
6059
6060status_t AudioFlinger::EffectHandle::onTransact(
6061 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6062{
6063 return BnEffect::onTransact(code, data, reply, flags);
6064}
6065
6066
6067void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6068{
6069 bool locked = tryLock(mCblk->lock);
6070
6071 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6072 (mClient == NULL) ? getpid() : mClient->pid(),
6073 mPriority,
6074 mHasControl,
6075 !locked,
6076 mCblk->clientIndex,
6077 mCblk->serverIndex
6078 );
6079
6080 if (locked) {
6081 mCblk->lock.unlock();
6082 }
6083}
6084
6085#undef LOG_TAG
6086#define LOG_TAG "AudioFlinger::EffectChain"
6087
6088AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6089 int sessionId)
Eric Laurent90681d62011-05-09 12:09:06 -07006090 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6091 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6092 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006093{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006094 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006095}
6096
6097AudioFlinger::EffectChain::~EffectChain()
6098{
6099 if (mOwnInBuffer) {
6100 delete mInBuffer;
6101 }
6102
6103}
6104
Eric Laurent76c40f72010-07-15 12:50:15 -07006105// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6106sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006107{
6108 sp<EffectModule> effect;
6109 size_t size = mEffects.size();
6110
6111 for (size_t i = 0; i < size; i++) {
6112 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6113 effect = mEffects[i];
6114 break;
6115 }
6116 }
6117 return effect;
6118}
6119
Eric Laurent76c40f72010-07-15 12:50:15 -07006120// getEffectFromId_l() must be called with PlaybackThread::mLock held
6121sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006122{
6123 sp<EffectModule> effect;
6124 size_t size = mEffects.size();
6125
6126 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006127 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6128 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006129 effect = mEffects[i];
6130 break;
6131 }
6132 }
6133 return effect;
6134}
6135
6136// Must be called with EffectChain::mLock locked
6137void AudioFlinger::EffectChain::process_l()
6138{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006139 sp<ThreadBase> thread = mThread.promote();
6140 if (thread == 0) {
6141 LOGW("process_l(): cannot promote mixer thread");
6142 return;
6143 }
6144 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006145 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6146 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006147 bool tracksOnSession = false;
6148 if (!isGlobalSession) {
Eric Laurent90681d62011-05-09 12:09:06 -07006149 tracksOnSession = (trackCnt() != 0);
6150 }
6151
6152 // if no track is active, input buffer must be cleared here as the mixer process
6153 // will not do it
6154 if (tracksOnSession &&
6155 activeTrackCnt() == 0) {
6156 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6157 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006158 }
6159
Eric Laurent65b65452010-06-01 23:49:17 -07006160 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006161 // do not process effect if no track is present in same audio session
6162 if (isGlobalSession || tracksOnSession) {
6163 for (size_t i = 0; i < size; i++) {
6164 mEffects[i]->process();
6165 }
Eric Laurent65b65452010-06-01 23:49:17 -07006166 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006167 for (size_t i = 0; i < size; i++) {
6168 mEffects[i]->updateState();
6169 }
Eric Laurent65b65452010-06-01 23:49:17 -07006170}
6171
Eric Laurent76c40f72010-07-15 12:50:15 -07006172// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006173status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006174{
6175 effect_descriptor_t desc = effect->desc();
6176 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6177
6178 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006179 effect->setChain(this);
6180 sp<ThreadBase> thread = mThread.promote();
6181 if (thread == 0) {
6182 return NO_INIT;
6183 }
6184 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006185
6186 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6187 // Auxiliary effects are inserted at the beginning of mEffects vector as
6188 // they are processed first and accumulated in chain input buffer
6189 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006190
Eric Laurent65b65452010-06-01 23:49:17 -07006191 // the input buffer for auxiliary effect contains mono samples in
6192 // 32 bit format. This is to avoid saturation in AudoMixer
6193 // accumulation stage. Saturation is done in EffectModule::process() before
6194 // calling the process in effect engine
6195 size_t numSamples = thread->frameCount();
6196 int32_t *buffer = new int32_t[numSamples];
6197 memset(buffer, 0, numSamples * sizeof(int32_t));
6198 effect->setInBuffer((int16_t *)buffer);
6199 // auxiliary effects output samples to chain input buffer for further processing
6200 // by insert effects
6201 effect->setOutBuffer(mInBuffer);
6202 } else {
6203 // Insert effects are inserted at the end of mEffects vector as they are processed
6204 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006205 // Insert effect order as a function of indicated preference:
6206 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6207 // another effect is present
6208 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6209 // last effect claiming first position
6210 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6211 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006212 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006213 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6214 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006215
6216 int size = (int)mEffects.size();
6217 int idx_insert = size;
6218 int idx_insert_first = -1;
6219 int idx_insert_last = -1;
6220
6221 for (int i = 0; i < size; i++) {
6222 effect_descriptor_t d = mEffects[i]->desc();
6223 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6224 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6225 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6226 // check invalid effect chaining combinations
6227 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006228 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006229 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006230 return INVALID_OPERATION;
6231 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006232 // remember position of first insert effect and by default
6233 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006234 if (idx_insert == size) {
6235 idx_insert = i;
6236 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006237 // remember position of last insert effect claiming
6238 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006239 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6240 idx_insert_first = i;
6241 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006242 // remember position of first insert effect claiming
6243 // last position
6244 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6245 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006246 idx_insert_last = i;
6247 }
6248 }
6249 }
6250
Eric Laurent53334cd2010-06-23 17:38:20 -07006251 // modify idx_insert from first position if needed
6252 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6253 if (idx_insert_last != -1) {
6254 idx_insert = idx_insert_last;
6255 } else {
6256 idx_insert = size;
6257 }
6258 } else {
6259 if (idx_insert_first != -1) {
6260 idx_insert = idx_insert_first + 1;
6261 }
Eric Laurent65b65452010-06-01 23:49:17 -07006262 }
6263
6264 // always read samples from chain input buffer
6265 effect->setInBuffer(mInBuffer);
6266
6267 // if last effect in the chain, output samples to chain
6268 // output buffer, otherwise to chain input buffer
6269 if (idx_insert == size) {
6270 if (idx_insert != 0) {
6271 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6272 mEffects[idx_insert-1]->configure();
6273 }
6274 effect->setOutBuffer(mOutBuffer);
6275 } else {
6276 effect->setOutBuffer(mInBuffer);
6277 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006278 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006279
Eric Laurent76c40f72010-07-15 12:50:15 -07006280 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006281 }
6282 effect->configure();
6283 return NO_ERROR;
6284}
6285
Eric Laurent76c40f72010-07-15 12:50:15 -07006286// removeEffect_l() must be called with PlaybackThread::mLock held
6287size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006288{
6289 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006290 int size = (int)mEffects.size();
6291 int i;
6292 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6293
6294 for (i = 0; i < size; i++) {
6295 if (effect == mEffects[i]) {
6296 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6297 delete[] effect->inBuffer();
6298 } else {
6299 if (i == size - 1 && i != 0) {
6300 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6301 mEffects[i - 1]->configure();
6302 }
6303 }
6304 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006305 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006306 break;
6307 }
6308 }
Eric Laurent65b65452010-06-01 23:49:17 -07006309
6310 return mEffects.size();
6311}
6312
Eric Laurent76c40f72010-07-15 12:50:15 -07006313// setDevice_l() must be called with PlaybackThread::mLock held
6314void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006315{
6316 size_t size = mEffects.size();
6317 for (size_t i = 0; i < size; i++) {
6318 mEffects[i]->setDevice(device);
6319 }
6320}
6321
Eric Laurent76c40f72010-07-15 12:50:15 -07006322// setMode_l() must be called with PlaybackThread::mLock held
6323void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006324{
6325 size_t size = mEffects.size();
6326 for (size_t i = 0; i < size; i++) {
6327 mEffects[i]->setMode(mode);
6328 }
6329}
6330
Eric Laurent76c40f72010-07-15 12:50:15 -07006331// setVolume_l() must be called with PlaybackThread::mLock held
6332bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006333{
6334 uint32_t newLeft = *left;
6335 uint32_t newRight = *right;
6336 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006337 int ctrlIdx = -1;
6338 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006339
Eric Laurent76c40f72010-07-15 12:50:15 -07006340 // first update volume controller
6341 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006342 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006343 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6344 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006345 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006346 break;
6347 }
6348 }
6349
6350 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006351 if (hasControl) {
6352 *left = mNewLeftVolume;
6353 *right = mNewRightVolume;
6354 }
6355 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006356 }
6357
6358 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006359 mLeftVolume = newLeft;
6360 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006361
6362 // second get volume update from volume controller
6363 if (ctrlIdx >= 0) {
6364 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006365 mNewLeftVolume = newLeft;
6366 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006367 }
6368 // then indicate volume to all other effects in chain.
6369 // Pass altered volume to effects before volume controller
6370 // and requested volume to effects after controller
6371 uint32_t lVol = newLeft;
6372 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006373
Eric Laurent65b65452010-06-01 23:49:17 -07006374 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006375 if ((int)i == ctrlIdx) continue;
6376 // this also works for ctrlIdx == -1 when there is no volume controller
6377 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006378 lVol = *left;
6379 rVol = *right;
6380 }
6381 mEffects[i]->setVolume(&lVol, &rVol, false);
6382 }
6383 *left = newLeft;
6384 *right = newRight;
6385
6386 return hasControl;
6387}
6388
Eric Laurent65b65452010-06-01 23:49:17 -07006389status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6390{
6391 const size_t SIZE = 256;
6392 char buffer[SIZE];
6393 String8 result;
6394
6395 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6396 result.append(buffer);
6397
6398 bool locked = tryLock(mLock);
6399 // failed to lock - AudioFlinger is probably deadlocked
6400 if (!locked) {
6401 result.append("\tCould not lock mutex:\n");
6402 }
6403
Eric Laurent76c40f72010-07-15 12:50:15 -07006404 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6405 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006406 mEffects.size(),
6407 (uint32_t)mInBuffer,
6408 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006409 mActiveTrackCnt);
6410 result.append(buffer);
6411 write(fd, result.string(), result.size());
6412
6413 for (size_t i = 0; i < mEffects.size(); ++i) {
6414 sp<EffectModule> effect = mEffects[i];
6415 if (effect != 0) {
6416 effect->dump(fd, args);
6417 }
6418 }
6419
6420 if (locked) {
6421 mLock.unlock();
6422 }
6423
6424 return NO_ERROR;
6425}
6426
6427#undef LOG_TAG
6428#define LOG_TAG "AudioFlinger"
6429
Eric Laurenta553c252009-07-17 12:17:14 -07006430// ----------------------------------------------------------------------------
6431
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006432status_t AudioFlinger::onTransact(
6433 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6434{
6435 return BnAudioFlinger::onTransact(code, data, reply, flags);
6436}
6437
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006438}; // namespace android