blob: ab49f93bf124cb22efc1cf9b9e833cfebab3ac29 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9b3f1522011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070028#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurentae29b762011-03-28 18:37:07 -070034#include <utils/Atomic.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035
Dima Zavin24fc2fb2011-04-19 22:30:36 -070036#include <cutils/bitops.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080037#include <cutils/properties.h>
38
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070044#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
Dima Zavin34bb4192011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070047#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Eric Laurent53334cd2010-06-23 17:38:20 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
Glenn Kastenda494f92011-07-08 15:26:12 -070057#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070059// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
60
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
Eric Laurent8ed6ed02010-07-13 04:45:46 -070063
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070064namespace android {
65
The Android Open Source Project10592532009-03-18 17:39:46 -070066static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
67static const char* kHardwareLockedString = "Hardware lock is taken\n";
68
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080069//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070071static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072
73// retry counts for buffer fill timeout
74// 50 * ~20msecs = 1 second
75static const int8_t kMaxTrackRetries = 50;
76static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080077// allow less retry attempts on direct output thread.
78// direct outputs can be a scarce resource in audio hardware and should
79// be released as quickly as possible.
80static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070081
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070082static const int kDumpLockRetries = 50;
83static const int kDumpLockSleep = 20000;
84
Dave Sparksd0ac8c02009-09-30 03:09:03 -070085static const nsecs_t kWarningThrottle = seconds(5);
86
Eric Laurent464d5b32011-06-17 21:29:58 -070087// RecordThread loop sleep time upon application overrun or audio HAL read error
88static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Eric Laurent5f37be32011-09-13 11:40:21 -070090static const nsecs_t kSetParametersTimeout = seconds(2);
91
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070092// ----------------------------------------------------------------------------
93
94static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070095 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
96 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
97 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
98 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070099}
100
101static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
103 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
104 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
105 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106}
107
Gloria Wang9b3f1522011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
110 sp<IBinder> binder =
111 defaultServiceManager()->getService(String16("media.player"));
112 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
113 if (service.get() == NULL) {
114 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
115 return;
116 }
117
118 service->addBatteryData(params);
119}
120
Dima Zavin31f188892011-04-18 16:57:27 -0700121static int load_audio_interface(const char *if_name, const hw_module_t **mod,
122 audio_hw_device_t **dev)
123{
124 int rc;
125
126 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
127 if (rc)
128 goto out;
129
130 rc = audio_hw_device_open(*mod, dev);
131 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
132 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
133 if (rc)
134 goto out;
135
136 return 0;
137
138out:
139 *mod = NULL;
140 *dev = NULL;
141 return rc;
142}
143
144static const char *audio_interfaces[] = {
145 "primary",
146 "a2dp",
147 "usb",
148};
149#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
150
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700151// ----------------------------------------------------------------------------
152
153AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 : BnAudioFlinger(),
Eric Laurent6639b552011-08-01 09:52:20 -0700155 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700156 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700157{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700158}
159
160void AudioFlinger::onFirstRef()
161{
Dima Zavin31f188892011-04-18 16:57:27 -0700162 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700163
Eric Laurent01635942011-01-18 18:39:02 -0800164 Mutex::Autolock _l(mLock);
165
Dima Zavin31f188892011-04-18 16:57:27 -0700166 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700168
Dima Zavin31f188892011-04-18 16:57:27 -0700169 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
170 const hw_module_t *mod;
171 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700172
Dima Zavin31f188892011-04-18 16:57:27 -0700173 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
174 if (rc)
175 continue;
176
177 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
178 mod->name, mod->id);
179 mAudioHwDevs.push(dev);
180
181 if (!mPrimaryHardwareDev) {
182 mPrimaryHardwareDev = dev;
183 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700184 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700185 }
186 }
Eric Laurenta553c252009-07-17 12:17:14 -0700187
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700188 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700189
Dima Zavin31f188892011-04-18 16:57:27 -0700190 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
191 LOGE("Primary audio interface not found");
192 return;
193 }
194
195 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
196 audio_hw_device_t *dev = mAudioHwDevs[i];
197
198 mHardwareStatus = AUDIO_HW_INIT;
199 rc = dev->init_check(dev);
200 if (rc == 0) {
201 AutoMutex lock(mHardwareLock);
202
203 mMode = AUDIO_MODE_NORMAL;
204 mHardwareStatus = AUDIO_HW_SET_MODE;
205 dev->set_mode(dev, mMode);
206 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
207 dev->set_master_volume(dev, 1.0f);
208 mHardwareStatus = AUDIO_HW_IDLE;
209 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700210 }
211}
212
Dima Zavin2986f5b2011-04-19 19:04:32 -0700213status_t AudioFlinger::initCheck() const
214{
215 Mutex::Autolock _l(mLock);
216 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
217 return NO_INIT;
218 return NO_ERROR;
219}
220
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700221AudioFlinger::~AudioFlinger()
222{
Dima Zavin31f188892011-04-18 16:57:27 -0700223 int num_devs = mAudioHwDevs.size();
224
Eric Laurent7954c462009-08-28 10:39:03 -0700225 while (!mRecordThreads.isEmpty()) {
226 // closeInput() will remove first entry from mRecordThreads
227 closeInput(mRecordThreads.keyAt(0));
228 }
229 while (!mPlaybackThreads.isEmpty()) {
230 // closeOutput() will remove first entry from mPlaybackThreads
231 closeOutput(mPlaybackThreads.keyAt(0));
232 }
Dima Zavin31f188892011-04-18 16:57:27 -0700233
234 for (int i = 0; i < num_devs; i++) {
235 audio_hw_device_t *dev = mAudioHwDevs[i];
236 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700237 }
Dima Zavin31f188892011-04-18 16:57:27 -0700238 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800239}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800240
Dima Zavin31f188892011-04-18 16:57:27 -0700241audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
242{
243 /* first matching HW device is returned */
244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 if ((dev->get_supported_devices(dev) & devices) == devices)
247 return dev;
248 }
249 return NULL;
250}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700251
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700252status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
253{
254 const size_t SIZE = 256;
255 char buffer[SIZE];
256 String8 result;
257
258 result.append("Clients:\n");
259 for (size_t i = 0; i < mClients.size(); ++i) {
260 wp<Client> wClient = mClients.valueAt(i);
261 if (wClient != 0) {
262 sp<Client> client = wClient.promote();
263 if (client != 0) {
264 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
265 result.append(buffer);
266 }
267 }
268 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700269
270 result.append("Global session refs:\n");
271 result.append(" session pid cnt\n");
272 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
273 AudioSessionRef *r = mAudioSessionRefs[i];
274 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
275 result.append(buffer);
276 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700277 write(fd, result.string(), result.size());
278 return NO_ERROR;
279}
280
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281
282status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700287 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700288
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700289 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700290 result.append(buffer);
291 write(fd, result.string(), result.size());
292 return NO_ERROR;
293}
294
295status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
296{
297 const size_t SIZE = 256;
298 char buffer[SIZE];
299 String8 result;
300 snprintf(buffer, SIZE, "Permission Denial: "
301 "can't dump AudioFlinger from pid=%d, uid=%d\n",
302 IPCThreadState::self()->getCallingPid(),
303 IPCThreadState::self()->getCallingUid());
304 result.append(buffer);
305 write(fd, result.string(), result.size());
306 return NO_ERROR;
307}
308
The Android Open Source Project10592532009-03-18 17:39:46 -0700309static bool tryLock(Mutex& mutex)
310{
311 bool locked = false;
312 for (int i = 0; i < kDumpLockRetries; ++i) {
313 if (mutex.tryLock() == NO_ERROR) {
314 locked = true;
315 break;
316 }
317 usleep(kDumpLockSleep);
318 }
319 return locked;
320}
321
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700322status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
323{
324 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
325 dumpPermissionDenial(fd, args);
326 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700327 // get state of hardware lock
328 bool hardwareLocked = tryLock(mHardwareLock);
329 if (!hardwareLocked) {
330 String8 result(kHardwareLockedString);
331 write(fd, result.string(), result.size());
332 } else {
333 mHardwareLock.unlock();
334 }
335
336 bool locked = tryLock(mLock);
337
338 // failed to lock - AudioFlinger is probably deadlocked
339 if (!locked) {
340 String8 result(kDeadlockedString);
341 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700342 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700343
344 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700345 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346
Eric Laurenta553c252009-07-17 12:17:14 -0700347 // dump playback threads
348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700349 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700350 }
351
352 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700353 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700354 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
Dima Zavin31f188892011-04-18 16:57:27 -0700357 // dump all hardware devs
358 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
359 audio_hw_device_t *dev = mAudioHwDevs[i];
360 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700361 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700362 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700363 }
364 return NO_ERROR;
365}
366
Eric Laurenta553c252009-07-17 12:17:14 -0700367
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369
370
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371sp<IAudioTrack> AudioFlinger::createTrack(
372 pid_t pid,
373 int streamType,
374 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700375 uint32_t format,
376 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800377 int frameCount,
378 uint32_t flags,
379 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700380 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700381 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800382 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700383{
Eric Laurenta553c252009-07-17 12:17:14 -0700384 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700385 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700386 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800387 wp<Client> wclient;
388 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700389 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700390
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700391 if (streamType >= AUDIO_STREAM_CNT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800392 LOGE("invalid stream type");
393 lStatus = BAD_VALUE;
394 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 }
396
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800397 {
398 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700399 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700400 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700401 if (thread == NULL) {
402 LOGE("unknown output thread");
403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800406
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800407 wclient = mClients.valueFor(pid);
408
409 if (wclient != NULL) {
410 client = wclient.promote();
411 } else {
412 client = new Client(this, pid);
413 mClients.add(pid, client);
414 }
Eric Laurent65b65452010-06-01 23:49:17 -0700415
Eric Laurent65b65452010-06-01 23:49:17 -0700416 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700417 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700418 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700419 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
420 if (mPlaybackThreads.keyAt(i) != output) {
421 // prevent same audio session on different output threads
422 uint32_t sessions = t->hasAudioSession(*sessionId);
423 if (sessions & PlaybackThread::TRACK_SESSION) {
424 lStatus = BAD_VALUE;
425 goto Exit;
426 }
427 // check if an effect with same session ID is waiting for a track to be created
428 if (sessions & PlaybackThread::EFFECT_SESSION) {
429 effectThread = t.get();
430 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700431 }
432 }
Eric Laurent65b65452010-06-01 23:49:17 -0700433 lSessionId = *sessionId;
434 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700435 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700436 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700437 if (sessionId != NULL) {
438 *sessionId = lSessionId;
439 }
440 }
441 LOGV("createTrack() lSessionId: %d", lSessionId);
442
Eric Laurenta553c252009-07-17 12:17:14 -0700443 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700444 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700445
446 // move effect chain to this output thread if an effect on same session was waiting
447 // for a track to be created
448 if (lStatus == NO_ERROR && effectThread != NULL) {
449 Mutex::Autolock _dl(thread->mLock);
450 Mutex::Autolock _sl(effectThread->mLock);
451 moveEffectChain_l(lSessionId, effectThread, thread, true);
452 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700453 }
454 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800455 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700456 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700457 // remove local strong reference to Client before deleting the Track so that the Client
458 // destructor is called by the TrackBase destructor with mLock held
459 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700460 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800461 }
462
463Exit:
464 if(status) {
465 *status = lStatus;
466 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700467 return trackHandle;
468}
469
Eric Laurentddb78e72009-07-28 08:44:33 -0700470uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700471{
Eric Laurenta553c252009-07-17 12:17:14 -0700472 Mutex::Autolock _l(mLock);
473 PlaybackThread *thread = checkPlaybackThread_l(output);
474 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700475 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700476 return 0;
477 }
478 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479}
480
Eric Laurentddb78e72009-07-28 08:44:33 -0700481int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482{
Eric Laurenta553c252009-07-17 12:17:14 -0700483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700486 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700487 return 0;
488 }
489 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490}
491
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700492uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700493{
Eric Laurenta553c252009-07-17 12:17:14 -0700494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700497 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700498 return 0;
499 }
500 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501}
502
Eric Laurentddb78e72009-07-28 08:44:33 -0700503size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700504{
Eric Laurenta553c252009-07-17 12:17:14 -0700505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700508 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700509 return 0;
510 }
511 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512}
513
Eric Laurentddb78e72009-07-28 08:44:33 -0700514uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800515{
Eric Laurenta553c252009-07-17 12:17:14 -0700516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700519 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700520 return 0;
521 }
522 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800523}
524
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700525status_t AudioFlinger::setMasterVolume(float value)
526{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700527 status_t ret = initCheck();
528 if (ret != NO_ERROR) {
529 return ret;
530 }
531
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700532 // check calling permissions
533 if (!settingsAllowed()) {
534 return PERMISSION_DENIED;
535 }
536
537 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800538 { // scope for the lock
539 AutoMutex lock(mHardwareLock);
540 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700541 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800542 value = 1.0f;
543 }
544 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700545 }
Eric Laurenta553c252009-07-17 12:17:14 -0700546
Eric Laurent01635942011-01-18 18:39:02 -0800547 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700548 mMasterVolume = value;
549 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700550 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700551
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552 return NO_ERROR;
553}
554
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555status_t AudioFlinger::setMode(int mode)
556{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700557 status_t ret = initCheck();
558 if (ret != NO_ERROR) {
559 return ret;
560 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700561
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700562 // check calling permissions
563 if (!settingsAllowed()) {
564 return PERMISSION_DENIED;
565 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700566 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700567 LOGW("Illegal value: setMode(%d)", mode);
568 return BAD_VALUE;
569 }
570
Eric Laurent53334cd2010-06-23 17:38:20 -0700571 { // scope for the lock
572 AutoMutex lock(mHardwareLock);
573 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700574 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700575 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800576 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700577
578 if (NO_ERROR == ret) {
579 Mutex::Autolock _l(mLock);
580 mMode = mode;
581 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
582 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700583 }
584
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700585 return ret;
586}
587
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700588status_t AudioFlinger::setMicMute(bool state)
589{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700590 status_t ret = initCheck();
591 if (ret != NO_ERROR) {
592 return ret;
593 }
594
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700595 // check calling permissions
596 if (!settingsAllowed()) {
597 return PERMISSION_DENIED;
598 }
599
600 AutoMutex lock(mHardwareLock);
601 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700602 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700603 mHardwareStatus = AUDIO_HW_IDLE;
604 return ret;
605}
606
607bool AudioFlinger::getMicMute() const
608{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700609 status_t ret = initCheck();
610 if (ret != NO_ERROR) {
611 return false;
612 }
613
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700614 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700615 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700616 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700617 mHardwareStatus = AUDIO_HW_IDLE;
618 return state;
619}
620
621status_t AudioFlinger::setMasterMute(bool muted)
622{
623 // check calling permissions
624 if (!settingsAllowed()) {
625 return PERMISSION_DENIED;
626 }
Eric Laurenta553c252009-07-17 12:17:14 -0700627
Eric Laurent01635942011-01-18 18:39:02 -0800628 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700629 mMasterMute = muted;
630 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700631 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700632
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700633 return NO_ERROR;
634}
635
636float AudioFlinger::masterVolume() const
637{
Eric Laurenta553c252009-07-17 12:17:14 -0700638 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700639}
640
641bool AudioFlinger::masterMute() const
642{
Eric Laurenta553c252009-07-17 12:17:14 -0700643 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700644}
645
Eric Laurentddb78e72009-07-28 08:44:33 -0700646status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700647{
648 // check calling permissions
649 if (!settingsAllowed()) {
650 return PERMISSION_DENIED;
651 }
652
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700653 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700654 return BAD_VALUE;
655 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800656
Eric Laurenta553c252009-07-17 12:17:14 -0700657 AutoMutex lock(mLock);
658 PlaybackThread *thread = NULL;
659 if (output) {
660 thread = checkPlaybackThread_l(output);
661 if (thread == NULL) {
662 return BAD_VALUE;
663 }
664 }
665
Eric Laurenta553c252009-07-17 12:17:14 -0700666 mStreamTypes[stream].volume = value;
667
668 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700669 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700670 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700671 }
Eric Laurenta553c252009-07-17 12:17:14 -0700672 } else {
673 thread->setStreamVolume(stream, value);
674 }
Eric Laurentef028272009-04-21 07:56:33 -0700675
Eric Laurent415f3e22009-10-21 08:14:22 -0700676 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700677}
678
679status_t AudioFlinger::setStreamMute(int stream, bool muted)
680{
681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700686 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
687 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700688 return BAD_VALUE;
689 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700690
Eric Laurent01635942011-01-18 18:39:02 -0800691 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700692 mStreamTypes[stream].mute = muted;
693 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700694 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700696 return NO_ERROR;
697}
698
Eric Laurentddb78e72009-07-28 08:44:33 -0700699float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700700{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700701 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700702 return 0.0f;
703 }
Eric Laurenta553c252009-07-17 12:17:14 -0700704
705 AutoMutex lock(mLock);
706 float volume;
707 if (output) {
708 PlaybackThread *thread = checkPlaybackThread_l(output);
709 if (thread == NULL) {
710 return 0.0f;
711 }
712 volume = thread->streamVolume(stream);
713 } else {
714 volume = mStreamTypes[stream].volume;
715 }
716
Eric Laurentef028272009-04-21 07:56:33 -0700717 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700718}
719
720bool AudioFlinger::streamMute(int stream) const
721{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700722 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700723 return true;
724 }
Eric Laurenta553c252009-07-17 12:17:14 -0700725
726 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700727}
728
Eric Laurentddb78e72009-07-28 08:44:33 -0700729status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700730{
Eric Laurenta553c252009-07-17 12:17:14 -0700731 status_t result;
732
Eric Laurentddb78e72009-07-28 08:44:33 -0700733 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700734 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
735 // check calling permissions
736 if (!settingsAllowed()) {
737 return PERMISSION_DENIED;
The Android Open Source Project9266c5582009-01-15 16:12:10 -0800738 }
Eric Laurenta553c252009-07-17 12:17:14 -0700739
740 // ioHandle == 0 means the parameters are global to the audio hardware interface
741 if (ioHandle == 0) {
742 AutoMutex lock(mHardwareLock);
743 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700744 status_t final_result = NO_ERROR;
745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
746 audio_hw_device_t *dev = mAudioHwDevs[i];
747 result = dev->set_parameters(dev, keyValuePairs.string());
748 final_result = result ?: final_result;
749 }
Eric Laurenta553c252009-07-17 12:17:14 -0700750 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700751 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
752 AudioParameter param = AudioParameter(keyValuePairs);
753 String8 value;
754 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
755 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700756 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
757 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700758 for (size_t i = 0; i < mRecordThreads.size(); i++) {
759 sp<RecordThread> thread = mRecordThreads.valueAt(i);
760 RecordThread::RecordTrack *track = thread->track();
761 if (track != NULL) {
762 audio_devices_t device = (audio_devices_t)(
763 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700764 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700765 thread->setEffectSuspended(FX_IID_AEC,
766 suspend,
767 track->sessionId());
768 thread->setEffectSuspended(FX_IID_NS,
769 suspend,
770 track->sessionId());
771 }
772 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700773 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700774 }
775 }
Dima Zavin31f188892011-04-18 16:57:27 -0700776 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700777 }
778
Eric Laurentb7d94602009-09-29 11:12:57 -0700779 // hold a strong ref on thread in case closeOutput() or closeInput() is called
780 // and the thread is exited once the lock is released
781 sp<ThreadBase> thread;
782 {
783 Mutex::Autolock _l(mLock);
784 thread = checkPlaybackThread_l(ioHandle);
785 if (thread == NULL) {
786 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700787 } else if (thread.get() == primaryPlaybackThread_l()) {
788 // indicate output device change to all input threads for pre processing
789 AudioParameter param = AudioParameter(keyValuePairs);
790 int value;
791 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
792 for (size_t i = 0; i < mRecordThreads.size(); i++) {
793 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
794 }
795 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700796 }
Eric Laurenta553c252009-07-17 12:17:14 -0700797 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700798 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800799 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800800 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700801 }
Eric Laurenta553c252009-07-17 12:17:14 -0700802 return BAD_VALUE;
803}
804
Eric Laurentddb78e72009-07-28 08:44:33 -0700805String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700806{
Eric Laurentddb78e72009-07-28 08:44:33 -0700807// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700808// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
809
810 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700811 String8 out_s8;
812
Dima Zavin31f188892011-04-18 16:57:27 -0700813 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
814 audio_hw_device_t *dev = mAudioHwDevs[i];
815 char *s = dev->get_parameters(dev, keys.string());
816 out_s8 += String8(s);
817 free(s);
818 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700819 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700820 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700821
822 Mutex::Autolock _l(mLock);
823
Eric Laurenta553c252009-07-17 12:17:14 -0700824 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
825 if (playbackThread != NULL) {
826 return playbackThread->getParameters(keys);
827 }
828 RecordThread *recordThread = checkRecordThread_l(ioHandle);
829 if (recordThread != NULL) {
830 return recordThread->getParameters(keys);
831 }
832 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700833}
834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
836{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700837 status_t ret = initCheck();
838 if (ret != NO_ERROR) {
839 return 0;
840 }
841
Dima Zavin31f188892011-04-18 16:57:27 -0700842 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843}
844
Eric Laurent47d0a922010-02-26 02:47:27 -0800845unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
846{
847 if (ioHandle == 0) {
848 return 0;
849 }
850
851 Mutex::Autolock _l(mLock);
852
853 RecordThread *recordThread = checkRecordThread_l(ioHandle);
854 if (recordThread != NULL) {
855 return recordThread->getInputFramesLost();
856 }
857 return 0;
858}
859
Eric Laurent415f3e22009-10-21 08:14:22 -0700860status_t AudioFlinger::setVoiceVolume(float value)
861{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700862 status_t ret = initCheck();
863 if (ret != NO_ERROR) {
864 return ret;
865 }
866
Eric Laurent415f3e22009-10-21 08:14:22 -0700867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
872 AutoMutex lock(mHardwareLock);
873 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700874 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700875 mHardwareStatus = AUDIO_HW_IDLE;
876
877 return ret;
878}
879
Eric Laurent0986e792010-01-19 17:37:09 -0800880status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
881{
882 status_t status;
883
884 Mutex::Autolock _l(mLock);
885
886 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
887 if (playbackThread != NULL) {
888 return playbackThread->getRenderPosition(halFrames, dspFrames);
889 }
890
891 return BAD_VALUE;
892}
893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
895{
Eric Laurenta553c252009-07-17 12:17:14 -0700896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 Mutex::Autolock _l(mLock);
898
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700899 int pid = IPCThreadState::self()->getCallingPid();
900 if (mNotificationClients.indexOfKey(pid) < 0) {
901 sp<NotificationClient> notificationClient = new NotificationClient(this,
902 client,
903 pid);
904 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700905
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700906 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700907
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700908 sp<IBinder> binder = client->asBinder();
909 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700911 // the config change is always sent from playback or record threads to avoid deadlock
912 // with AudioSystem::gLock
913 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
914 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
915 }
Eric Laurenta553c252009-07-17 12:17:14 -0700916
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700917 for (size_t i = 0; i < mRecordThreads.size(); i++) {
918 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
920 }
921}
922
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700923void AudioFlinger::removeNotificationClient(pid_t pid)
924{
925 Mutex::Autolock _l(mLock);
926
927 int index = mNotificationClients.indexOfKey(pid);
928 if (index >= 0) {
929 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
930 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700931 mNotificationClients.removeItem(pid);
932 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700933
934 LOGV("%d died, releasing its sessions", pid);
935 int num = mAudioSessionRefs.size();
936 bool removed = false;
937 for (int i = 0; i< num; i++) {
938 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
939 LOGV(" pid %d @ %d", ref->pid, i);
940 if (ref->pid == pid) {
941 LOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
942 mAudioSessionRefs.removeAt(i);
943 delete ref;
944 removed = true;
945 i--;
946 num--;
947 }
948 }
949 if (removed) {
950 purgeStaleEffects_l();
951 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700952}
953
Eric Laurent296a0ec2009-09-15 07:10:12 -0700954// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700955void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
956{
Eric Laurent49f02be2009-11-19 09:00:56 -0800957 size_t size = mNotificationClients.size();
958 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700959 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700960 }
961}
962
Eric Laurentb9481d82009-09-17 05:12:56 -0700963// removeClient_l() must be called with AudioFlinger::mLock held
964void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965{
Eric Laurentb9481d82009-09-17 05:12:56 -0700966 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 -0700967 mClients.removeItem(pid);
968}
969
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700970
Eric Laurenta553c252009-07-17 12:17:14 -0700971// ----------------------------------------------------------------------------
972
Eric Laurent464d5b32011-06-17 21:29:58 -0700973AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700974 : Thread(false),
975 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700976 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
977 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700978{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700979 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980}
981
Eric Laurenta553c252009-07-17 12:17:14 -0700982AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700984 mParamCond.broadcast();
985 mNewParameters.clear();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700986 // do not lock the mutex in destructor
987 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -0700988 if (mPowerManager != 0) {
989 sp<IBinder> binder = mPowerManager->asBinder();
990 binder->unlinkToDeath(mDeathRecipient);
991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992}
993
Eric Laurenta553c252009-07-17 12:17:14 -0700994void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700995{
Eric Laurentb7d94602009-09-29 11:12:57 -0700996 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700997 // destroyed in the middle of requestExitAndWait()
998 sp <ThreadBase> strongMe = this;
999
1000 LOGV("ThreadBase::exit");
1001 {
1002 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001003 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001004 requestExit();
1005 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001006 }
Eric Laurenta553c252009-07-17 12:17:14 -07001007 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001008}
Eric Laurenta553c252009-07-17 12:17:14 -07001009
1010uint32_t AudioFlinger::ThreadBase::sampleRate() const
1011{
1012 return mSampleRate;
1013}
1014
1015int AudioFlinger::ThreadBase::channelCount() const
1016{
Eric Laurentb0a01472010-05-14 05:45:46 -07001017 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001018}
1019
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001020uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001021{
1022 return mFormat;
1023}
1024
1025size_t AudioFlinger::ThreadBase::frameCount() const
1026{
1027 return mFrameCount;
1028}
1029
1030status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1031{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001032 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001033
Eric Laurent8fce46a2009-08-04 09:45:33 -07001034 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001035 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001036
Eric Laurent8fce46a2009-08-04 09:45:33 -07001037 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001038 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001039 // wait condition with timeout in case the thread loop has exited
1040 // before the request could be processed
Eric Laurent5f37be32011-09-13 11:40:21 -07001041 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001042 status = mParamStatus;
1043 mWaitWorkCV.signal();
1044 } else {
1045 status = TIMED_OUT;
1046 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001047 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001048}
1049
1050void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1051{
1052 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001053 sendConfigEvent_l(event, param);
1054}
1055
1056// sendConfigEvent_l() must be called with ThreadBase::mLock held
1057void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1058{
Eric Laurenta553c252009-07-17 12:17:14 -07001059 ConfigEvent *configEvent = new ConfigEvent();
1060 configEvent->mEvent = event;
1061 configEvent->mParam = param;
1062 mConfigEvents.add(configEvent);
1063 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1064 mWaitWorkCV.signal();
1065}
1066
1067void AudioFlinger::ThreadBase::processConfigEvents()
1068{
1069 mLock.lock();
1070 while(!mConfigEvents.isEmpty()) {
1071 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1072 ConfigEvent *configEvent = mConfigEvents[0];
1073 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001074 // release mLock before locking AudioFlinger mLock: lock order is always
1075 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001076 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001077 mAudioFlinger->mLock.lock();
1078 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1079 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001080 delete configEvent;
1081 mLock.lock();
1082 }
1083 mLock.unlock();
1084}
1085
Eric Laurent3fdb1262009-11-07 00:01:32 -08001086status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1087{
1088 const size_t SIZE = 256;
1089 char buffer[SIZE];
1090 String8 result;
1091
1092 bool locked = tryLock(mLock);
1093 if (!locked) {
1094 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1095 write(fd, buffer, strlen(buffer));
1096 }
1097
1098 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1103 result.append(buffer);
1104 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1105 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001106 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1107 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001108 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1111 result.append(buffer);
1112
1113 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1114 result.append(buffer);
1115 result.append(" Index Command");
1116 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1117 snprintf(buffer, SIZE, "\n %02d ", i);
1118 result.append(buffer);
1119 result.append(mNewParameters[i]);
1120 }
1121
1122 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1123 result.append(buffer);
1124 snprintf(buffer, SIZE, " Index event param\n");
1125 result.append(buffer);
1126 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1127 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1128 result.append(buffer);
1129 }
1130 result.append("\n");
1131
1132 write(fd, result.string(), result.size());
1133
1134 if (locked) {
1135 mLock.unlock();
1136 }
1137 return NO_ERROR;
1138}
1139
Eric Laurent1345d332011-07-24 17:49:51 -07001140status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1141{
1142 const size_t SIZE = 256;
1143 char buffer[SIZE];
1144 String8 result;
1145
1146 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1147 write(fd, buffer, strlen(buffer));
1148
1149 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1150 sp<EffectChain> chain = mEffectChains[i];
1151 if (chain != 0) {
1152 chain->dump(fd, args);
1153 }
1154 }
1155 return NO_ERROR;
1156}
1157
Eric Laurent6dbdc402011-07-22 09:04:31 -07001158void AudioFlinger::ThreadBase::acquireWakeLock()
1159{
1160 Mutex::Autolock _l(mLock);
1161 acquireWakeLock_l();
1162}
1163
1164void AudioFlinger::ThreadBase::acquireWakeLock_l()
1165{
1166 if (mPowerManager == 0) {
1167 // use checkService() to avoid blocking if power service is not up yet
1168 sp<IBinder> binder =
1169 defaultServiceManager()->checkService(String16("power"));
1170 if (binder == 0) {
1171 LOGW("Thread %s cannot connect to the power manager service", mName);
1172 } else {
1173 mPowerManager = interface_cast<IPowerManager>(binder);
1174 binder->linkToDeath(mDeathRecipient);
1175 }
1176 }
1177 if (mPowerManager != 0) {
1178 sp<IBinder> binder = new BBinder();
1179 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1180 binder,
1181 String16(mName));
1182 if (status == NO_ERROR) {
1183 mWakeLockToken = binder;
1184 }
1185 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1186 }
1187}
1188
1189void AudioFlinger::ThreadBase::releaseWakeLock()
1190{
1191 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001192 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001193}
1194
1195void AudioFlinger::ThreadBase::releaseWakeLock_l()
1196{
1197 if (mWakeLockToken != 0) {
1198 LOGV("releaseWakeLock_l() %s", mName);
1199 if (mPowerManager != 0) {
1200 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1201 }
1202 mWakeLockToken.clear();
1203 }
1204}
1205
1206void AudioFlinger::ThreadBase::clearPowerManager()
1207{
1208 Mutex::Autolock _l(mLock);
1209 releaseWakeLock_l();
1210 mPowerManager.clear();
1211}
1212
1213void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1214{
1215 sp<ThreadBase> thread = mThread.promote();
1216 if (thread != 0) {
1217 thread->clearPowerManager();
1218 }
1219 LOGW("power manager service died !!!");
1220}
Eric Laurent1345d332011-07-24 17:49:51 -07001221
Eric Laurentf82fccd2011-07-27 19:49:51 -07001222void AudioFlinger::ThreadBase::setEffectSuspended(
1223 const effect_uuid_t *type, bool suspend, int sessionId)
1224{
1225 Mutex::Autolock _l(mLock);
1226 setEffectSuspended_l(type, suspend, sessionId);
1227}
1228
1229void AudioFlinger::ThreadBase::setEffectSuspended_l(
1230 const effect_uuid_t *type, bool suspend, int sessionId)
1231{
1232 sp<EffectChain> chain;
1233 chain = getEffectChain_l(sessionId);
1234 if (chain != 0) {
1235 if (type != NULL) {
1236 chain->setEffectSuspended_l(type, suspend);
1237 } else {
1238 chain->setEffectSuspendedAll_l(suspend);
1239 }
1240 }
1241
1242 updateSuspendedSessions_l(type, suspend, sessionId);
1243}
1244
1245void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1246{
1247 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1248 if (index < 0) {
1249 return;
1250 }
1251
1252 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1253 mSuspendedSessions.editValueAt(index);
1254
1255 for (size_t i = 0; i < sessionEffects.size(); i++) {
1256 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1257 for (int j = 0; j < desc->mRefCount; j++) {
1258 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1259 chain->setEffectSuspendedAll_l(true);
1260 } else {
1261 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1262 desc->mType.timeLow);
1263 chain->setEffectSuspended_l(&desc->mType, true);
1264 }
1265 }
1266 }
1267}
1268
Eric Laurentf82fccd2011-07-27 19:49:51 -07001269void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1270 bool suspend,
1271 int sessionId)
1272{
1273 int index = mSuspendedSessions.indexOfKey(sessionId);
1274
1275 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1276
1277 if (suspend) {
1278 if (index >= 0) {
1279 sessionEffects = mSuspendedSessions.editValueAt(index);
1280 } else {
1281 mSuspendedSessions.add(sessionId, sessionEffects);
1282 }
1283 } else {
1284 if (index < 0) {
1285 return;
1286 }
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 }
1289
1290
1291 int key = EffectChain::kKeyForSuspendAll;
1292 if (type != NULL) {
1293 key = type->timeLow;
1294 }
1295 index = sessionEffects.indexOfKey(key);
1296
1297 sp <SuspendedSessionDesc> desc;
1298 if (suspend) {
1299 if (index >= 0) {
1300 desc = sessionEffects.valueAt(index);
1301 } else {
1302 desc = new SuspendedSessionDesc();
1303 if (type != NULL) {
1304 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1305 }
1306 sessionEffects.add(key, desc);
1307 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1308 }
1309 desc->mRefCount++;
1310 } else {
1311 if (index < 0) {
1312 return;
1313 }
1314 desc = sessionEffects.valueAt(index);
1315 if (--desc->mRefCount == 0) {
1316 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1317 sessionEffects.removeItemsAt(index);
1318 if (sessionEffects.isEmpty()) {
1319 LOGV("updateSuspendedSessions_l() restore removing session %d",
1320 sessionId);
1321 mSuspendedSessions.removeItem(sessionId);
1322 }
1323 }
1324 }
1325 if (!sessionEffects.isEmpty()) {
1326 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1327 }
1328}
1329
1330void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1331 bool enabled,
1332 int sessionId)
1333{
1334 Mutex::Autolock _l(mLock);
1335
Eric Laurent6752ec82011-08-10 10:37:50 -07001336 if (mType != RECORD) {
1337 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1338 // another session. This gives the priority to well behaved effect control panels
1339 // and applications not using global effects.
1340 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1341 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1342 }
1343 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001344
1345 sp<EffectChain> chain = getEffectChain_l(sessionId);
1346 if (chain != 0) {
1347 chain->checkSuspendOnEffectEnabled(effect, enabled);
1348 }
1349}
1350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351// ----------------------------------------------------------------------------
1352
Eric Laurent464d5b32011-06-17 21:29:58 -07001353AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1354 AudioStreamOut* output,
1355 int id,
1356 uint32_t device)
1357 : ThreadBase(audioFlinger, id, device),
Eric Laurentd5603c12009-08-06 08:49:39 -07001358 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001359 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001361 snprintf(mName, kNameLength, "AudioOut_%d", id);
1362
Eric Laurenta553c252009-07-17 12:17:14 -07001363 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364
Eric Laurenta553c252009-07-17 12:17:14 -07001365 mMasterVolume = mAudioFlinger->masterVolume();
1366 mMasterMute = mAudioFlinger->masterMute();
1367
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001368 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001369 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1370 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001371 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373}
1374
Eric Laurenta553c252009-07-17 12:17:14 -07001375AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376{
1377 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378}
1379
Eric Laurenta553c252009-07-17 12:17:14 -07001380status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381{
1382 dumpInternals(fd, args);
1383 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001384 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 return NO_ERROR;
1386}
1387
Eric Laurenta553c252009-07-17 12:17:14 -07001388status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389{
1390 const size_t SIZE = 256;
1391 char buffer[SIZE];
1392 String8 result;
1393
Eric Laurenta553c252009-07-17 12:17:14 -07001394 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001396 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 -08001397 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001398 sp<Track> track = mTracks[i];
1399 if (track != 0) {
1400 track->dump(buffer, SIZE);
1401 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403 }
1404
Eric Laurenta553c252009-07-17 12:17:14 -07001405 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001407 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 -08001408 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001409 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 if (wTrack != 0) {
1411 sp<Track> track = wTrack.promote();
1412 if (track != 0) {
1413 track->dump(buffer, SIZE);
1414 result.append(buffer);
1415 }
1416 }
1417 }
1418 write(fd, result.string(), result.size());
1419 return NO_ERROR;
1420}
1421
Eric Laurenta553c252009-07-17 12:17:14 -07001422status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423{
1424 const size_t SIZE = 256;
1425 char buffer[SIZE];
1426 String8 result;
1427
Eric Laurent3fdb1262009-11-07 00:01:32 -08001428 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 result.append(buffer);
1430 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1431 result.append(buffer);
1432 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1433 result.append(buffer);
1434 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1435 result.append(buffer);
1436 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1437 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001438 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1439 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001440 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1441 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001443
1444 dumpBase(fd, args);
1445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 return NO_ERROR;
1447}
1448
1449// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001450status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451{
Eric Laurent828b9772011-08-07 16:32:26 -07001452 status_t status = initCheck();
1453 if (status == NO_ERROR) {
1454 LOGI("AudioFlinger's thread %p ready to run", this);
1455 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 LOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 }
Eric Laurent828b9772011-08-07 16:32:26 -07001458 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459}
1460
Eric Laurenta553c252009-07-17 12:17:14 -07001461void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001463 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464}
1465
Eric Laurenta553c252009-07-17 12:17:14 -07001466// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1467sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 const sp<AudioFlinger::Client>& client,
1469 int streamType,
1470 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001471 uint32_t format,
1472 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 int frameCount,
1474 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001475 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 status_t *status)
1477{
1478 sp<Track> track;
1479 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001480
1481 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001482 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1483 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1484 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1485 "for output %p with format %d",
1486 sampleRate, format, channelMask, mOutput, mFormat);
1487 lStatus = BAD_VALUE;
1488 goto Exit;
1489 }
Eric Laurenta553c252009-07-17 12:17:14 -07001490 }
1491 } else {
1492 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1493 if (sampleRate > mSampleRate*2) {
1494 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1495 lStatus = BAD_VALUE;
1496 goto Exit;
1497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499
Eric Laurent464d5b32011-06-17 21:29:58 -07001500 lStatus = initCheck();
1501 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001502 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001503 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505
Eric Laurenta553c252009-07-17 12:17:14 -07001506 { // scope for mLock
1507 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001508
1509 // all tracks in same audio session must share the same routing strategy otherwise
1510 // conflicts will happen when tracks are moved from one output to another by audio policy
1511 // manager
1512 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001513 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001514 for (size_t i = 0; i < mTracks.size(); ++i) {
1515 sp<Track> t = mTracks[i];
1516 if (t != 0) {
1517 if (sessionId == t->sessionId() &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001518 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001519 lStatus = BAD_VALUE;
1520 goto Exit;
1521 }
1522 }
1523 }
1524
Eric Laurenta553c252009-07-17 12:17:14 -07001525 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001526 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001527 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001528 lStatus = NO_MEMORY;
1529 goto Exit;
1530 }
1531 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001532
1533 sp<EffectChain> chain = getEffectChain_l(sessionId);
1534 if (chain != 0) {
1535 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1536 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001537 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001538 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001539 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001540
1541 // invalidate track immediately if the stream type was moved to another thread since
1542 // createTrack() was called by the client process.
1543 if (!mStreamTypes[streamType].valid) {
1544 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1545 this, streamType);
1546 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1547 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001548 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001549 lStatus = NO_ERROR;
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551Exit:
1552 if(status) {
1553 *status = lStatus;
1554 }
1555 return track;
1556}
1557
Eric Laurenta553c252009-07-17 12:17:14 -07001558uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559{
Eric Laurent828b9772011-08-07 16:32:26 -07001560 Mutex::Autolock _l(mLock);
1561 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001562 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001563 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 return 0;
1565 }
1566}
1567
Eric Laurenta553c252009-07-17 12:17:14 -07001568status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569{
1570 mMasterVolume = value;
1571 return NO_ERROR;
1572}
1573
Eric Laurenta553c252009-07-17 12:17:14 -07001574status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575{
1576 mMasterMute = muted;
1577 return NO_ERROR;
1578}
1579
Eric Laurenta553c252009-07-17 12:17:14 -07001580float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581{
1582 return mMasterVolume;
1583}
1584
Eric Laurenta553c252009-07-17 12:17:14 -07001585bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586{
1587 return mMasterMute;
1588}
1589
Eric Laurenta553c252009-07-17 12:17:14 -07001590status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591{
1592 mStreamTypes[stream].volume = value;
1593 return NO_ERROR;
1594}
1595
Eric Laurenta553c252009-07-17 12:17:14 -07001596status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597{
1598 mStreamTypes[stream].mute = muted;
1599 return NO_ERROR;
1600}
1601
Eric Laurenta553c252009-07-17 12:17:14 -07001602float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603{
1604 return mStreamTypes[stream].volume;
1605}
1606
Eric Laurenta553c252009-07-17 12:17:14 -07001607bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608{
1609 return mStreamTypes[stream].mute;
1610}
1611
Eric Laurenta553c252009-07-17 12:17:14 -07001612// addTrack_l() must be called with ThreadBase::mLock held
1613status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614{
1615 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001616
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001617 // set retry count for buffer fill
1618 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001619 if (mActiveTracks.indexOf(track) < 0) {
1620 // the track is newly added, make sure it fills up all its
1621 // buffers before playing. This is to ensure the client will
1622 // effectively get the latency it requested.
1623 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001624 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001625 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001626 if (track->mainBuffer() != mMixBuffer) {
1627 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1628 if (chain != 0) {
1629 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001630 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001631 }
1632 }
1633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001635 }
Eric Laurenta553c252009-07-17 12:17:14 -07001636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001638 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639
1640 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001641}
1642
Eric Laurenta553c252009-07-17 12:17:14 -07001643// destroyTrack_l() must be called with ThreadBase::mLock held
1644void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001645{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001646 track->mState = TrackBase::TERMINATED;
1647 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001648 removeTrack_l(track);
1649 }
1650}
1651
1652void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1653{
1654 mTracks.remove(track);
1655 deleteTrackName_l(track->name());
1656 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1657 if (chain != 0) {
1658 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001659 }
1660}
1661
Eric Laurenta553c252009-07-17 12:17:14 -07001662String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001663{
Eric Laurent828b9772011-08-07 16:32:26 -07001664 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001665 char *s;
1666
Eric Laurent828b9772011-08-07 16:32:26 -07001667 Mutex::Autolock _l(mLock);
1668 if (initCheck() != NO_ERROR) {
1669 return out_s8;
1670 }
1671
Dima Zavin31f188892011-04-18 16:57:27 -07001672 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001673 out_s8 = String8(s);
1674 free(s);
1675 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001676}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001677
Eric Laurent828b9772011-08-07 16:32:26 -07001678// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001679void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001680 AudioSystem::OutputDescriptor desc;
1681 void *param2 = 0;
1682
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001683 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001684
1685 switch (event) {
1686 case AudioSystem::OUTPUT_OPENED:
1687 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001688 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001689 desc.samplingRate = mSampleRate;
1690 desc.format = mFormat;
1691 desc.frameCount = mFrameCount;
1692 desc.latency = latency();
1693 param2 = &desc;
1694 break;
1695
1696 case AudioSystem::STREAM_CONFIG_CHANGED:
1697 param2 = &param;
1698 case AudioSystem::OUTPUT_CLOSED:
1699 default:
1700 break;
1701 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001702 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001703}
1704
1705void AudioFlinger::PlaybackThread::readOutputParameters()
1706{
Dima Zavin31f188892011-04-18 16:57:27 -07001707 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001708 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1709 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001710 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1711 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1712 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001713
Eric Laurenta553c252009-07-17 12:17:14 -07001714 // FIXME - Current mixer implementation only supports stereo output: Always
1715 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001716 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001717 mMixBuffer = new int16_t[mFrameCount * 2];
1718 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001719
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001720 // force reconfiguration of effect chains and engines to take new buffer size and audio
1721 // parameters into account
1722 // Note that mLock is not held when readOutputParameters() is called from the constructor
1723 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1724 // matter.
1725 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1726 Vector< sp<EffectChain> > effectChains = mEffectChains;
1727 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001728 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001729 }
Eric Laurenta553c252009-07-17 12:17:14 -07001730}
1731
Eric Laurent0986e792010-01-19 17:37:09 -08001732status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1733{
1734 if (halFrames == 0 || dspFrames == 0) {
1735 return BAD_VALUE;
1736 }
Eric Laurent828b9772011-08-07 16:32:26 -07001737 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001738 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001739 return INVALID_OPERATION;
1740 }
Dima Zavin31f188892011-04-18 16:57:27 -07001741 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001742
Dima Zavin31f188892011-04-18 16:57:27 -07001743 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001744}
1745
Eric Laurent493941b2010-07-28 01:32:47 -07001746uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001747{
1748 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001749 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001750 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001751 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001752 }
1753
1754 for (size_t i = 0; i < mTracks.size(); ++i) {
1755 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001756 if (sessionId == track->sessionId() &&
1757 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001758 result |= TRACK_SESSION;
1759 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001760 }
1761 }
1762
Eric Laurent493941b2010-07-28 01:32:47 -07001763 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001764}
1765
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001766uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1767{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001768 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001769 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001770 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1771 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001772 }
1773 for (size_t i = 0; i < mTracks.size(); i++) {
1774 sp<Track> track = mTracks[i];
1775 if (sessionId == track->sessionId() &&
1776 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001777 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001778 }
1779 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001780 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001781}
1782
Eric Laurent53334cd2010-06-23 17:38:20 -07001783
Eric Laurent828b9772011-08-07 16:32:26 -07001784AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1785{
1786 Mutex::Autolock _l(mLock);
1787 return mOutput;
1788}
1789
1790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1791{
1792 Mutex::Autolock _l(mLock);
1793 AudioStreamOut *output = mOutput;
1794 mOutput = NULL;
1795 return output;
1796}
1797
1798// this method must always be called either with ThreadBase mLock held or inside the thread loop
1799audio_stream_t* AudioFlinger::PlaybackThread::stream()
1800{
1801 if (mOutput == NULL) {
1802 return NULL;
1803 }
1804 return &mOutput->stream->common;
1805}
1806
Eric Laurenta553c252009-07-17 12:17:14 -07001807// ----------------------------------------------------------------------------
1808
Dima Zavin31f188892011-04-18 16:57:27 -07001809AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001810 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001811 mAudioMixer(0)
1812{
Eric Laurent464d5b32011-06-17 21:29:58 -07001813 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001814 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1815
1816 // FIXME - Current mixer implementation only supports stereo output
1817 if (mChannelCount == 1) {
1818 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001820}
1821
Eric Laurenta553c252009-07-17 12:17:14 -07001822AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001823{
Eric Laurenta553c252009-07-17 12:17:14 -07001824 delete mAudioMixer;
1825}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826
Eric Laurenta553c252009-07-17 12:17:14 -07001827bool AudioFlinger::MixerThread::threadLoop()
1828{
Eric Laurenta553c252009-07-17 12:17:14 -07001829 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001830 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001831 nsecs_t standbyTime = systemTime();
1832 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001833 // FIXME: Relaxed timing because of a certain device that can't meet latency
1834 // Should be reduced to 2x after the vendor fixes the driver issue
1835 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1836 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001837 bool longStandbyExit = false;
1838 uint32_t activeSleepTime = activeSleepTimeUs();
1839 uint32_t idleSleepTime = idleSleepTimeUs();
1840 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001841 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001842#ifdef DEBUG_CPU_USAGE
1843 ThreadCpuUsage cpu;
1844 const CentralTendencyStatistics& stats = cpu.statistics();
1845#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846
Eric Laurent6dbdc402011-07-22 09:04:31 -07001847 acquireWakeLock();
1848
Eric Laurenta553c252009-07-17 12:17:14 -07001849 while (!exitPending())
1850 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001851#ifdef DEBUG_CPU_USAGE
1852 cpu.sampleAndEnable();
1853 unsigned n = stats.n();
1854 // cpu.elapsed() is expensive, so don't call it every loop
1855 if ((n & 127) == 1) {
1856 long long elapsed = cpu.elapsed();
1857 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1858 double perLoop = elapsed / (double) n;
1859 double perLoop100 = perLoop * 0.01;
1860 double mean = stats.mean();
1861 double stddev = stats.stddev();
1862 double minimum = stats.minimum();
1863 double maximum = stats.maximum();
1864 cpu.resetStatistics();
1865 LOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
1866 elapsed * .000000001, n, perLoop * .000001,
1867 mean * .001,
1868 stddev * .001,
1869 minimum * .001,
1870 maximum * .001,
1871 mean / perLoop100,
1872 stddev / perLoop100,
1873 minimum / perLoop100,
1874 maximum / perLoop100);
1875 }
1876 }
1877#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001878 processConfigEvents();
1879
Eric Laurent059b4be2009-11-09 23:32:22 -08001880 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001881 { // scope for mLock
1882
1883 Mutex::Autolock _l(mLock);
1884
1885 if (checkForNewParameters_l()) {
1886 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001887 // FIXME: Relaxed timing because of a certain device that can't meet latency
1888 // Should be reduced to 2x after the vendor fixes the driver issue
1889 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001890 activeSleepTime = activeSleepTimeUs();
1891 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001892 }
1893
1894 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1895
1896 // put audio hardware into standby after short delay
1897 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1898 mSuspended) {
1899 if (!mStandby) {
1900 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001901 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001902 mStandby = true;
1903 mBytesWritten = 0;
1904 }
1905
1906 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1907 // we're about to wait, flush the binder command buffer
1908 IPCThreadState::self()->flushCommands();
1909
1910 if (exitPending()) break;
1911
Eric Laurent6dbdc402011-07-22 09:04:31 -07001912 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001913 // wait until we have something to do...
1914 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1915 mWaitWorkCV.wait(mLock);
1916 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001917 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001918
1919 if (mMasterMute == false) {
1920 char value[PROPERTY_VALUE_MAX];
1921 property_get("ro.audio.silent", value, "0");
1922 if (atoi(value)) {
1923 LOGD("Silence is golden");
1924 setMasterMute(true);
1925 }
1926 }
1927
1928 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001929 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001930 continue;
1931 }
1932 }
1933
Eric Laurent059b4be2009-11-09 23:32:22 -08001934 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001935
1936 // prevent any changes in effect chain list and in each effect chain
1937 // during mixing and effect process as the audio buffers could be deleted
1938 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001939 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001940 }
1941
Eric Laurent059b4be2009-11-09 23:32:22 -08001942 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001943 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001944 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001945 sleepTime = 0;
1946 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001947 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001948 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001949 // If no tracks are ready, sleep once for the duration of an output
1950 // buffer size, then write 0s to the output
1951 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001952 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1953 sleepTime = activeSleepTime;
1954 } else {
1955 sleepTime = idleSleepTime;
1956 }
1957 } else if (mBytesWritten != 0 ||
1958 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001959 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001960 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001961 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001962 }
Eric Laurent65b65452010-06-01 23:49:17 -07001963 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001964 }
1965
1966 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001967 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001968 }
1969 // sleepTime == 0 means we must write to audio hardware
1970 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001971 for (size_t i = 0; i < effectChains.size(); i ++) {
1972 effectChains[i]->process_l();
1973 }
1974 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001975 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07001976 mLastWriteTime = systemTime();
1977 mInWrite = true;
1978 mBytesWritten += mixBufferSize;
1979
Dima Zavin31f188892011-04-18 16:57:27 -07001980 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001981 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001982 mNumWrites++;
1983 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001984 nsecs_t now = systemTime();
1985 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001986 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001987 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001988 if ((now - lastWarning) > kWarningThrottle) {
1989 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1990 ns2ms(delta), mNumDelayedWrites, this);
1991 lastWarning = now;
1992 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001993 if (mStandby) {
1994 longStandbyExit = true;
1995 }
Eric Laurenta553c252009-07-17 12:17:14 -07001996 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001997 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001998 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001999 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002000 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002001 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002002 }
2003
2004 // finally let go of all our tracks, without the lock held
2005 // since we can't guarantee the destructors won't acquire that
2006 // same lock.
2007 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002008
2009 // Effect chains will be actually deleted here if they were removed from
2010 // mEffectChains list during mixing or effects processing
2011 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002012 }
2013
2014 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002015 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002016 }
Eric Laurenta553c252009-07-17 12:17:14 -07002017
Eric Laurent6dbdc402011-07-22 09:04:31 -07002018 releaseWakeLock();
2019
Eric Laurenta553c252009-07-17 12:17:14 -07002020 LOGV("MixerThread %p exiting", this);
2021 return false;
2022}
2023
2024// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002025uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002026{
2027
Eric Laurent059b4be2009-11-09 23:32:22 -08002028 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002029 // find out which tracks need to be processed
2030 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002031 size_t mixedTracks = 0;
2032 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002033
2034 float masterVolume = mMasterVolume;
2035 bool masterMute = mMasterMute;
2036
Eric Laurent8cc93b92010-08-11 05:20:11 -07002037 if (masterMute) {
2038 masterVolume = 0;
2039 }
Eric Laurent65b65452010-06-01 23:49:17 -07002040 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002041 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002042 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002043 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002044 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002045 masterVolume = (float)((v + (1 << 23)) >> 24);
2046 chain.clear();
2047 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002048
Eric Laurenta553c252009-07-17 12:17:14 -07002049 for (size_t i=0 ; i<count ; i++) {
2050 sp<Track> t = activeTracks[i].promote();
2051 if (t == 0) continue;
2052
2053 Track* const track = t.get();
2054 audio_track_cblk_t* cblk = track->cblk();
2055
2056 // The first time a track is added we wait
2057 // for all its buffers to be filled before processing it
2058 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07002059 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002060 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002061 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002062 //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 -07002063
Eric Laurent65b65452010-06-01 23:49:17 -07002064 mixedTracks++;
2065
2066 // track->mainBuffer() != mMixBuffer means there is an effect chain
2067 // connected to the track
2068 chain.clear();
2069 if (track->mainBuffer() != mMixBuffer) {
2070 chain = getEffectChain_l(track->sessionId());
2071 // Delegate volume control to effect in track effect chain if needed
2072 if (chain != 0) {
2073 tracksWithEffect++;
2074 } else {
2075 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2076 track->name(), track->sessionId());
2077 }
2078 }
2079
2080
2081 int param = AudioMixer::VOLUME;
2082 if (track->mFillingUpStatus == Track::FS_FILLED) {
2083 // no ramp for the first volume setting
2084 track->mFillingUpStatus = Track::FS_ACTIVE;
2085 if (track->mState == TrackBase::RESUMING) {
2086 track->mState = TrackBase::ACTIVE;
2087 param = AudioMixer::RAMP_VOLUME;
2088 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08002089 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002090 } else if (cblk->server != 0) {
2091 // If the track is stopped before the first frame was mixed,
2092 // do not apply ramp
2093 param = AudioMixer::RAMP_VOLUME;
2094 }
2095
Eric Laurenta553c252009-07-17 12:17:14 -07002096 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002097 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002098 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002099 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002100 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002101 if (track->isPausing()) {
2102 track->setPaused();
2103 }
2104 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002105
Glenn Kasten871c16c2010-03-05 12:18:01 -08002106 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002107 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002108 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002109 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2110 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002111
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002112 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002113 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002114 // Delegate volume control to effect in track effect chain if needed
2115 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2116 // Do not ramp volume if volume is controlled by effect
2117 param = AudioMixer::VOLUME;
2118 track->mHasVolumeController = true;
2119 } else {
2120 // force no volume ramp when volume controller was just disabled or removed
2121 // from effect chain to avoid volume spike
2122 if (track->mHasVolumeController) {
2123 param = AudioMixer::VOLUME;
2124 }
2125 track->mHasVolumeController = false;
2126 }
2127
2128 // Convert volumes from 8.24 to 4.12 format
2129 int16_t left, right, aux;
2130 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2131 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2132 left = int16_t(v_clamped);
2133 v_clamped = (vr + (1 << 11)) >> 12;
2134 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2135 right = int16_t(v_clamped);
2136
2137 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2138 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002139
Eric Laurent65b65452010-06-01 23:49:17 -07002140 // XXX: these things DON'T need to be done each time
2141 mAudioMixer->setBufferProvider(track);
2142 mAudioMixer->enable(AudioMixer::MIXING);
2143
2144 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2145 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2146 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002147 mAudioMixer->setParameter(
2148 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002149 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002150 mAudioMixer->setParameter(
2151 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002152 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002153 mAudioMixer->setParameter(
2154 AudioMixer::RESAMPLE,
2155 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002156 (void *)(cblk->sampleRate));
2157 mAudioMixer->setParameter(
2158 AudioMixer::TRACK,
2159 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2160 mAudioMixer->setParameter(
2161 AudioMixer::TRACK,
2162 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002163
2164 // reset retry count
2165 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002166 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002167 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002168 //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 -07002169 if (track->isStopped()) {
2170 track->reset();
2171 }
2172 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2173 // We have consumed all the buffers of this track.
2174 // Remove it from the list of active tracks.
2175 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002176 } else {
2177 // No buffers for this track. Give it a few chances to
2178 // fill a buffer, then remove it from active list.
2179 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07002180 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002181 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002182 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002183 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002184 } else if (mixerStatus != MIXER_TRACKS_READY) {
2185 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002186 }
Eric Laurenta553c252009-07-17 12:17:14 -07002187 }
Eric Laurent65b65452010-06-01 23:49:17 -07002188 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07002189 }
2190 }
2191
2192 // remove all the tracks that need to be...
2193 count = tracksToRemove->size();
2194 if (UNLIKELY(count)) {
2195 for (size_t i=0 ; i<count ; i++) {
2196 const sp<Track>& track = tracksToRemove->itemAt(i);
2197 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002198 if (track->mainBuffer() != mMixBuffer) {
2199 chain = getEffectChain_l(track->sessionId());
2200 if (chain != 0) {
2201 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002202 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002203 }
2204 }
Eric Laurenta553c252009-07-17 12:17:14 -07002205 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002206 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002207 }
2208 }
2209 }
2210
Eric Laurent65b65452010-06-01 23:49:17 -07002211 // mix buffer must be cleared if all tracks are connected to an
2212 // effect chain as in this case the mixer will not write to
2213 // mix buffer and track effects will accumulate into it
2214 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2215 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2216 }
2217
Eric Laurent059b4be2009-11-09 23:32:22 -08002218 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002219}
2220
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002221void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002222{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002223 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2224 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002225 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002226
Eric Laurenta553c252009-07-17 12:17:14 -07002227 size_t size = mTracks.size();
2228 for (size_t i = 0; i < size; i++) {
2229 sp<Track> t = mTracks[i];
2230 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002231 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002232 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002233 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002234 }
2235}
Eric Laurenta553c252009-07-17 12:17:14 -07002236
Eric Laurent05ce0942011-08-30 10:18:54 -07002237void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2238{
2239 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2240 this, streamType, valid);
2241 Mutex::Autolock _l(mLock);
2242
2243 mStreamTypes[streamType].valid = valid;
2244}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245
Eric Laurenta553c252009-07-17 12:17:14 -07002246// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002247int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248{
2249 return mAudioMixer->getTrackName();
2250}
2251
Eric Laurenta553c252009-07-17 12:17:14 -07002252// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002253void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254{
Eric Laurent0a080292009-12-07 10:53:10 -08002255 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 mAudioMixer->deleteTrackName(name);
2257}
2258
Eric Laurenta553c252009-07-17 12:17:14 -07002259// checkForNewParameters_l() must be called with ThreadBase::mLock held
2260bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261{
Eric Laurenta553c252009-07-17 12:17:14 -07002262 bool reconfig = false;
2263
Eric Laurent8fce46a2009-08-04 09:45:33 -07002264 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002265 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002266 String8 keyValuePair = mNewParameters[0];
2267 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002268 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002269
Eric Laurenta553c252009-07-17 12:17:14 -07002270 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2271 reconfig = true;
2272 }
2273 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002274 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002275 status = BAD_VALUE;
2276 } else {
2277 reconfig = true;
2278 }
2279 }
2280 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002281 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002282 status = BAD_VALUE;
2283 } else {
2284 reconfig = true;
2285 }
2286 }
2287 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2288 // do not accept frame count changes if tracks are open as the track buffer
2289 // size depends on frame count and correct behavior would not be garantied
2290 // if frame count is changed after track creation
2291 if (!mTracks.isEmpty()) {
2292 status = INVALID_OPERATION;
2293 } else {
2294 reconfig = true;
2295 }
2296 }
Eric Laurent65b65452010-06-01 23:49:17 -07002297 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002298 // when changing the audio output device, call addBatteryData to notify
2299 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002300 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002301 uint32_t params = 0;
2302 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002303 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002304 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2305 }
2306
2307 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002308 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002309 // check if any other device (except speaker) is on
2310 if (value & deviceWithoutSpeaker ) {
2311 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2312 }
2313
2314 if (params != 0) {
2315 addBatteryData(params);
2316 }
2317 }
2318
Eric Laurent65b65452010-06-01 23:49:17 -07002319 // forward device change to effects that have requested to be
2320 // aware of attached audio device.
2321 mDevice = (uint32_t)value;
2322 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002323 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002324 }
2325 }
2326
Eric Laurenta553c252009-07-17 12:17:14 -07002327 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002328 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002329 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002330 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002331 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002332 mStandby = true;
2333 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002334 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002335 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002336 }
2337 if (status == NO_ERROR && reconfig) {
2338 delete mAudioMixer;
2339 readOutputParameters();
2340 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2341 for (size_t i = 0; i < mTracks.size() ; i++) {
2342 int name = getTrackName_l();
2343 if (name < 0) break;
2344 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002345 // limit track sample rate to 2 x new output sample rate
2346 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2347 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2348 }
Eric Laurenta553c252009-07-17 12:17:14 -07002349 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002350 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002351 }
2352 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002353
2354 mNewParameters.removeAt(0);
2355
Eric Laurenta553c252009-07-17 12:17:14 -07002356 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002357 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002358 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2359 // already timed out waiting for the status and will never signal the condition.
2360 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07002361 }
2362 return reconfig;
2363}
2364
2365status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2366{
2367 const size_t SIZE = 256;
2368 char buffer[SIZE];
2369 String8 result;
2370
2371 PlaybackThread::dumpInternals(fd, args);
2372
2373 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2374 result.append(buffer);
2375 write(fd, result.string(), result.size());
2376 return NO_ERROR;
2377}
2378
Eric Laurent059b4be2009-11-09 23:32:22 -08002379uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002380{
Dima Zavin31f188892011-04-18 16:57:27 -07002381 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002382}
2383
2384uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2385{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002386 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002387}
2388
Eric Laurent8448a792010-08-18 18:13:17 -07002389uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2390{
2391 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2392}
2393
Eric Laurenta553c252009-07-17 12:17:14 -07002394// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002395AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002396 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002397{
Eric Laurent464d5b32011-06-17 21:29:58 -07002398 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002399}
2400
2401AudioFlinger::DirectOutputThread::~DirectOutputThread()
2402{
2403}
2404
2405
Eric Laurent65b65452010-06-01 23:49:17 -07002406static inline int16_t clamp16(int32_t sample)
2407{
2408 if ((sample>>15) ^ (sample>>31))
2409 sample = 0x7FFF ^ (sample>>31);
2410 return sample;
2411}
2412
2413static inline
2414int32_t mul(int16_t in, int16_t v)
2415{
2416#if defined(__arm__) && !defined(__thumb__)
2417 int32_t out;
2418 asm( "smulbb %[out], %[in], %[v] \n"
2419 : [out]"=r"(out)
2420 : [in]"%r"(in), [v]"r"(v)
2421 : );
2422 return out;
2423#else
2424 return in * int32_t(v);
2425#endif
2426}
2427
2428void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2429{
2430 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002431 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002432 return;
2433 }
2434
2435 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002436 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002437 size_t count = mFrameCount * mChannelCount;
2438 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2439 int16_t *dst = mMixBuffer + count-1;
2440 while(count--) {
2441 *dst-- = (int16_t)(*src--^0x80) << 8;
2442 }
2443 }
2444
2445 size_t frameCount = mFrameCount;
2446 int16_t *out = mMixBuffer;
2447 if (ramp) {
2448 if (mChannelCount == 1) {
2449 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2450 int32_t vlInc = d / (int32_t)frameCount;
2451 int32_t vl = ((int32_t)mLeftVolShort << 16);
2452 do {
2453 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2454 out++;
2455 vl += vlInc;
2456 } while (--frameCount);
2457
2458 } else {
2459 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2460 int32_t vlInc = d / (int32_t)frameCount;
2461 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2462 int32_t vrInc = d / (int32_t)frameCount;
2463 int32_t vl = ((int32_t)mLeftVolShort << 16);
2464 int32_t vr = ((int32_t)mRightVolShort << 16);
2465 do {
2466 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2467 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2468 out += 2;
2469 vl += vlInc;
2470 vr += vrInc;
2471 } while (--frameCount);
2472 }
2473 } else {
2474 if (mChannelCount == 1) {
2475 do {
2476 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2477 out++;
2478 } while (--frameCount);
2479 } else {
2480 do {
2481 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2482 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2483 out += 2;
2484 } while (--frameCount);
2485 }
2486 }
2487
2488 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002489 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002490 size_t count = mFrameCount * mChannelCount;
2491 int16_t *src = mMixBuffer;
2492 uint8_t *dst = (uint8_t *)mMixBuffer;
2493 while(count--) {
2494 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2495 }
2496 }
2497
2498 mLeftVolShort = leftVol;
2499 mRightVolShort = rightVol;
2500}
2501
Eric Laurenta553c252009-07-17 12:17:14 -07002502bool AudioFlinger::DirectOutputThread::threadLoop()
2503{
Eric Laurent059b4be2009-11-09 23:32:22 -08002504 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002505 sp<Track> trackToRemove;
2506 sp<Track> activeTrack;
2507 nsecs_t standbyTime = systemTime();
2508 int8_t *curBuf;
2509 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002510 uint32_t activeSleepTime = activeSleepTimeUs();
2511 uint32_t idleSleepTime = idleSleepTimeUs();
2512 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002513 // use shorter standby delay as on normal output to release
2514 // hardware resources as soon as possible
2515 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002516
Eric Laurent6dbdc402011-07-22 09:04:31 -07002517 acquireWakeLock();
2518
Eric Laurenta553c252009-07-17 12:17:14 -07002519 while (!exitPending())
2520 {
Eric Laurent65b65452010-06-01 23:49:17 -07002521 bool rampVolume;
2522 uint16_t leftVol;
2523 uint16_t rightVol;
2524 Vector< sp<EffectChain> > effectChains;
2525
Eric Laurenta553c252009-07-17 12:17:14 -07002526 processConfigEvents();
2527
Eric Laurent059b4be2009-11-09 23:32:22 -08002528 mixerStatus = MIXER_IDLE;
2529
Eric Laurenta553c252009-07-17 12:17:14 -07002530 { // scope for the mLock
2531
2532 Mutex::Autolock _l(mLock);
2533
2534 if (checkForNewParameters_l()) {
2535 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002536 activeSleepTime = activeSleepTimeUs();
2537 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002538 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002539 }
2540
2541 // put audio hardware into standby after short delay
2542 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2543 mSuspended) {
2544 // wait until we have something to do...
2545 if (!mStandby) {
2546 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002547 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002548 mStandby = true;
2549 mBytesWritten = 0;
2550 }
2551
2552 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2553 // we're about to wait, flush the binder command buffer
2554 IPCThreadState::self()->flushCommands();
2555
2556 if (exitPending()) break;
2557
Eric Laurent6dbdc402011-07-22 09:04:31 -07002558 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002559 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2560 mWaitWorkCV.wait(mLock);
2561 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002562 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002563
2564 if (mMasterMute == false) {
2565 char value[PROPERTY_VALUE_MAX];
2566 property_get("ro.audio.silent", value, "0");
2567 if (atoi(value)) {
2568 LOGD("Silence is golden");
2569 setMasterMute(true);
2570 }
2571 }
2572
Eric Laurentef9500f2010-03-11 14:47:00 -08002573 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002574 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002575 continue;
2576 }
2577 }
2578
Eric Laurent65b65452010-06-01 23:49:17 -07002579 effectChains = mEffectChains;
2580
Eric Laurenta553c252009-07-17 12:17:14 -07002581 // find out which tracks need to be processed
2582 if (mActiveTracks.size() != 0) {
2583 sp<Track> t = mActiveTracks[0].promote();
2584 if (t == 0) continue;
2585
2586 Track* const track = t.get();
2587 audio_track_cblk_t* cblk = track->cblk();
2588
2589 // The first time a track is added we wait
2590 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002591 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002592 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002593 {
2594 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2595
Eric Laurent65b65452010-06-01 23:49:17 -07002596 if (track->mFillingUpStatus == Track::FS_FILLED) {
2597 track->mFillingUpStatus = Track::FS_ACTIVE;
2598 mLeftVolFloat = mRightVolFloat = 0;
2599 mLeftVolShort = mRightVolShort = 0;
2600 if (track->mState == TrackBase::RESUMING) {
2601 track->mState = TrackBase::ACTIVE;
2602 rampVolume = true;
2603 }
2604 } else if (cblk->server != 0) {
2605 // If the track is stopped before the first frame was mixed,
2606 // do not apply ramp
2607 rampVolume = true;
2608 }
Eric Laurenta553c252009-07-17 12:17:14 -07002609 // compute volume for this track
2610 float left, right;
2611 if (track->isMuted() || mMasterMute || track->isPausing() ||
2612 mStreamTypes[track->type()].mute) {
2613 left = right = 0;
2614 if (track->isPausing()) {
2615 track->setPaused();
2616 }
2617 } else {
2618 float typeVolume = mStreamTypes[track->type()].volume;
2619 float v = mMasterVolume * typeVolume;
2620 float v_clamped = v * cblk->volume[0];
2621 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2622 left = v_clamped/MAX_GAIN;
2623 v_clamped = v * cblk->volume[1];
2624 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2625 right = v_clamped/MAX_GAIN;
2626 }
2627
Eric Laurent65b65452010-06-01 23:49:17 -07002628 if (left != mLeftVolFloat || right != mRightVolFloat) {
2629 mLeftVolFloat = left;
2630 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002631
Eric Laurent65b65452010-06-01 23:49:17 -07002632 // If audio HAL implements volume control,
2633 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002634 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002635 left = 1.0f;
2636 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002637 }
Eric Laurent65b65452010-06-01 23:49:17 -07002638
2639 // Convert volumes from float to 8.24
2640 uint32_t vl = (uint32_t)(left * (1 << 24));
2641 uint32_t vr = (uint32_t)(right * (1 << 24));
2642
2643 // Delegate volume control to effect in track effect chain if needed
2644 // only one effect chain can be present on DirectOutputThread, so if
2645 // there is one, the track is connected to it
2646 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002647 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002648 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002649 rampVolume = false;
2650 }
2651 }
2652
2653 // Convert volumes from 8.24 to 4.12 format
2654 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2655 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2656 leftVol = (uint16_t)v_clamped;
2657 v_clamped = (vr + (1 << 11)) >> 12;
2658 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2659 rightVol = (uint16_t)v_clamped;
2660 } else {
2661 leftVol = mLeftVolShort;
2662 rightVol = mRightVolShort;
2663 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002664 }
2665
2666 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002667 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002668 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002669 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002670 } else {
2671 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2672 if (track->isStopped()) {
2673 track->reset();
2674 }
2675 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2676 // We have consumed all the buffers of this track.
2677 // Remove it from the list of active tracks.
2678 trackToRemove = track;
2679 } else {
2680 // No buffers for this track. Give it a few chances to
2681 // fill a buffer, then remove it from active list.
2682 if (--(track->mRetryCount) <= 0) {
2683 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2684 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002685 } else {
2686 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002687 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002688 }
Eric Laurenta553c252009-07-17 12:17:14 -07002689 }
2690 }
2691
2692 // remove all the tracks that need to be...
2693 if (UNLIKELY(trackToRemove != 0)) {
2694 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002695 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002696 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2697 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002698 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002699 }
Eric Laurenta553c252009-07-17 12:17:14 -07002700 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002701 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002702 }
2703 }
Eric Laurent65b65452010-06-01 23:49:17 -07002704
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002705 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002706 }
2707
Eric Laurent059b4be2009-11-09 23:32:22 -08002708 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002709 AudioBufferProvider::Buffer buffer;
2710 size_t frameCount = mFrameCount;
2711 curBuf = (int8_t *)mMixBuffer;
2712 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002713 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002714 buffer.frameCount = frameCount;
2715 activeTrack->getNextBuffer(&buffer);
2716 if (UNLIKELY(buffer.raw == 0)) {
2717 memset(curBuf, 0, frameCount * mFrameSize);
2718 break;
2719 }
2720 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2721 frameCount -= buffer.frameCount;
2722 curBuf += buffer.frameCount * mFrameSize;
2723 activeTrack->releaseBuffer(&buffer);
2724 }
2725 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002726 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002727 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002728 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002729 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2730 sleepTime = activeSleepTime;
2731 } else {
2732 sleepTime = idleSleepTime;
2733 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002734 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002735 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002736 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002737 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002738 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002739
Eric Laurentf69a3f82009-09-22 00:35:48 -07002740 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002741 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002742 }
2743 // sleepTime == 0 means we must write to audio hardware
2744 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002745 if (mixerStatus == MIXER_TRACKS_READY) {
2746 applyVolume(leftVol, rightVol, rampVolume);
2747 }
2748 for (size_t i = 0; i < effectChains.size(); i ++) {
2749 effectChains[i]->process_l();
2750 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002751 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002752
Eric Laurentf69a3f82009-09-22 00:35:48 -07002753 mLastWriteTime = systemTime();
2754 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002755 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002756 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002757 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002758 mNumWrites++;
2759 mInWrite = false;
2760 mStandby = false;
2761 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002762 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002763 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002764 }
2765
2766 // finally let go of removed track, without the lock held
2767 // since we can't guarantee the destructors won't acquire that
2768 // same lock.
2769 trackToRemove.clear();
2770 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002771
2772 // Effect chains will be actually deleted here if they were removed from
2773 // mEffectChains list during mixing or effects processing
2774 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002775 }
2776
2777 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002778 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002779 }
Eric Laurenta553c252009-07-17 12:17:14 -07002780
Eric Laurent6dbdc402011-07-22 09:04:31 -07002781 releaseWakeLock();
2782
Eric Laurenta553c252009-07-17 12:17:14 -07002783 LOGV("DirectOutputThread %p exiting", this);
2784 return false;
2785}
2786
2787// getTrackName_l() must be called with ThreadBase::mLock held
2788int AudioFlinger::DirectOutputThread::getTrackName_l()
2789{
2790 return 0;
2791}
2792
2793// deleteTrackName_l() must be called with ThreadBase::mLock held
2794void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2795{
2796}
2797
2798// checkForNewParameters_l() must be called with ThreadBase::mLock held
2799bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2800{
2801 bool reconfig = false;
2802
Eric Laurent8fce46a2009-08-04 09:45:33 -07002803 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002804 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002805 String8 keyValuePair = mNewParameters[0];
2806 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002807 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002808
Eric Laurenta553c252009-07-17 12:17:14 -07002809 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2810 // do not accept frame count changes if tracks are open as the track buffer
2811 // size depends on frame count and correct behavior would not be garantied
2812 // if frame count is changed after track creation
2813 if (!mTracks.isEmpty()) {
2814 status = INVALID_OPERATION;
2815 } else {
2816 reconfig = true;
2817 }
2818 }
2819 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002820 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002821 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002822 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002823 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002824 mStandby = true;
2825 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002826 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002827 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002828 }
2829 if (status == NO_ERROR && reconfig) {
2830 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002831 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002832 }
2833 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002834
2835 mNewParameters.removeAt(0);
2836
Eric Laurenta553c252009-07-17 12:17:14 -07002837 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002838 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002839 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2840 // already timed out waiting for the status and will never signal the condition.
2841 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07002842 }
2843 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002844}
2845
Eric Laurent059b4be2009-11-09 23:32:22 -08002846uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002847{
2848 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002849 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin31f188892011-04-18 16:57:27 -07002850 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002851 } else {
2852 time = 10000;
2853 }
2854 return time;
2855}
2856
2857uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2858{
2859 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002860 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002861 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002862 } else {
2863 time = 10000;
2864 }
2865 return time;
2866}
2867
Eric Laurent8448a792010-08-18 18:13:17 -07002868uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2869{
2870 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002871 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002872 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2873 } else {
2874 time = 10000;
2875 }
2876 return time;
2877}
2878
2879
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002880// ----------------------------------------------------------------------------
2881
Eric Laurent49f02be2009-11-19 09:00:56 -08002882AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002883 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002884{
Eric Laurent464d5b32011-06-17 21:29:58 -07002885 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002886 addOutputTrack(mainThread);
2887}
2888
2889AudioFlinger::DuplicatingThread::~DuplicatingThread()
2890{
Eric Laurent0a080292009-12-07 10:53:10 -08002891 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2892 mOutputTracks[i]->destroy();
2893 }
Eric Laurenta553c252009-07-17 12:17:14 -07002894 mOutputTracks.clear();
2895}
2896
2897bool AudioFlinger::DuplicatingThread::threadLoop()
2898{
Eric Laurenta553c252009-07-17 12:17:14 -07002899 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002900 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002901 nsecs_t standbyTime = systemTime();
2902 size_t mixBufferSize = mFrameCount*mFrameSize;
2903 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002904 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002905 uint32_t activeSleepTime = activeSleepTimeUs();
2906 uint32_t idleSleepTime = idleSleepTimeUs();
2907 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002908 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002909
Eric Laurent6dbdc402011-07-22 09:04:31 -07002910 acquireWakeLock();
2911
Eric Laurenta553c252009-07-17 12:17:14 -07002912 while (!exitPending())
2913 {
2914 processConfigEvents();
2915
Eric Laurent059b4be2009-11-09 23:32:22 -08002916 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002917 { // scope for the mLock
2918
2919 Mutex::Autolock _l(mLock);
2920
2921 if (checkForNewParameters_l()) {
2922 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002923 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002924 activeSleepTime = activeSleepTimeUs();
2925 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002926 }
2927
2928 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2929
2930 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2931 outputTracks.add(mOutputTracks[i]);
2932 }
2933
2934 // put audio hardware into standby after short delay
2935 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2936 mSuspended) {
2937 if (!mStandby) {
2938 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002939 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002940 }
2941 mStandby = true;
2942 mBytesWritten = 0;
2943 }
2944
2945 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2946 // we're about to wait, flush the binder command buffer
2947 IPCThreadState::self()->flushCommands();
2948 outputTracks.clear();
2949
2950 if (exitPending()) break;
2951
Eric Laurent6dbdc402011-07-22 09:04:31 -07002952 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002953 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2954 mWaitWorkCV.wait(mLock);
2955 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002956 acquireWakeLock_l();
2957
Eric Laurenta553c252009-07-17 12:17:14 -07002958 if (mMasterMute == false) {
2959 char value[PROPERTY_VALUE_MAX];
2960 property_get("ro.audio.silent", value, "0");
2961 if (atoi(value)) {
2962 LOGD("Silence is golden");
2963 setMasterMute(true);
2964 }
2965 }
2966
2967 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002968 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002969 continue;
2970 }
2971 }
2972
Eric Laurent059b4be2009-11-09 23:32:22 -08002973 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002974
2975 // prevent any changes in effect chain list and in each effect chain
2976 // during mixing and effect process as the audio buffers could be deleted
2977 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002978 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002979 }
Eric Laurenta553c252009-07-17 12:17:14 -07002980
Eric Laurent059b4be2009-11-09 23:32:22 -08002981 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002982 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002983 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002984 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002985 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002986 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002987 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002988 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002989 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002990 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002991 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002992 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2993 sleepTime = activeSleepTime;
2994 } else {
2995 sleepTime = idleSleepTime;
2996 }
Eric Laurent62443f52009-10-05 20:29:18 -07002997 } else if (mBytesWritten != 0) {
2998 // flush remaining overflow buffers in output tracks
2999 for (size_t i = 0; i < outputTracks.size(); i++) {
3000 if (outputTracks[i]->isActive()) {
3001 sleepTime = 0;
3002 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003003 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003004 break;
3005 }
3006 }
Eric Laurenta553c252009-07-17 12:17:14 -07003007 }
3008 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003009
3010 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003011 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003012 }
3013 // sleepTime == 0 means we must write to audio hardware
3014 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003015 for (size_t i = 0; i < effectChains.size(); i ++) {
3016 effectChains[i]->process_l();
3017 }
3018 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003019 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003020
Eric Laurent62443f52009-10-05 20:29:18 -07003021 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003022 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003023 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003024 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003025 mStandby = false;
3026 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003027 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003028 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003029 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003030 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003031 }
3032
3033 // finally let go of all our tracks, without the lock held
3034 // since we can't guarantee the destructors won't acquire that
3035 // same lock.
3036 tracksToRemove.clear();
3037 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003038
3039 // Effect chains will be actually deleted here if they were removed from
3040 // mEffectChains list during mixing or effects processing
3041 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003042 }
3043
Eric Laurent6dbdc402011-07-22 09:04:31 -07003044 releaseWakeLock();
3045
Eric Laurenta553c252009-07-17 12:17:14 -07003046 return false;
3047}
3048
3049void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3050{
3051 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3052 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003053 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003054 mSampleRate,
3055 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003056 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003057 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003058 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003059 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003060 mOutputTracks.add(outputTrack);
3061 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003062 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003063 }
Eric Laurenta553c252009-07-17 12:17:14 -07003064}
3065
3066void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3067{
3068 Mutex::Autolock _l(mLock);
3069 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3070 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003071 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003072 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003073 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003074 return;
3075 }
3076 }
3077 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3078}
3079
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003080void AudioFlinger::DuplicatingThread::updateWaitTime()
3081{
3082 mWaitTimeMs = UINT_MAX;
3083 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3084 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3085 if (strong != NULL) {
3086 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3087 if (waitTimeMs < mWaitTimeMs) {
3088 mWaitTimeMs = waitTimeMs;
3089 }
3090 }
3091 }
3092}
3093
3094
3095bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3096{
3097 for (size_t i = 0; i < outputTracks.size(); i++) {
3098 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3099 if (thread == 0) {
3100 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3101 return false;
3102 }
3103 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3104 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3105 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3106 return false;
3107 }
3108 }
3109 return true;
3110}
3111
3112uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3113{
3114 return (mWaitTimeMs * 1000) / 2;
3115}
3116
Eric Laurenta553c252009-07-17 12:17:14 -07003117// ----------------------------------------------------------------------------
3118
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003119// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003120AudioFlinger::ThreadBase::TrackBase::TrackBase(
3121 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003122 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003123 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003124 uint32_t format,
3125 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003126 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003128 const sp<IMemory>& sharedBuffer,
3129 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003130 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003131 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003132 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003133 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003134 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003135 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003136 mClientTid(-1),
3137 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003138 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3139 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003140{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003141 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3142
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003143 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003144 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003145 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003146 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3147 if (sharedBuffer == 0) {
3148 size += bufferSize;
3149 }
3150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 if (client != NULL) {
3152 mCblkMemory = client->heap()->allocate(size);
3153 if (mCblkMemory != 0) {
3154 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3155 if (mCblk) { // construct the shared structure in-place.
3156 new(mCblk) audio_track_cblk_t();
3157 // clear all buffers
3158 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003159 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003160 mChannelCount = channelCount;
3161 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 if (sharedBuffer == 0) {
3163 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3164 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3165 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003166 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003167 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 } else {
3169 mBuffer = sharedBuffer->pointer();
3170 }
3171 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 } else {
3174 LOGE("not enough memory for AudioTrack size=%u", size);
3175 client->heap()->dump("AudioTrack");
3176 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 } else {
3179 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3180 if (mCblk) { // construct the shared structure in-place.
3181 new(mCblk) audio_track_cblk_t();
3182 // clear all buffers
3183 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003184 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003185 mChannelCount = channelCount;
3186 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3188 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3189 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003190 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003191 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3193 }
3194 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003195}
3196
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003197AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003198{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003200 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3201 if (mClient == NULL) {
3202 delete mCblk;
3203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003205 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003206 if (mClient != NULL) {
3207 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3208 mClient.clear();
3209 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003210}
3211
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003212void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003213{
3214 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003215 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003216 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003217 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003218}
3219
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003220bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003221 bool result;
3222 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003223
3224 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003225 if (!result) {
3226 LOGV("stepServer failed acquiring cblk mutex");
3227 mFlags |= STEPSERVER_FAILED;
3228 }
3229 return result;
3230}
3231
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003232void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003233 audio_track_cblk_t* cblk = this->cblk();
3234
3235 cblk->user = 0;
3236 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003237 cblk->userBase = 0;
3238 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003240 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003241}
3242
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003243sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003244{
3245 return mCblkMemory;
3246}
3247
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003248int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003249 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003250}
3251
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003252int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003253 return (const int)mChannelCount;
3254}
3255
3256uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3257 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003258}
3259
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003260void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003261 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003262 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3263 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003264
3265 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003266 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3267 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003268 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 -07003269 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003270 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003271 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003272 return 0;
3273 }
3274
3275 return bufferStart;
3276}
3277
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003278// ----------------------------------------------------------------------------
3279
Eric Laurenta553c252009-07-17 12:17:14 -07003280// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3281AudioFlinger::PlaybackThread::Track::Track(
3282 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003283 const sp<Client>& client,
3284 int streamType,
3285 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003286 uint32_t format,
3287 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003288 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003289 const sp<IMemory>& sharedBuffer,
3290 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003291 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003292 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3293 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003294{
Eric Laurent8a77a992009-09-09 05:16:08 -07003295 if (mCblk != NULL) {
3296 sp<ThreadBase> baseThread = thread.promote();
3297 if (baseThread != 0) {
3298 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3299 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003300 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003301 }
3302 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3303 if (mName < 0) {
3304 LOGE("no more track names available");
3305 }
3306 mVolume[0] = 1.0f;
3307 mVolume[1] = 1.0f;
3308 mStreamType = streamType;
3309 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3310 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003311 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003312 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003313}
3314
Eric Laurenta553c252009-07-17 12:17:14 -07003315AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003316{
Eric Laurenta553c252009-07-17 12:17:14 -07003317 LOGV("PlaybackThread::Track destructor");
3318 sp<ThreadBase> thread = mThread.promote();
3319 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003320 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003321 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003322 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003323}
3324
Eric Laurenta553c252009-07-17 12:17:14 -07003325void AudioFlinger::PlaybackThread::Track::destroy()
3326{
3327 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3328 // by removing it from mTracks vector, so there is a risk that this Tracks's
3329 // desctructor is called. As the destructor needs to lock mLock,
3330 // we must acquire a strong reference on this Track before locking mLock
3331 // here so that the destructor is called only when exiting this function.
3332 // On the other hand, as long as Track::destroy() is only called by
3333 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3334 // this Track with its member mTrack.
3335 sp<Track> keep(this);
3336 { // scope for mLock
3337 sp<ThreadBase> thread = mThread.promote();
3338 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003339 if (!isOutputTrack()) {
3340 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003341 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003342 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003343 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003344
3345 // to track the speaker usage
3346 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003347 }
3348 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003349 }
Eric Laurenta553c252009-07-17 12:17:14 -07003350 Mutex::Autolock _l(thread->mLock);
3351 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3352 playbackThread->destroyTrack_l(this);
3353 }
3354 }
3355}
3356
3357void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003358{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003359 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 -07003360 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003362 mStreamType,
3363 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003364 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003365 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003366 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003367 mState,
3368 mMute,
3369 mFillingUpStatus,
3370 mCblk->sampleRate,
3371 mCblk->volume[0],
3372 mCblk->volume[1],
3373 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003374 mCblk->user,
3375 (int)mMainBuffer,
3376 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003377}
3378
Eric Laurenta553c252009-07-17 12:17:14 -07003379status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003380{
3381 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003382 uint32_t framesReady;
3383 uint32_t framesReq = buffer->frameCount;
3384
3385 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003386 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3387 if (!step()) goto getNextBuffer_exit;
3388 LOGV("stepServer recovered");
3389 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3390 }
3391
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003392 framesReady = cblk->framesReady();
3393
3394 if (LIKELY(framesReady)) {
3395 uint32_t s = cblk->server;
3396 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3397
3398 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3399 if (framesReq > framesReady) {
3400 framesReq = framesReady;
3401 }
3402 if (s + framesReq > bufferEnd) {
3403 framesReq = bufferEnd - s;
3404 }
3405
3406 buffer->raw = getBuffer(s, framesReq);
3407 if (buffer->raw == 0) goto getNextBuffer_exit;
3408
3409 buffer->frameCount = framesReq;
3410 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003411 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003412
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003413getNextBuffer_exit:
3414 buffer->raw = 0;
3415 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003416 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 -07003417 return NOT_ENOUGH_DATA;
3418}
3419
Eric Laurenta553c252009-07-17 12:17:14 -07003420bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003421 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003422
3423 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003424 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003425 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003426 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003427 return true;
3428 }
3429 return false;
3430}
3431
Eric Laurenta553c252009-07-17 12:17:14 -07003432status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003433{
Eric Laurent49f02be2009-11-19 09:00:56 -08003434 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003435 LOGV("start(%d), calling thread %d session %d",
3436 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003437 sp<ThreadBase> thread = mThread.promote();
3438 if (thread != 0) {
3439 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003440 int state = mState;
3441 // here the track could be either new, or restarted
3442 // in both cases "unstop" the track
3443 if (mState == PAUSED) {
3444 mState = TrackBase::RESUMING;
3445 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3446 } else {
3447 mState = TrackBase::ACTIVE;
3448 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3449 }
3450
3451 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3452 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003453 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003454 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003455 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003456 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003457
3458 // to track the speaker usage
3459 if (status == NO_ERROR) {
3460 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3461 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003462 }
3463 if (status == NO_ERROR) {
3464 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3465 playbackThread->addTrack_l(this);
3466 } else {
3467 mState = state;
3468 }
3469 } else {
3470 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003471 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003472 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003473}
3474
Eric Laurenta553c252009-07-17 12:17:14 -07003475void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003476{
Eric Laurenta553c252009-07-17 12:17:14 -07003477 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3478 sp<ThreadBase> thread = mThread.promote();
3479 if (thread != 0) {
3480 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003481 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003482 if (mState > STOPPED) {
3483 mState = STOPPED;
3484 // If the track is not active (PAUSED and buffers full), flush buffers
3485 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3486 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3487 reset();
3488 }
Eric Laurent62443f52009-10-05 20:29:18 -07003489 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003490 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003491 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3492 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003493 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003494 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003495 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003496 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003497
3498 // to track the speaker usage
3499 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003500 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003501 }
3502}
3503
Eric Laurenta553c252009-07-17 12:17:14 -07003504void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003505{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003507 sp<ThreadBase> thread = mThread.promote();
3508 if (thread != 0) {
3509 Mutex::Autolock _l(thread->mLock);
3510 if (mState == ACTIVE || mState == RESUMING) {
3511 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003512 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003513 if (!isOutputTrack()) {
3514 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003515 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003516 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003517 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003518 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003519
3520 // to track the speaker usage
3521 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003522 }
Eric Laurenta553c252009-07-17 12:17:14 -07003523 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003524 }
3525}
3526
Eric Laurenta553c252009-07-17 12:17:14 -07003527void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003528{
3529 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003530 sp<ThreadBase> thread = mThread.promote();
3531 if (thread != 0) {
3532 Mutex::Autolock _l(thread->mLock);
3533 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3534 return;
3535 }
3536 // No point remaining in PAUSED state after a flush => go to
3537 // STOPPED state
3538 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003539
Eric Laurentae29b762011-03-28 18:37:07 -07003540 // do not reset the track if it is still in the process of being stopped or paused.
3541 // this will be done by prepareTracks_l() when the track is stopped.
3542 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3543 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3544 reset();
3545 }
Eric Laurenta553c252009-07-17 12:17:14 -07003546 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003547}
3548
Eric Laurenta553c252009-07-17 12:17:14 -07003549void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003550{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003551 // Do not reset twice to avoid discarding data written just after a flush and before
3552 // the audioflinger thread detects the track is stopped.
3553 if (!mResetDone) {
3554 TrackBase::reset();
3555 // Force underrun condition to avoid false underrun callback until first data is
3556 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003557 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3558 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003559 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003560 mResetDone = true;
3561 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003562}
3563
Eric Laurenta553c252009-07-17 12:17:14 -07003564void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003565{
3566 mMute = muted;
3567}
3568
Eric Laurenta553c252009-07-17 12:17:14 -07003569void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003570{
3571 mVolume[0] = left;
3572 mVolume[1] = right;
3573}
3574
Eric Laurent65b65452010-06-01 23:49:17 -07003575status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3576{
3577 status_t status = DEAD_OBJECT;
3578 sp<ThreadBase> thread = mThread.promote();
3579 if (thread != 0) {
3580 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3581 status = playbackThread->attachAuxEffect(this, EffectId);
3582 }
3583 return status;
3584}
3585
3586void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3587{
3588 mAuxEffectId = EffectId;
3589 mAuxBuffer = buffer;
3590}
3591
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003592// ----------------------------------------------------------------------------
3593
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003594// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003595AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3596 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003599 uint32_t format,
3600 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003602 uint32_t flags,
3603 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003604 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003605 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003606 mOverflow(false)
3607{
Eric Laurent8a77a992009-09-09 05:16:08 -07003608 if (mCblk != NULL) {
3609 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003610 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003611 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003612 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003613 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003614 } else {
3615 mCblk->frameSize = sizeof(int8_t);
3616 }
3617 }
Eric Laurenta553c252009-07-17 12:17:14 -07003618}
3619
3620AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621{
Eric Laurent49f02be2009-11-19 09:00:56 -08003622 sp<ThreadBase> thread = mThread.promote();
3623 if (thread != 0) {
3624 AudioSystem::releaseInput(thread->id());
3625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626}
3627
Eric Laurenta553c252009-07-17 12:17:14 -07003628status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629{
3630 audio_track_cblk_t* cblk = this->cblk();
3631 uint32_t framesAvail;
3632 uint32_t framesReq = buffer->frameCount;
3633
3634 // Check if last stepServer failed, try to step now
3635 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3636 if (!step()) goto getNextBuffer_exit;
3637 LOGV("stepServer recovered");
3638 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3639 }
3640
3641 framesAvail = cblk->framesAvailable_l();
3642
3643 if (LIKELY(framesAvail)) {
3644 uint32_t s = cblk->server;
3645 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3646
3647 if (framesReq > framesAvail) {
3648 framesReq = framesAvail;
3649 }
3650 if (s + framesReq > bufferEnd) {
3651 framesReq = bufferEnd - s;
3652 }
3653
3654 buffer->raw = getBuffer(s, framesReq);
3655 if (buffer->raw == 0) goto getNextBuffer_exit;
3656
3657 buffer->frameCount = framesReq;
3658 return NO_ERROR;
3659 }
3660
3661getNextBuffer_exit:
3662 buffer->raw = 0;
3663 buffer->frameCount = 0;
3664 return NOT_ENOUGH_DATA;
3665}
3666
Eric Laurenta553c252009-07-17 12:17:14 -07003667status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668{
Eric Laurenta553c252009-07-17 12:17:14 -07003669 sp<ThreadBase> thread = mThread.promote();
3670 if (thread != 0) {
3671 RecordThread *recordThread = (RecordThread *)thread.get();
3672 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003673 } else {
3674 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676}
3677
Eric Laurenta553c252009-07-17 12:17:14 -07003678void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679{
Eric Laurenta553c252009-07-17 12:17:14 -07003680 sp<ThreadBase> thread = mThread.promote();
3681 if (thread != 0) {
3682 RecordThread *recordThread = (RecordThread *)thread.get();
3683 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003684 TrackBase::reset();
3685 // Force overerrun condition to avoid false overrun callback until first data is
3686 // read from buffer
3687 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689}
3690
Eric Laurent3fdb1262009-11-07 00:01:32 -08003691void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3692{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003693 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003694 (mClient == NULL) ? getpid() : mClient->pid(),
3695 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003696 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003697 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003698 mFrameCount,
3699 mState,
3700 mCblk->sampleRate,
3701 mCblk->server,
3702 mCblk->user);
3703}
3704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705
3706// ----------------------------------------------------------------------------
3707
Eric Laurenta553c252009-07-17 12:17:14 -07003708AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3709 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003710 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003712 uint32_t format,
3713 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003715 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003716 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717{
Eric Laurenta553c252009-07-17 12:17:14 -07003718
3719 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003720 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003721 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003722 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3723 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3724 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003725 playbackThread->mTracks.add(this);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003726 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3727 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3728 mCblk, mBuffer, mCblk->buffers,
3729 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003730 } else {
3731 LOGW("Error creating output track on thread %p", playbackThread);
3732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733}
3734
Eric Laurenta553c252009-07-17 12:17:14 -07003735AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736{
Eric Laurent6c30a712009-08-10 23:22:32 -07003737 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738}
3739
Eric Laurenta553c252009-07-17 12:17:14 -07003740status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741{
3742 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003743 if (status != NO_ERROR) {
3744 return status;
3745 }
3746
3747 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 mRetryCount = 127;
3749 return status;
3750}
3751
Eric Laurenta553c252009-07-17 12:17:14 -07003752void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753{
3754 Track::stop();
3755 clearBufferQueue();
3756 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003757 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758}
3759
Eric Laurenta553c252009-07-17 12:17:14 -07003760bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761{
3762 Buffer *pInBuffer;
3763 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003764 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003765 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 inBuffer.frameCount = frames;
3767 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003768
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003769 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003770
Eric Laurent62443f52009-10-05 20:29:18 -07003771 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003772 start();
3773 sp<ThreadBase> thread = mThread.promote();
3774 if (thread != 0) {
3775 MixerThread *mixerThread = (MixerThread *)thread.get();
3776 if (mCblk->frameCount > frames){
3777 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3778 uint32_t startFrames = (mCblk->frameCount - frames);
3779 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003780 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003781 pInBuffer->frameCount = startFrames;
3782 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003783 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003784 mBufferQueue.add(pInBuffer);
3785 } else {
3786 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 }
Eric Laurenta553c252009-07-17 12:17:14 -07003789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 }
3791
Eric Laurenta553c252009-07-17 12:17:14 -07003792 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 // First write pending buffers, then new data
3794 if (mBufferQueue.size()) {
3795 pInBuffer = mBufferQueue.itemAt(0);
3796 } else {
3797 pInBuffer = &inBuffer;
3798 }
Eric Laurenta553c252009-07-17 12:17:14 -07003799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 if (pInBuffer->frameCount == 0) {
3801 break;
3802 }
Eric Laurenta553c252009-07-17 12:17:14 -07003803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 if (mOutBuffer.frameCount == 0) {
3805 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003806 nsecs_t startTime = systemTime();
3807 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003808 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003809 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 break;
3811 }
Eric Laurenta553c252009-07-17 12:17:14 -07003812 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003813 if (waitTimeLeftMs >= waitTimeMs) {
3814 waitTimeLeftMs -= waitTimeMs;
3815 } else {
3816 waitTimeLeftMs = 0;
3817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 }
Eric Laurenta553c252009-07-17 12:17:14 -07003819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003821 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 mCblk->stepUser(outFrames);
3823 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003824 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003826 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 if (pInBuffer->frameCount == 0) {
3829 if (mBufferQueue.size()) {
3830 mBufferQueue.removeAt(0);
3831 delete [] pInBuffer->mBuffer;
3832 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003833 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 -08003834 } else {
3835 break;
3836 }
3837 }
3838 }
Eric Laurenta553c252009-07-17 12:17:14 -07003839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 // If we could not write all frames, allocate a buffer and queue it for next time.
3841 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003842 sp<ThreadBase> thread = mThread.promote();
3843 if (thread != 0 && !thread->standby()) {
3844 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3845 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003846 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003847 pInBuffer->frameCount = inBuffer.frameCount;
3848 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003849 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003850 mBufferQueue.add(pInBuffer);
3851 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3852 } else {
3853 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 }
3856 }
Eric Laurenta553c252009-07-17 12:17:14 -07003857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003859 // 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 -08003860 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003861 if (frames == 0 && mBufferQueue.size() == 0) {
3862 if (mCblk->user < mCblk->frameCount) {
3863 frames = mCblk->frameCount - mCblk->user;
3864 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003865 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003866 pInBuffer->frameCount = frames;
3867 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003868 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003869 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003870 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003871 stop();
3872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 }
3874
Eric Laurenta553c252009-07-17 12:17:14 -07003875 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876}
3877
Eric Laurenta553c252009-07-17 12:17:14 -07003878status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879{
3880 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 status_t result;
3882 audio_track_cblk_t* cblk = mCblk;
3883 uint32_t framesReq = buffer->frameCount;
3884
Eric Laurenta553c252009-07-17 12:17:14 -07003885// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 uint32_t framesAvail = cblk->framesAvailable();
3889
Eric Laurenta553c252009-07-17 12:17:14 -07003890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003892 Mutex::Autolock _l(cblk->lock);
3893 goto start_loop_here;
3894 while (framesAvail == 0) {
3895 active = mActive;
3896 if (UNLIKELY(!active)) {
3897 LOGV("Not active and NO_MORE_BUFFERS");
3898 return AudioTrack::NO_MORE_BUFFERS;
3899 }
3900 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3901 if (result != NO_ERROR) {
3902 return AudioTrack::NO_MORE_BUFFERS;
3903 }
3904 // read the server count again
3905 start_loop_here:
3906 framesAvail = cblk->framesAvailable_l();
3907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909
Eric Laurenta553c252009-07-17 12:17:14 -07003910// if (framesAvail < framesReq) {
3911// return AudioTrack::NO_MORE_BUFFERS;
3912// }
3913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 if (framesReq > framesAvail) {
3915 framesReq = framesAvail;
3916 }
3917
3918 uint32_t u = cblk->user;
3919 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3920
3921 if (u + framesReq > bufferEnd) {
3922 framesReq = bufferEnd - u;
3923 }
3924
3925 buffer->frameCount = framesReq;
3926 buffer->raw = (void *)cblk->buffer(u);
3927 return NO_ERROR;
3928}
3929
3930
Eric Laurenta553c252009-07-17 12:17:14 -07003931void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932{
3933 size_t size = mBufferQueue.size();
3934 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 for (size_t i = 0; i < size; i++) {
3937 pBuffer = mBufferQueue.itemAt(i);
3938 delete [] pBuffer->mBuffer;
3939 delete pBuffer;
3940 }
3941 mBufferQueue.clear();
3942}
3943
3944// ----------------------------------------------------------------------------
3945
3946AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3947 : RefBase(),
3948 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003949 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 mPid(pid)
3951{
3952 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3953}
3954
Eric Laurentb9481d82009-09-17 05:12:56 -07003955// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956AudioFlinger::Client::~Client()
3957{
Eric Laurentb9481d82009-09-17 05:12:56 -07003958 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959}
3960
3961const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3962{
3963 return mMemoryDealer;
3964}
3965
3966// ----------------------------------------------------------------------------
3967
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003968AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3969 const sp<IAudioFlingerClient>& client,
3970 pid_t pid)
3971 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3972{
3973}
3974
3975AudioFlinger::NotificationClient::~NotificationClient()
3976{
3977 mClient.clear();
3978}
3979
3980void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3981{
3982 sp<NotificationClient> keep(this);
3983 {
3984 mAudioFlinger->removeNotificationClient(mPid);
3985 }
3986}
3987
3988// ----------------------------------------------------------------------------
3989
Eric Laurenta553c252009-07-17 12:17:14 -07003990AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003991 : BnAudioTrack(),
3992 mTrack(track)
3993{
3994}
3995
3996AudioFlinger::TrackHandle::~TrackHandle() {
3997 // just stop the track on deletion, associated resources
3998 // will be freed from the main thread once all pending buffers have
3999 // been played. Unless it's not in the active track list, in which
4000 // case we free everything now...
4001 mTrack->destroy();
4002}
4003
4004status_t AudioFlinger::TrackHandle::start() {
4005 return mTrack->start();
4006}
4007
4008void AudioFlinger::TrackHandle::stop() {
4009 mTrack->stop();
4010}
4011
4012void AudioFlinger::TrackHandle::flush() {
4013 mTrack->flush();
4014}
4015
4016void AudioFlinger::TrackHandle::mute(bool e) {
4017 mTrack->mute(e);
4018}
4019
4020void AudioFlinger::TrackHandle::pause() {
4021 mTrack->pause();
4022}
4023
4024void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4025 mTrack->setVolume(left, right);
4026}
4027
4028sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4029 return mTrack->getCblk();
4030}
4031
Eric Laurent65b65452010-06-01 23:49:17 -07004032status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4033{
4034 return mTrack->attachAuxEffect(EffectId);
4035}
4036
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004037status_t AudioFlinger::TrackHandle::onTransact(
4038 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4039{
4040 return BnAudioTrack::onTransact(code, data, reply, flags);
4041}
4042
4043// ----------------------------------------------------------------------------
4044
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004045sp<IAudioRecord> AudioFlinger::openRecord(
4046 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004047 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004048 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004049 uint32_t format,
4050 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004051 int frameCount,
4052 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004053 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004054 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004055{
Eric Laurenta553c252009-07-17 12:17:14 -07004056 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004057 sp<RecordHandle> recordHandle;
4058 sp<Client> client;
4059 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004060 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004061 RecordThread *thread;
4062 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004063 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004064
4065 // check calling permissions
4066 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004067 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004068 goto Exit;
4069 }
4070
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004071 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004072 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004073 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004074 thread = checkRecordThread_l(input);
4075 if (thread == NULL) {
4076 lStatus = BAD_VALUE;
4077 goto Exit;
4078 }
4079
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004080 wclient = mClients.valueFor(pid);
4081 if (wclient != NULL) {
4082 client = wclient.promote();
4083 } else {
4084 client = new Client(this, pid);
4085 mClients.add(pid, client);
4086 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004087
Eric Laurent65b65452010-06-01 23:49:17 -07004088 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004089 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004090 lSessionId = *sessionId;
4091 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004092 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004093 if (sessionId != NULL) {
4094 *sessionId = lSessionId;
4095 }
4096 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004097 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004098 recordTrack = thread->createRecordTrack_l(client,
4099 sampleRate,
4100 format,
4101 channelMask,
4102 frameCount,
4103 flags,
4104 lSessionId,
4105 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004106 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004107 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004108 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4109 // destructor is called by the TrackBase destructor with mLock held
4110 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 goto Exit;
4113 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004114
4115 // return to handle to client
4116 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004117 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004118
4119Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004120 if (status) {
4121 *status = lStatus;
4122 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004123 return recordHandle;
4124}
4125
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004126// ----------------------------------------------------------------------------
4127
Eric Laurenta553c252009-07-17 12:17:14 -07004128AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004129 : BnAudioRecord(),
4130 mRecordTrack(recordTrack)
4131{
4132}
4133
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004134AudioFlinger::RecordHandle::~RecordHandle() {
4135 stop();
4136}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004137
4138status_t AudioFlinger::RecordHandle::start() {
4139 LOGV("RecordHandle::start()");
4140 return mRecordTrack->start();
4141}
4142
4143void AudioFlinger::RecordHandle::stop() {
4144 LOGV("RecordHandle::stop()");
4145 mRecordTrack->stop();
4146}
4147
4148sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4149 return mRecordTrack->getCblk();
4150}
4151
4152status_t AudioFlinger::RecordHandle::onTransact(
4153 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4154{
4155 return BnAudioRecord::onTransact(code, data, reply, flags);
4156}
4157
4158// ----------------------------------------------------------------------------
4159
Eric Laurent464d5b32011-06-17 21:29:58 -07004160AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4161 AudioStreamIn *input,
4162 uint32_t sampleRate,
4163 uint32_t channels,
4164 int id,
4165 uint32_t device) :
4166 ThreadBase(audioFlinger, id, device),
4167 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004168{
Eric Laurent464d5b32011-06-17 21:29:58 -07004169 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004170
4171 snprintf(mName, kNameLength, "AudioIn_%d", id);
4172
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004173 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004174 mReqSampleRate = sampleRate;
4175 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004176}
4177
Eric Laurenta553c252009-07-17 12:17:14 -07004178
4179AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004180{
Eric Laurenta553c252009-07-17 12:17:14 -07004181 delete[] mRsmpInBuffer;
4182 if (mResampler != 0) {
4183 delete mResampler;
4184 delete[] mRsmpOutBuffer;
4185 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004186}
4187
Eric Laurenta553c252009-07-17 12:17:14 -07004188void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004189{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004190 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004191}
Eric Laurent49f02be2009-11-19 09:00:56 -08004192
Eric Laurent828b9772011-08-07 16:32:26 -07004193status_t AudioFlinger::RecordThread::readyToRun()
4194{
4195 status_t status = initCheck();
4196 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4197 return status;
4198}
4199
Eric Laurenta553c252009-07-17 12:17:14 -07004200bool AudioFlinger::RecordThread::threadLoop()
4201{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004202 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004203 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004204 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004205
Eric Laurent4712baa2010-09-30 16:12:31 -07004206 nsecs_t lastWarning = 0;
4207
Eric Laurent6dbdc402011-07-22 09:04:31 -07004208 acquireWakeLock();
4209
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004210 // start recording
4211 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004212
Eric Laurenta553c252009-07-17 12:17:14 -07004213 processConfigEvents();
4214
4215 { // scope for mLock
4216 Mutex::Autolock _l(mLock);
4217 checkForNewParameters_l();
4218 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4219 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004220 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004221 mStandby = true;
4222 }
4223
4224 if (exitPending()) break;
4225
Eric Laurent6dbdc402011-07-22 09:04:31 -07004226 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004227 LOGV("RecordThread: loop stopping");
4228 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004229 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004230 LOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004231 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004232 continue;
4233 }
4234 if (mActiveTrack != 0) {
4235 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004236 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004237 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004238 mStandby = true;
4239 }
Eric Laurenta553c252009-07-17 12:17:14 -07004240 mActiveTrack.clear();
4241 mStartStopCond.broadcast();
4242 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004243 if (mReqChannelCount != mActiveTrack->channelCount()) {
4244 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004245 mStartStopCond.broadcast();
4246 } else if (mBytesRead != 0) {
4247 // record start succeeds only if first read from audio input
4248 // succeeds
4249 if (mBytesRead > 0) {
4250 mActiveTrack->mState = TrackBase::ACTIVE;
4251 } else {
4252 mActiveTrack.clear();
4253 }
4254 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004255 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004256 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004257 }
Eric Laurenta553c252009-07-17 12:17:14 -07004258 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004259 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004260 }
4261
4262 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004263 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4264 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004265 unlockEffectChains(effectChains);
4266 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004267 continue;
4268 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004269 for (size_t i = 0; i < effectChains.size(); i ++) {
4270 effectChains[i]->process_l();
4271 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004272
Eric Laurenta553c252009-07-17 12:17:14 -07004273 buffer.frameCount = mFrameCount;
4274 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4275 size_t framesOut = buffer.frameCount;
4276 if (mResampler == 0) {
4277 // no resampling
4278 while (framesOut) {
4279 size_t framesIn = mFrameCount - mRsmpInIndex;
4280 if (framesIn) {
4281 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4282 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4283 if (framesIn > framesOut)
4284 framesIn = framesOut;
4285 mRsmpInIndex += framesIn;
4286 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004287 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004288 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004289 memcpy(dst, src, framesIn * mFrameSize);
4290 } else {
4291 int16_t *src16 = (int16_t *)src;
4292 int16_t *dst16 = (int16_t *)dst;
4293 if (mChannelCount == 1) {
4294 while (framesIn--) {
4295 *dst16++ = *src16;
4296 *dst16++ = *src16++;
4297 }
4298 } else {
4299 while (framesIn--) {
4300 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4301 src16 += 2;
4302 }
4303 }
4304 }
4305 }
4306 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004307 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004308 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004309 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004310 framesOut = 0;
4311 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004312 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004313 mRsmpInIndex = 0;
4314 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004315 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004316 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004317 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004318 // Force input into standby so that it tries to
4319 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004320 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004321 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004322 }
Eric Laurenta553c252009-07-17 12:17:14 -07004323 mRsmpInIndex = mFrameCount;
4324 framesOut = 0;
4325 buffer.frameCount = 0;
4326 }
4327 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004328 }
4329 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004330 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004331
Eric Laurenta553c252009-07-17 12:17:14 -07004332 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4333 // alter output frame count as if we were expecting stereo samples
4334 if (mChannelCount == 1 && mReqChannelCount == 1) {
4335 framesOut >>= 1;
4336 }
4337 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4338 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4339 // are 32 bit aligned which should be always true.
4340 if (mChannelCount == 2 && mReqChannelCount == 1) {
4341 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4342 // the resampler always outputs stereo samples: do post stereo to mono conversion
4343 int16_t *src = (int16_t *)mRsmpOutBuffer;
4344 int16_t *dst = buffer.i16;
4345 while (framesOut--) {
4346 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4347 src += 2;
4348 }
4349 } else {
4350 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4351 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004352
Eric Laurenta553c252009-07-17 12:17:14 -07004353 }
4354 mActiveTrack->releaseBuffer(&buffer);
4355 mActiveTrack->overflow();
4356 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004357 // client isn't retrieving buffers fast enough
4358 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004359 if (!mActiveTrack->setOverflow()) {
4360 nsecs_t now = systemTime();
4361 if ((now - lastWarning) > kWarningThrottle) {
4362 LOGW("RecordThread: buffer overflow");
4363 lastWarning = now;
4364 }
4365 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004366 // Release the processor for a while before asking for a new buffer.
4367 // This will give the application more chance to read from the buffer and
4368 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004369 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004370 }
4371 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004372 // enable changes in effect chain
4373 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004374 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004375 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004376
Eric Laurenta553c252009-07-17 12:17:14 -07004377 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004378 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004379 }
Eric Laurenta553c252009-07-17 12:17:14 -07004380 mActiveTrack.clear();
4381
Eric Laurent49f02be2009-11-19 09:00:56 -08004382 mStartStopCond.broadcast();
4383
Eric Laurent6dbdc402011-07-22 09:04:31 -07004384 releaseWakeLock();
4385
Eric Laurenta553c252009-07-17 12:17:14 -07004386 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004387 return false;
4388}
4389
Eric Laurent464d5b32011-06-17 21:29:58 -07004390
4391sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4392 const sp<AudioFlinger::Client>& client,
4393 uint32_t sampleRate,
4394 int format,
4395 int channelMask,
4396 int frameCount,
4397 uint32_t flags,
4398 int sessionId,
4399 status_t *status)
4400{
4401 sp<RecordTrack> track;
4402 status_t lStatus;
4403
4404 lStatus = initCheck();
4405 if (lStatus != NO_ERROR) {
4406 LOGE("Audio driver not initialized.");
4407 goto Exit;
4408 }
4409
4410 { // scope for mLock
4411 Mutex::Autolock _l(mLock);
4412
4413 track = new RecordTrack(this, client, sampleRate,
4414 format, channelMask, frameCount, flags, sessionId);
4415
4416 if (track->getCblk() == NULL) {
4417 lStatus = NO_MEMORY;
4418 goto Exit;
4419 }
4420
4421 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004422 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4423 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004424 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004425 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4426 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004427 }
4428 lStatus = NO_ERROR;
4429
4430Exit:
4431 if (status) {
4432 *status = lStatus;
4433 }
4434 return track;
4435}
4436
Eric Laurenta553c252009-07-17 12:17:14 -07004437status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004438{
Eric Laurenta553c252009-07-17 12:17:14 -07004439 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004440 sp <ThreadBase> strongMe = this;
4441 status_t status = NO_ERROR;
4442 {
4443 AutoMutex lock(&mLock);
4444 if (mActiveTrack != 0) {
4445 if (recordTrack != mActiveTrack.get()) {
4446 status = -EBUSY;
4447 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004448 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004449 }
4450 return status;
4451 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004452
Eric Laurent49f02be2009-11-19 09:00:56 -08004453 recordTrack->mState = TrackBase::IDLE;
4454 mActiveTrack = recordTrack;
4455 mLock.unlock();
4456 status_t status = AudioSystem::startInput(mId);
4457 mLock.lock();
4458 if (status != NO_ERROR) {
4459 mActiveTrack.clear();
4460 return status;
4461 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004462 mRsmpInIndex = mFrameCount;
4463 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004464 if (mResampler != NULL) {
4465 mResampler->reset();
4466 }
4467 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004468 // signal thread to start
4469 LOGV("Signal record thread");
4470 mWaitWorkCV.signal();
4471 // do not wait for mStartStopCond if exiting
4472 if (mExiting) {
4473 mActiveTrack.clear();
4474 status = INVALID_OPERATION;
4475 goto startError;
4476 }
4477 mStartStopCond.wait(mLock);
4478 if (mActiveTrack == 0) {
4479 LOGV("Record failed to start");
4480 status = BAD_VALUE;
4481 goto startError;
4482 }
Eric Laurenta553c252009-07-17 12:17:14 -07004483 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004484 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004485 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004486startError:
4487 AudioSystem::stopInput(mId);
4488 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004489}
4490
Eric Laurenta553c252009-07-17 12:17:14 -07004491void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4492 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004493 sp <ThreadBase> strongMe = this;
4494 {
4495 AutoMutex lock(&mLock);
4496 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4497 mActiveTrack->mState = TrackBase::PAUSING;
4498 // do not wait for mStartStopCond if exiting
4499 if (mExiting) {
4500 return;
4501 }
4502 mStartStopCond.wait(mLock);
4503 // if we have been restarted, recordTrack == mActiveTrack.get() here
4504 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4505 mLock.unlock();
4506 AudioSystem::stopInput(mId);
4507 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004508 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004509 }
4510 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004511 }
4512}
4513
Eric Laurenta553c252009-07-17 12:17:14 -07004514status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515{
4516 const size_t SIZE = 256;
4517 char buffer[SIZE];
4518 String8 result;
4519 pid_t pid = 0;
4520
Eric Laurent3fdb1262009-11-07 00:01:32 -08004521 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4522 result.append(buffer);
4523
4524 if (mActiveTrack != 0) {
4525 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004526 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004527 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004529
4530 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4531 result.append(buffer);
4532 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4533 result.append(buffer);
4534 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4535 result.append(buffer);
4536 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4537 result.append(buffer);
4538 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4539 result.append(buffer);
4540
4541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 } else {
4543 result.append("No record client\n");
4544 }
4545 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004546
4547 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004548 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 return NO_ERROR;
4551}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004552
Eric Laurenta553c252009-07-17 12:17:14 -07004553status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4554{
4555 size_t framesReq = buffer->frameCount;
4556 size_t framesReady = mFrameCount - mRsmpInIndex;
4557 int channelCount;
4558
4559 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004560 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004561 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004562 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004563 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004564 // Force input into standby so that it tries to
4565 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004566 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004567 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004568 }
Eric Laurenta553c252009-07-17 12:17:14 -07004569 buffer->raw = 0;
4570 buffer->frameCount = 0;
4571 return NOT_ENOUGH_DATA;
4572 }
4573 mRsmpInIndex = 0;
4574 framesReady = mFrameCount;
4575 }
4576
4577 if (framesReq > framesReady) {
4578 framesReq = framesReady;
4579 }
4580
4581 if (mChannelCount == 1 && mReqChannelCount == 2) {
4582 channelCount = 1;
4583 } else {
4584 channelCount = 2;
4585 }
4586 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4587 buffer->frameCount = framesReq;
4588 return NO_ERROR;
4589}
4590
4591void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4592{
4593 mRsmpInIndex += buffer->frameCount;
4594 buffer->frameCount = 0;
4595}
4596
4597bool AudioFlinger::RecordThread::checkForNewParameters_l()
4598{
4599 bool reconfig = false;
4600
Eric Laurent8fce46a2009-08-04 09:45:33 -07004601 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004602 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004603 String8 keyValuePair = mNewParameters[0];
4604 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004605 int value;
4606 int reqFormat = mFormat;
4607 int reqSamplingRate = mReqSampleRate;
4608 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004609
Eric Laurenta553c252009-07-17 12:17:14 -07004610 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4611 reqSamplingRate = value;
4612 reconfig = true;
4613 }
4614 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4615 reqFormat = value;
4616 reconfig = true;
4617 }
4618 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004619 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004620 reconfig = true;
4621 }
4622 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4623 // do not accept frame count changes if tracks are open as the track buffer
4624 // size depends on frame count and correct behavior would not be garantied
4625 // if frame count is changed after track creation
4626 if (mActiveTrack != 0) {
4627 status = INVALID_OPERATION;
4628 } else {
4629 reconfig = true;
4630 }
4631 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004632 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4633 // forward device change to effects that have requested to be
4634 // aware of attached audio device.
4635 for (size_t i = 0; i < mEffectChains.size(); i++) {
4636 mEffectChains[i]->setDevice_l(value);
4637 }
4638 // store input device and output device but do not forward output device to audio HAL.
4639 // Note that status is ignored by the caller for output device
4640 // (see AudioFlinger::setParameters()
4641 if (value & AUDIO_DEVICE_OUT_ALL) {
4642 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4643 status = BAD_VALUE;
4644 } else {
4645 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004646 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4647 if (mTrack != NULL) {
4648 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004649 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004650 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4651 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4652 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004653 }
4654 mDevice |= (uint32_t)value;
4655 }
Eric Laurenta553c252009-07-17 12:17:14 -07004656 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004657 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004658 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004659 mInput->stream->common.standby(&mInput->stream->common);
4660 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004661 }
4662 if (reconfig) {
4663 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004664 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004665 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004666 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4667 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004668 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004669 status = NO_ERROR;
4670 }
4671 if (status == NO_ERROR) {
4672 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004673 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004674 }
4675 }
4676 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004677
4678 mNewParameters.removeAt(0);
4679
Eric Laurenta553c252009-07-17 12:17:14 -07004680 mParamStatus = status;
4681 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004682 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4683 // already timed out waiting for the status and will never signal the condition.
4684 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Eric Laurenta553c252009-07-17 12:17:14 -07004685 }
4686 return reconfig;
4687}
4688
4689String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4690{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004691 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004692 String8 out_s8 = String8();
4693
4694 Mutex::Autolock _l(mLock);
4695 if (initCheck() != NO_ERROR) {
4696 return out_s8;
4697 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004698
Dima Zavin31f188892011-04-18 16:57:27 -07004699 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004700 out_s8 = String8(s);
4701 free(s);
4702 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004703}
4704
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004705void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004706 AudioSystem::OutputDescriptor desc;
4707 void *param2 = 0;
4708
4709 switch (event) {
4710 case AudioSystem::INPUT_OPENED:
4711 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004712 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004713 desc.samplingRate = mSampleRate;
4714 desc.format = mFormat;
4715 desc.frameCount = mFrameCount;
4716 desc.latency = 0;
4717 param2 = &desc;
4718 break;
4719
4720 case AudioSystem::INPUT_CLOSED:
4721 default:
4722 break;
4723 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004724 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004725}
4726
4727void AudioFlinger::RecordThread::readInputParameters()
4728{
4729 if (mRsmpInBuffer) delete mRsmpInBuffer;
4730 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4731 if (mResampler) delete mResampler;
4732 mResampler = 0;
4733
Dima Zavin31f188892011-04-18 16:57:27 -07004734 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004735 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4736 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004737 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4738 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4739 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004740 mFrameCount = mInputBytes / mFrameSize;
4741 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4742
4743 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4744 {
4745 int channelCount;
4746 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4747 // stereo to mono post process as the resampler always outputs stereo.
4748 if (mChannelCount == 1 && mReqChannelCount == 2) {
4749 channelCount = 1;
4750 } else {
4751 channelCount = 2;
4752 }
4753 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4754 mResampler->setSampleRate(mSampleRate);
4755 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4756 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4757
4758 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4759 if (mChannelCount == 1 && mReqChannelCount == 1) {
4760 mFrameCount >>= 1;
4761 }
4762
4763 }
4764 mRsmpInIndex = mFrameCount;
4765}
4766
Eric Laurent47d0a922010-02-26 02:47:27 -08004767unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4768{
Eric Laurent828b9772011-08-07 16:32:26 -07004769 Mutex::Autolock _l(mLock);
4770 if (initCheck() != NO_ERROR) {
4771 return 0;
4772 }
4773
Dima Zavin31f188892011-04-18 16:57:27 -07004774 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004775}
4776
Eric Laurent464d5b32011-06-17 21:29:58 -07004777uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4778{
4779 Mutex::Autolock _l(mLock);
4780 uint32_t result = 0;
4781 if (getEffectChain_l(sessionId) != 0) {
4782 result = EFFECT_SESSION;
4783 }
4784
4785 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4786 result |= TRACK_SESSION;
4787 }
4788
4789 return result;
4790}
4791
Eric Laurent6639b552011-08-01 09:52:20 -07004792AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4793{
4794 Mutex::Autolock _l(mLock);
4795 return mTrack;
4796}
4797
Eric Laurent828b9772011-08-07 16:32:26 -07004798AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4799{
4800 Mutex::Autolock _l(mLock);
4801 return mInput;
4802}
4803
4804AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4805{
4806 Mutex::Autolock _l(mLock);
4807 AudioStreamIn *input = mInput;
4808 mInput = NULL;
4809 return input;
4810}
4811
4812// this method must always be called either with ThreadBase mLock held or inside the thread loop
4813audio_stream_t* AudioFlinger::RecordThread::stream()
4814{
4815 if (mInput == NULL) {
4816 return NULL;
4817 }
4818 return &mInput->stream->common;
4819}
4820
4821
Eric Laurenta553c252009-07-17 12:17:14 -07004822// ----------------------------------------------------------------------------
4823
Eric Laurentddb78e72009-07-28 08:44:33 -07004824int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004825 uint32_t *pSamplingRate,
4826 uint32_t *pFormat,
4827 uint32_t *pChannels,
4828 uint32_t *pLatencyMs,
4829 uint32_t flags)
4830{
4831 status_t status;
4832 PlaybackThread *thread = NULL;
4833 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4834 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4835 uint32_t format = pFormat ? *pFormat : 0;
4836 uint32_t channels = pChannels ? *pChannels : 0;
4837 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004838 audio_stream_out_t *outStream;
4839 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004840
4841 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4842 pDevices ? *pDevices : 0,
4843 samplingRate,
4844 format,
4845 channels,
4846 flags);
4847
4848 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004849 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004850 }
Dima Zavin31f188892011-04-18 16:57:27 -07004851
Eric Laurenta553c252009-07-17 12:17:14 -07004852 Mutex::Autolock _l(mLock);
4853
Dima Zavin31f188892011-04-18 16:57:27 -07004854 outHwDev = findSuitableHwDev_l(*pDevices);
4855 if (outHwDev == NULL)
4856 return 0;
4857
4858 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4859 &channels, &samplingRate, &outStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004860 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004861 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004862 samplingRate,
4863 format,
4864 channels,
4865 status);
4866
4867 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004868 if (outStream != NULL) {
4869 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004870 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004871
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004872 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4873 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4874 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004875 thread = new DirectOutputThread(this, output, id, *pDevices);
4876 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004877 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004878 thread = new MixerThread(this, output, id, *pDevices);
4879 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004880 }
Eric Laurent65b65452010-06-01 23:49:17 -07004881 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004882
4883 if (pSamplingRate) *pSamplingRate = samplingRate;
4884 if (pFormat) *pFormat = format;
4885 if (pChannels) *pChannels = channels;
4886 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004887
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004888 // notify client processes of the new output creation
4889 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004890 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004891 }
4892
Eric Laurent9cc489a22009-12-05 05:20:01 -08004893 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004894}
4895
Eric Laurentddb78e72009-07-28 08:44:33 -07004896int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004897{
4898 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004899 MixerThread *thread1 = checkMixerThread_l(output1);
4900 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004901
Eric Laurentddb78e72009-07-28 08:44:33 -07004902 if (thread1 == NULL || thread2 == NULL) {
4903 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4904 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004905 }
4906
Eric Laurent464d5b32011-06-17 21:29:58 -07004907 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004908 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004909 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004910 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004911 // notify client processes of the new output creation
4912 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004913 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004914}
4915
Eric Laurentddb78e72009-07-28 08:44:33 -07004916status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004917{
Eric Laurent49018a52009-08-04 08:37:05 -07004918 // keep strong reference on the playback thread so that
4919 // it is not destroyed while exit() is executed
4920 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004921 {
4922 Mutex::Autolock _l(mLock);
4923 thread = checkPlaybackThread_l(output);
4924 if (thread == NULL) {
4925 return BAD_VALUE;
4926 }
4927
Eric Laurentddb78e72009-07-28 08:44:33 -07004928 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004929
Eric Laurent464d5b32011-06-17 21:29:58 -07004930 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004931 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004932 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004933 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004934 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004935 }
4936 }
4937 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004938 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004939 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004940 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004941 }
4942 thread->exit();
4943
Eric Laurent464d5b32011-06-17 21:29:58 -07004944 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07004945 AudioStreamOut *out = thread->clearOutput();
4946 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07004947 out->hwDev->close_output_stream(out->hwDev, out->stream);
4948 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07004949 }
Eric Laurenta553c252009-07-17 12:17:14 -07004950 return NO_ERROR;
4951}
4952
Eric Laurentddb78e72009-07-28 08:44:33 -07004953status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004954{
4955 Mutex::Autolock _l(mLock);
4956 PlaybackThread *thread = checkPlaybackThread_l(output);
4957
4958 if (thread == NULL) {
4959 return BAD_VALUE;
4960 }
4961
Eric Laurentddb78e72009-07-28 08:44:33 -07004962 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004963 thread->suspend();
4964
4965 return NO_ERROR;
4966}
4967
Eric Laurentddb78e72009-07-28 08:44:33 -07004968status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004969{
4970 Mutex::Autolock _l(mLock);
4971 PlaybackThread *thread = checkPlaybackThread_l(output);
4972
4973 if (thread == NULL) {
4974 return BAD_VALUE;
4975 }
4976
Eric Laurentddb78e72009-07-28 08:44:33 -07004977 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004978
4979 thread->restore();
4980
4981 return NO_ERROR;
4982}
4983
Eric Laurentddb78e72009-07-28 08:44:33 -07004984int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004985 uint32_t *pSamplingRate,
4986 uint32_t *pFormat,
4987 uint32_t *pChannels,
4988 uint32_t acoustics)
4989{
4990 status_t status;
4991 RecordThread *thread = NULL;
4992 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4993 uint32_t format = pFormat ? *pFormat : 0;
4994 uint32_t channels = pChannels ? *pChannels : 0;
4995 uint32_t reqSamplingRate = samplingRate;
4996 uint32_t reqFormat = format;
4997 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07004998 audio_stream_in_t *inStream;
4999 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005000
5001 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005002 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005003 }
Dima Zavin31f188892011-04-18 16:57:27 -07005004
Eric Laurenta553c252009-07-17 12:17:14 -07005005 Mutex::Autolock _l(mLock);
5006
Dima Zavin31f188892011-04-18 16:57:27 -07005007 inHwDev = findSuitableHwDev_l(*pDevices);
5008 if (inHwDev == NULL)
5009 return 0;
5010
5011 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5012 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005013 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005014 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005015 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005016 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005017 samplingRate,
5018 format,
5019 channels,
5020 acoustics,
5021 status);
5022
5023 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5024 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5025 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005026 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005027 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005028 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005029 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07005030 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005031 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5032 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005033 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005034 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005035 }
5036
Dima Zavin31f188892011-04-18 16:57:27 -07005037 if (inStream != NULL) {
5038 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5039
Eric Laurent464d5b32011-06-17 21:29:58 -07005040 int id = nextUniqueId();
5041 // Start record thread
5042 // RecorThread require both input and output device indication to forward to audio
5043 // pre processing modules
5044 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5045 thread = new RecordThread(this,
5046 input,
5047 reqSamplingRate,
5048 reqChannels,
5049 id,
5050 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005051 mRecordThreads.add(id, thread);
5052 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005053 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5054 if (pFormat) *pFormat = format;
5055 if (pChannels) *pChannels = reqChannels;
5056
Dima Zavin31f188892011-04-18 16:57:27 -07005057 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005058
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005059 // notify client processes of the new input creation
5060 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005061 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005062 }
5063
Eric Laurent9cc489a22009-12-05 05:20:01 -08005064 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005065}
5066
Eric Laurentddb78e72009-07-28 08:44:33 -07005067status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005068{
Eric Laurent49018a52009-08-04 08:37:05 -07005069 // keep strong reference on the record thread so that
5070 // it is not destroyed while exit() is executed
5071 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005072 {
5073 Mutex::Autolock _l(mLock);
5074 thread = checkRecordThread_l(input);
5075 if (thread == NULL) {
5076 return BAD_VALUE;
5077 }
5078
Eric Laurentddb78e72009-07-28 08:44:33 -07005079 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005080 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005081 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005082 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005083 }
5084 thread->exit();
5085
Eric Laurent828b9772011-08-07 16:32:26 -07005086 AudioStreamIn *in = thread->clearInput();
5087 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005088 in->hwDev->close_input_stream(in->hwDev, in->stream);
5089 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005090
Eric Laurenta553c252009-07-17 12:17:14 -07005091 return NO_ERROR;
5092}
5093
Eric Laurentddb78e72009-07-28 08:44:33 -07005094status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005095{
5096 Mutex::Autolock _l(mLock);
5097 MixerThread *dstThread = checkMixerThread_l(output);
5098 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005099 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005100 return BAD_VALUE;
5101 }
5102
Eric Laurentddb78e72009-07-28 08:44:33 -07005103 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005104 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005105
Eric Laurent05ce0942011-08-30 10:18:54 -07005106 dstThread->setStreamValid(stream, true);
5107
Eric Laurenta553c252009-07-17 12:17:14 -07005108 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005109 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005110 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005111 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005112 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005113 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005114 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005115 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005116 }
Eric Laurentd069f322009-09-01 05:56:26 -07005117
Eric Laurenta553c252009-07-17 12:17:14 -07005118 return NO_ERROR;
5119}
5120
Eric Laurent65b65452010-06-01 23:49:17 -07005121
5122int AudioFlinger::newAudioSessionId()
5123{
Eric Laurent464d5b32011-06-17 21:29:58 -07005124 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005125}
5126
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005127void AudioFlinger::acquireAudioSessionId(int audioSession)
5128{
5129 Mutex::Autolock _l(mLock);
5130 int caller = IPCThreadState::self()->getCallingPid();
5131 LOGV("acquiring %d from %d", audioSession, caller);
5132 int num = mAudioSessionRefs.size();
5133 for (int i = 0; i< num; i++) {
5134 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5135 if (ref->sessionid == audioSession && ref->pid == caller) {
5136 ref->cnt++;
5137 LOGV(" incremented refcount to %d", ref->cnt);
5138 return;
5139 }
5140 }
5141 AudioSessionRef *ref = new AudioSessionRef();
5142 ref->sessionid = audioSession;
5143 ref->pid = caller;
5144 ref->cnt = 1;
5145 mAudioSessionRefs.push(ref);
5146 LOGV(" added new entry for %d", ref->sessionid);
5147}
5148
5149void AudioFlinger::releaseAudioSessionId(int audioSession)
5150{
5151 Mutex::Autolock _l(mLock);
5152 int caller = IPCThreadState::self()->getCallingPid();
5153 LOGV("releasing %d from %d", audioSession, caller);
5154 int num = mAudioSessionRefs.size();
5155 for (int i = 0; i< num; i++) {
5156 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5157 if (ref->sessionid == audioSession && ref->pid == caller) {
5158 ref->cnt--;
5159 LOGV(" decremented refcount to %d", ref->cnt);
5160 if (ref->cnt == 0) {
5161 mAudioSessionRefs.removeAt(i);
5162 delete ref;
5163 purgeStaleEffects_l();
5164 }
5165 return;
5166 }
5167 }
5168 LOGW("session id %d not found for pid %d", audioSession, caller);
5169}
5170
5171void AudioFlinger::purgeStaleEffects_l() {
5172
5173 LOGV("purging stale effects");
5174
5175 Vector< sp<EffectChain> > chains;
5176
5177 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5178 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5179 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5180 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005181 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5182 chains.push(ec);
5183 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005184 }
5185 }
5186 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5187 sp<RecordThread> t = mRecordThreads.valueAt(i);
5188 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5189 sp<EffectChain> ec = t->mEffectChains[j];
5190 chains.push(ec);
5191 }
5192 }
5193
5194 for (size_t i = 0; i < chains.size(); i++) {
5195 sp<EffectChain> ec = chains[i];
5196 int sessionid = ec->sessionId();
5197 sp<ThreadBase> t = ec->mThread.promote();
5198 if (t == 0) {
5199 continue;
5200 }
5201 size_t numsessionrefs = mAudioSessionRefs.size();
5202 bool found = false;
5203 for (size_t k = 0; k < numsessionrefs; k++) {
5204 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5205 if (ref->sessionid == sessionid) {
5206 LOGV(" session %d still exists for %d with %d refs",
5207 sessionid, ref->pid, ref->cnt);
5208 found = true;
5209 break;
5210 }
5211 }
5212 if (!found) {
5213 // remove all effects from the chain
5214 while (ec->mEffects.size()) {
5215 sp<EffectModule> effect = ec->mEffects[0];
5216 effect->unPin();
5217 Mutex::Autolock _l (t->mLock);
5218 t->removeEffect_l(effect);
5219 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5220 sp<EffectHandle> handle = effect->mHandles[j].promote();
5221 if (handle != 0) {
5222 handle->mEffect.clear();
5223 }
5224 }
5225 AudioSystem::unregisterEffect(effect->id());
5226 }
5227 }
5228 }
5229 return;
5230}
5231
Eric Laurenta553c252009-07-17 12:17:14 -07005232// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005233AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005234{
5235 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005236 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5237 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005238 }
Eric Laurenta553c252009-07-17 12:17:14 -07005239 return thread;
5240}
5241
5242// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005243AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005244{
5245 PlaybackThread *thread = checkPlaybackThread_l(output);
5246 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005247 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005248 thread = NULL;
5249 }
5250 }
5251 return (MixerThread *)thread;
5252}
5253
5254// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005255AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005256{
5257 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005258 if (mRecordThreads.indexOfKey(input) >= 0) {
5259 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005260 }
Eric Laurenta553c252009-07-17 12:17:14 -07005261 return thread;
5262}
5263
Eric Laurent464d5b32011-06-17 21:29:58 -07005264uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005265{
Eric Laurent464d5b32011-06-17 21:29:58 -07005266 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005267}
5268
Eric Laurent464d5b32011-06-17 21:29:58 -07005269AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5270{
5271 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5272 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005273 AudioStreamOut *output = thread->getOutput();
5274 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005275 return thread;
5276 }
5277 }
5278 return NULL;
5279}
5280
5281uint32_t AudioFlinger::primaryOutputDevice_l()
5282{
5283 PlaybackThread *thread = primaryPlaybackThread_l();
5284
5285 if (thread == NULL) {
5286 return 0;
5287 }
5288
5289 return thread->device();
5290}
5291
5292
Eric Laurent65b65452010-06-01 23:49:17 -07005293// ----------------------------------------------------------------------------
5294// Effect management
5295// ----------------------------------------------------------------------------
5296
5297
Eric Laurent65b65452010-06-01 23:49:17 -07005298status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5299{
5300 Mutex::Autolock _l(mLock);
5301 return EffectQueryNumberEffects(numEffects);
5302}
5303
Eric Laurent53334cd2010-06-23 17:38:20 -07005304status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005305{
5306 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005307 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005308}
5309
5310status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5311{
5312 Mutex::Autolock _l(mLock);
5313 return EffectGetDescriptor(pUuid, descriptor);
5314}
5315
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005316
Eric Laurent65b65452010-06-01 23:49:17 -07005317sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5318 effect_descriptor_t *pDesc,
5319 const sp<IEffectClient>& effectClient,
5320 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005321 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005322 int sessionId,
5323 status_t *status,
5324 int *id,
5325 int *enabled)
5326{
5327 status_t lStatus = NO_ERROR;
5328 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005329 effect_descriptor_t desc;
5330 sp<Client> client;
5331 wp<Client> wclient;
5332
Eric Laurent464d5b32011-06-17 21:29:58 -07005333 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5334 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005335
5336 if (pDesc == NULL) {
5337 lStatus = BAD_VALUE;
5338 goto Exit;
5339 }
5340
Eric Laurent98c92592010-09-23 16:10:16 -07005341 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005342 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005343 lStatus = PERMISSION_DENIED;
5344 goto Exit;
5345 }
5346
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005347 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005348 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005349 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005350 lStatus = PERMISSION_DENIED;
5351 goto Exit;
5352 }
5353
Eric Laurent464d5b32011-06-17 21:29:58 -07005354 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005355 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005356 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005357 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005358 lStatus = BAD_VALUE;
5359 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005360 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005361 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005362 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005363 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005364 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005365 }
5366 }
5367
Eric Laurent65b65452010-06-01 23:49:17 -07005368 {
5369 Mutex::Autolock _l(mLock);
5370
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005371
Eric Laurent65b65452010-06-01 23:49:17 -07005372 if (!EffectIsNullUuid(&pDesc->uuid)) {
5373 // if uuid is specified, request effect descriptor
5374 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5375 if (lStatus < 0) {
5376 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5377 goto Exit;
5378 }
5379 } else {
5380 // if uuid is not specified, look for an available implementation
5381 // of the required type in effect factory
5382 if (EffectIsNullUuid(&pDesc->type)) {
5383 LOGW("createEffect() no effect type");
5384 lStatus = BAD_VALUE;
5385 goto Exit;
5386 }
5387 uint32_t numEffects = 0;
5388 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005389 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005390 bool found = false;
5391
5392 lStatus = EffectQueryNumberEffects(&numEffects);
5393 if (lStatus < 0) {
5394 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5395 goto Exit;
5396 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005397 for (uint32_t i = 0; i < numEffects; i++) {
5398 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005399 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005400 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005401 continue;
5402 }
5403 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5404 // If matching type found save effect descriptor. If the session is
5405 // 0 and the effect is not auxiliary, continue enumeration in case
5406 // an auxiliary version of this effect type is available
5407 found = true;
5408 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005409 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005410 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5411 break;
5412 }
5413 }
5414 }
5415 if (!found) {
5416 lStatus = BAD_VALUE;
5417 LOGW("createEffect() effect not found");
5418 goto Exit;
5419 }
5420 // For same effect type, chose auxiliary version over insert version if
5421 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005422 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005423 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5424 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5425 }
5426 }
5427
5428 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005429 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005430 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5431 lStatus = INVALID_OPERATION;
5432 goto Exit;
5433 }
5434
Eric Laurentf82fccd2011-07-27 19:49:51 -07005435 // check recording permission for visualizer
5436 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5437 !recordingAllowed()) {
5438 lStatus = PERMISSION_DENIED;
5439 goto Exit;
5440 }
5441
Eric Laurent65b65452010-06-01 23:49:17 -07005442 // return effect descriptor
5443 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5444
5445 // If output is not specified try to find a matching audio session ID in one of the
5446 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005447 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5448 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005449 // Note: io is never 0 when creating an effect on an input
5450 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005451 // look for the thread where the specified audio session is present
5452 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5453 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005454 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005455 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005456 }
Eric Laurent65b65452010-06-01 23:49:17 -07005457 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005458 if (io == 0) {
5459 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5460 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5461 io = mRecordThreads.keyAt(i);
5462 break;
5463 }
5464 }
5465 }
Eric Laurent98c92592010-09-23 16:10:16 -07005466 // If no output thread contains the requested session ID, default to
5467 // first output. The effect chain will be moved to the correct output
5468 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005469 if (io == 0 && mPlaybackThreads.size()) {
5470 io = mPlaybackThreads.keyAt(0);
5471 }
5472 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5473 }
5474 ThreadBase *thread = checkRecordThread_l(io);
5475 if (thread == NULL) {
5476 thread = checkPlaybackThread_l(io);
5477 if (thread == NULL) {
5478 LOGE("createEffect() unknown output thread");
5479 lStatus = BAD_VALUE;
5480 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005481 }
Eric Laurent65b65452010-06-01 23:49:17 -07005482 }
Eric Laurent98c92592010-09-23 16:10:16 -07005483
Eric Laurent65b65452010-06-01 23:49:17 -07005484 wclient = mClients.valueFor(pid);
5485
5486 if (wclient != NULL) {
5487 client = wclient.promote();
5488 } else {
5489 client = new Client(this, pid);
5490 mClients.add(pid, client);
5491 }
5492
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005493 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005494 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5495 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005496 if (handle != 0 && id != NULL) {
5497 *id = handle->id();
5498 }
5499 }
5500
5501Exit:
5502 if(status) {
5503 *status = lStatus;
5504 }
5505 return handle;
5506}
5507
Eric Laurentf82fccd2011-07-27 19:49:51 -07005508status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005509{
5510 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005511 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005512 Mutex::Autolock _l(mLock);
5513 if (srcOutput == dstOutput) {
5514 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5515 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005516 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005517 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5518 if (srcThread == NULL) {
5519 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5520 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005521 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005522 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5523 if (dstThread == NULL) {
5524 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5525 return BAD_VALUE;
5526 }
5527
5528 Mutex::Autolock _dl(dstThread->mLock);
5529 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005530 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005531
Eric Laurent53334cd2010-06-23 17:38:20 -07005532 return NO_ERROR;
5533}
5534
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005535// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005536status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005537 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005538 AudioFlinger::PlaybackThread *dstThread,
5539 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005540{
5541 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005542 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005543
Eric Laurentf82fccd2011-07-27 19:49:51 -07005544 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005545 if (chain == 0) {
5546 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005547 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005548 return INVALID_OPERATION;
5549 }
5550
Eric Laurent493941b2010-07-28 01:32:47 -07005551 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005552 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005553 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005554 // removed.
5555 srcThread->removeEffectChain_l(chain);
5556
5557 // transfer all effects one by one so that new effect chain is created on new thread with
5558 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005559 int dstOutput = dstThread->id();
5560 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005561 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005562 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5563 while (effect != 0) {
5564 srcThread->removeEffect_l(effect);
5565 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005566 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5567 if (effect->state() == EffectModule::ACTIVE ||
5568 effect->state() == EffectModule::STOPPING) {
5569 effect->start();
5570 }
Eric Laurent493941b2010-07-28 01:32:47 -07005571 // if the move request is not received from audio policy manager, the effect must be
5572 // re-registered with the new strategy and output
5573 if (dstChain == 0) {
5574 dstChain = effect->chain().promote();
5575 if (dstChain == 0) {
5576 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5577 srcThread->addEffect_l(effect);
5578 return NO_INIT;
5579 }
5580 strategy = dstChain->strategy();
5581 }
5582 if (reRegister) {
5583 AudioSystem::unregisterEffect(effect->id());
5584 AudioSystem::registerEffect(&effect->desc(),
5585 dstOutput,
5586 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005587 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005588 effect->id());
5589 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005590 effect = chain->getEffectFromId_l(0);
5591 }
5592
5593 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005594}
5595
Eric Laurent464d5b32011-06-17 21:29:58 -07005596
Eric Laurent65b65452010-06-01 23:49:17 -07005597// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005598sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005599 const sp<AudioFlinger::Client>& client,
5600 const sp<IEffectClient>& effectClient,
5601 int32_t priority,
5602 int sessionId,
5603 effect_descriptor_t *desc,
5604 int *enabled,
5605 status_t *status
5606 )
5607{
5608 sp<EffectModule> effect;
5609 sp<EffectHandle> handle;
5610 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005611 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005613 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005614 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005615
Eric Laurent464d5b32011-06-17 21:29:58 -07005616 lStatus = initCheck();
5617 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005618 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005619 goto Exit;
5620 }
5621
5622 // Do not allow effects with session ID 0 on direct output or duplicating threads
5623 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005624 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005625 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5626 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005627 lStatus = BAD_VALUE;
5628 goto Exit;
5629 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005630 // Only Pre processor effects are allowed on input threads and only on input threads
5631 if ((mType == RECORD &&
5632 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5633 (mType != RECORD &&
5634 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5635 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5636 desc->name, desc->flags, mType);
5637 lStatus = BAD_VALUE;
5638 goto Exit;
5639 }
Eric Laurent65b65452010-06-01 23:49:17 -07005640
5641 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5642
5643 { // scope for mLock
5644 Mutex::Autolock _l(mLock);
5645
5646 // check for existing effect chain with the requested audio session
5647 chain = getEffectChain_l(sessionId);
5648 if (chain == 0) {
5649 // create a new chain for this session
5650 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5651 chain = new EffectChain(this, sessionId);
5652 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005653 chain->setStrategy(getStrategyForSession_l(sessionId));
5654 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005655 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005656 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005657 }
5658
5659 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5660
5661 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005662 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005663 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005664 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005665 if (lStatus != NO_ERROR) {
5666 goto Exit;
5667 }
5668 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005669 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005670 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005671 lStatus = effect->status();
5672 if (lStatus != NO_ERROR) {
5673 goto Exit;
5674 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005675 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005676 if (lStatus != NO_ERROR) {
5677 goto Exit;
5678 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005679 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005680
5681 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005682 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005683 }
5684 // create effect handle and connect it to effect module
5685 handle = new EffectHandle(effect, client, effectClient, priority);
5686 lStatus = effect->addHandle(handle);
5687 if (enabled) {
5688 *enabled = (int)effect->isEnabled();
5689 }
5690 }
5691
5692Exit:
5693 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005694 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005695 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005696 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005697 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005698 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005699 AudioSystem::unregisterEffect(effect->id());
5700 }
5701 if (chainCreated) {
5702 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005703 }
Eric Laurent65b65452010-06-01 23:49:17 -07005704 handle.clear();
5705 }
5706
5707 if(status) {
5708 *status = lStatus;
5709 }
5710 return handle;
5711}
5712
Eric Laurent464d5b32011-06-17 21:29:58 -07005713sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5714{
5715 sp<EffectModule> effect;
5716
5717 sp<EffectChain> chain = getEffectChain_l(sessionId);
5718 if (chain != 0) {
5719 effect = chain->getEffectFromId_l(effectId);
5720 }
5721 return effect;
5722}
5723
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005724// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5725// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005726status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005727{
5728 // check for existing effect chain with the requested audio session
5729 int sessionId = effect->sessionId();
5730 sp<EffectChain> chain = getEffectChain_l(sessionId);
5731 bool chainCreated = false;
5732
5733 if (chain == 0) {
5734 // create a new chain for this session
5735 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5736 chain = new EffectChain(this, sessionId);
5737 addEffectChain_l(chain);
5738 chain->setStrategy(getStrategyForSession_l(sessionId));
5739 chainCreated = true;
5740 }
5741 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5742
5743 if (chain->getEffectFromId_l(effect->id()) != 0) {
5744 LOGW("addEffect_l() %p effect %s already present in chain %p",
5745 this, effect->desc().name, chain.get());
5746 return BAD_VALUE;
5747 }
5748
5749 status_t status = chain->addEffect_l(effect);
5750 if (status != NO_ERROR) {
5751 if (chainCreated) {
5752 removeEffectChain_l(chain);
5753 }
5754 return status;
5755 }
5756
5757 effect->setDevice(mDevice);
5758 effect->setMode(mAudioFlinger->getMode());
5759 return NO_ERROR;
5760}
5761
Eric Laurent464d5b32011-06-17 21:29:58 -07005762void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005763
5764 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005765 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005766 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5767 detachAuxEffect_l(effect->id());
5768 }
5769
5770 sp<EffectChain> chain = effect->chain().promote();
5771 if (chain != 0) {
5772 // remove effect chain if removing last effect
5773 if (chain->removeEffect_l(effect) == 0) {
5774 removeEffectChain_l(chain);
5775 }
5776 } else {
5777 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5778 }
5779}
5780
Eric Laurent464d5b32011-06-17 21:29:58 -07005781void AudioFlinger::ThreadBase::lockEffectChains_l(
5782 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5783{
5784 effectChains = mEffectChains;
5785 for (size_t i = 0; i < mEffectChains.size(); i++) {
5786 mEffectChains[i]->lock();
5787 }
5788}
5789
5790void AudioFlinger::ThreadBase::unlockEffectChains(
5791 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5792{
5793 for (size_t i = 0; i < effectChains.size(); i++) {
5794 effectChains[i]->unlock();
5795 }
5796}
5797
5798sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5799{
5800 Mutex::Autolock _l(mLock);
5801 return getEffectChain_l(sessionId);
5802}
5803
5804sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5805{
5806 sp<EffectChain> chain;
5807
5808 size_t size = mEffectChains.size();
5809 for (size_t i = 0; i < size; i++) {
5810 if (mEffectChains[i]->sessionId() == sessionId) {
5811 chain = mEffectChains[i];
5812 break;
5813 }
5814 }
5815 return chain;
5816}
5817
5818void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5819{
5820 Mutex::Autolock _l(mLock);
5821 size_t size = mEffectChains.size();
5822 for (size_t i = 0; i < size; i++) {
5823 mEffectChains[i]->setMode_l(mode);
5824 }
5825}
5826
5827void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005828 const wp<EffectHandle>& handle,
5829 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005830
Eric Laurent53334cd2010-06-23 17:38:20 -07005831 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005832 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005833 // delete the effect module if removing last handle on it
5834 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005835 if (!effect->isPinned() || unpiniflast) {
5836 removeEffect_l(effect);
5837 AudioSystem::unregisterEffect(effect->id());
5838 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005839 }
5840}
5841
Eric Laurent65b65452010-06-01 23:49:17 -07005842status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5843{
5844 int session = chain->sessionId();
5845 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005846 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005847
5848 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005849 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005850 // Only one effect chain can be present in direct output thread and it uses
5851 // the mix buffer as input
5852 if (mType != DIRECT) {
5853 size_t numSamples = mFrameCount * mChannelCount;
5854 buffer = new int16_t[numSamples];
5855 memset(buffer, 0, numSamples * sizeof(int16_t));
5856 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5857 ownsBuffer = true;
5858 }
Eric Laurent65b65452010-06-01 23:49:17 -07005859
Eric Laurent53334cd2010-06-23 17:38:20 -07005860 // Attach all tracks with same session ID to this chain.
5861 for (size_t i = 0; i < mTracks.size(); ++i) {
5862 sp<Track> track = mTracks[i];
5863 if (session == track->sessionId()) {
5864 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5865 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005866 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005867 }
5868 }
5869
5870 // indicate all active tracks in the chain
5871 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5872 sp<Track> track = mActiveTracks[i].promote();
5873 if (track == 0) continue;
5874 if (session == track->sessionId()) {
5875 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005876 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005877 }
Eric Laurent65b65452010-06-01 23:49:17 -07005878 }
5879 }
5880
Eric Laurent53334cd2010-06-23 17:38:20 -07005881 chain->setInBuffer(buffer, ownsBuffer);
5882 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005883 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005884 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005885 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5886 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005887 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005888 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5889 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005890 // Effect chain for other sessions are inserted at beginning of effect
5891 // chains list to be processed before output mix effects. Relative order between other
5892 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005893 size_t size = mEffectChains.size();
5894 size_t i = 0;
5895 for (i = 0; i < size; i++) {
5896 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005897 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005898 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005899 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005900
5901 return NO_ERROR;
5902}
5903
5904size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5905{
5906 int session = chain->sessionId();
5907
5908 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5909
5910 for (size_t i = 0; i < mEffectChains.size(); i++) {
5911 if (chain == mEffectChains[i]) {
5912 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005913 // detach all active tracks from the chain
5914 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5915 sp<Track> track = mActiveTracks[i].promote();
5916 if (track == 0) continue;
5917 if (session == track->sessionId()) {
5918 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5919 chain.get(), session);
5920 chain->decActiveTrackCnt();
5921 }
5922 }
5923
Eric Laurent65b65452010-06-01 23:49:17 -07005924 // detach all tracks with same session ID from this chain
5925 for (size_t i = 0; i < mTracks.size(); ++i) {
5926 sp<Track> track = mTracks[i];
5927 if (session == track->sessionId()) {
5928 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005929 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005930 }
5931 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005932 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005933 }
5934 }
5935 return mEffectChains.size();
5936}
5937
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005938status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5939 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005940{
5941 Mutex::Autolock _l(mLock);
5942 return attachAuxEffect_l(track, EffectId);
5943}
5944
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005945status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5946 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005947{
5948 status_t status = NO_ERROR;
5949
5950 if (EffectId == 0) {
5951 track->setAuxBuffer(0, NULL);
5952 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005953 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5954 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005955 if (effect != 0) {
5956 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5957 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5958 } else {
5959 status = INVALID_OPERATION;
5960 }
5961 } else {
5962 status = BAD_VALUE;
5963 }
5964 }
5965 return status;
5966}
5967
5968void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5969{
5970 for (size_t i = 0; i < mTracks.size(); ++i) {
5971 sp<Track> track = mTracks[i];
5972 if (track->auxEffectId() == effectId) {
5973 attachAuxEffect_l(track, 0);
5974 }
5975 }
5976}
5977
Eric Laurent464d5b32011-06-17 21:29:58 -07005978status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5979{
5980 // only one chain per input thread
5981 if (mEffectChains.size() != 0) {
5982 return INVALID_OPERATION;
5983 }
5984 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5985
5986 chain->setInBuffer(NULL);
5987 chain->setOutBuffer(NULL);
5988
Eric Laurentf82fccd2011-07-27 19:49:51 -07005989 checkSuspendOnAddEffectChain_l(chain);
5990
Eric Laurent464d5b32011-06-17 21:29:58 -07005991 mEffectChains.add(chain);
5992
5993 return NO_ERROR;
5994}
5995
5996size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5997{
5998 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5999 LOGW_IF(mEffectChains.size() != 1,
6000 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6001 chain.get(), mEffectChains.size(), this);
6002 if (mEffectChains.size() == 1) {
6003 mEffectChains.removeAt(0);
6004 }
6005 return 0;
6006}
6007
Eric Laurent65b65452010-06-01 23:49:17 -07006008// ----------------------------------------------------------------------------
6009// EffectModule implementation
6010// ----------------------------------------------------------------------------
6011
6012#undef LOG_TAG
6013#define LOG_TAG "AudioFlinger::EffectModule"
6014
6015AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6016 const wp<AudioFlinger::EffectChain>& chain,
6017 effect_descriptor_t *desc,
6018 int id,
6019 int sessionId)
6020 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006021 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006022{
6023 LOGV("Constructor %p", this);
6024 int lStatus;
6025 sp<ThreadBase> thread = mThread.promote();
6026 if (thread == 0) {
6027 return;
6028 }
Eric Laurent65b65452010-06-01 23:49:17 -07006029
6030 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6031
6032 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006033 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006034
Eric Laurent65b65452010-06-01 23:49:17 -07006035 if (mStatus != NO_ERROR) {
6036 return;
6037 }
6038 lStatus = init();
6039 if (lStatus < 0) {
6040 mStatus = lStatus;
6041 goto Error;
6042 }
6043
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006044 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6045 mPinned = true;
6046 }
Eric Laurent65b65452010-06-01 23:49:17 -07006047 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6048 return;
6049Error:
6050 EffectRelease(mEffectInterface);
6051 mEffectInterface = NULL;
6052 LOGV("Constructor Error %d", mStatus);
6053}
6054
6055AudioFlinger::EffectModule::~EffectModule()
6056{
6057 LOGV("Destructor %p", this);
6058 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006059 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6060 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6061 sp<ThreadBase> thread = mThread.promote();
6062 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006063 audio_stream_t *stream = thread->stream();
6064 if (stream != NULL) {
6065 stream->remove_audio_effect(stream, mEffectInterface);
6066 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006067 }
6068 }
Eric Laurent65b65452010-06-01 23:49:17 -07006069 // release effect engine
6070 EffectRelease(mEffectInterface);
6071 }
6072}
6073
6074status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6075{
6076 status_t status;
6077
6078 Mutex::Autolock _l(mLock);
6079 // First handle in mHandles has highest priority and controls the effect module
6080 int priority = handle->priority();
6081 size_t size = mHandles.size();
6082 sp<EffectHandle> h;
6083 size_t i;
6084 for (i = 0; i < size; i++) {
6085 h = mHandles[i].promote();
6086 if (h == 0) continue;
6087 if (h->priority() <= priority) break;
6088 }
6089 // if inserted in first place, move effect control from previous owner to this handle
6090 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006091 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006092 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006093 enabled = h->enabled();
6094 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006095 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006096 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006097 status = NO_ERROR;
6098 } else {
6099 status = ALREADY_EXISTS;
6100 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006101 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006102 mHandles.insertAt(handle, i);
6103 return status;
6104}
6105
6106size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6107{
6108 Mutex::Autolock _l(mLock);
6109 size_t size = mHandles.size();
6110 size_t i;
6111 for (i = 0; i < size; i++) {
6112 if (mHandles[i] == handle) break;
6113 }
6114 if (i == size) {
6115 return size;
6116 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006117 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6118
6119 bool enabled = false;
6120 EffectHandle *hdl = handle.unsafe_get();
6121 if (hdl) {
6122 LOGV("removeHandle() unsafe_get OK");
6123 enabled = hdl->enabled();
6124 }
Eric Laurent65b65452010-06-01 23:49:17 -07006125 mHandles.removeAt(i);
6126 size = mHandles.size();
6127 // if removed from first place, move effect control from this handle to next in line
6128 if (i == 0 && size != 0) {
6129 sp<EffectHandle> h = mHandles[0].promote();
6130 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006131 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006132 }
6133 }
6134
Eric Laurent21b5c472011-07-26 20:54:46 -07006135 // Prevent calls to process() and other functions on effect interface from now on.
6136 // The effect engine will be released by the destructor when the last strong reference on
6137 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006138 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006139 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006140 }
6141
Eric Laurent65b65452010-06-01 23:49:17 -07006142 return size;
6143}
6144
Eric Laurentf82fccd2011-07-27 19:49:51 -07006145sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6146{
6147 Mutex::Autolock _l(mLock);
6148 sp<EffectHandle> handle;
6149 if (mHandles.size() != 0) {
6150 handle = mHandles[0].promote();
6151 }
6152 return handle;
6153}
6154
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006155void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006156{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006157 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006158 // keep a strong reference on this EffectModule to avoid calling the
6159 // destructor before we exit
6160 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006161 {
6162 sp<ThreadBase> thread = mThread.promote();
6163 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006164 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006165 }
6166 }
6167}
6168
Eric Laurent7d850f22010-07-09 13:34:17 -07006169void AudioFlinger::EffectModule::updateState() {
6170 Mutex::Autolock _l(mLock);
6171
6172 switch (mState) {
6173 case RESTART:
6174 reset_l();
6175 // FALL THROUGH
6176
6177 case STARTING:
6178 // clear auxiliary effect input buffer for next accumulation
6179 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6180 memset(mConfig.inputCfg.buffer.raw,
6181 0,
6182 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6183 }
6184 start_l();
6185 mState = ACTIVE;
6186 break;
6187 case STOPPING:
6188 stop_l();
6189 mDisableWaitCnt = mMaxDisableWaitCnt;
6190 mState = STOPPED;
6191 break;
6192 case STOPPED:
6193 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6194 // turn off sequence.
6195 if (--mDisableWaitCnt == 0) {
6196 reset_l();
6197 mState = IDLE;
6198 }
6199 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006200 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006201 break;
6202 }
6203}
6204
Eric Laurent65b65452010-06-01 23:49:17 -07006205void AudioFlinger::EffectModule::process()
6206{
6207 Mutex::Autolock _l(mLock);
6208
Eric Laurent21b5c472011-07-26 20:54:46 -07006209 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006210 mConfig.inputCfg.buffer.raw == NULL ||
6211 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006212 return;
6213 }
6214
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006215 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006216 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6217 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6218 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6219 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006220 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006221 }
6222
Eric Laurent65b65452010-06-01 23:49:17 -07006223 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006224 int ret = (*mEffectInterface)->process(mEffectInterface,
6225 &mConfig.inputCfg.buffer,
6226 &mConfig.outputCfg.buffer);
6227
6228 // force transition to IDLE state when engine is ready
6229 if (mState == STOPPED && ret == -ENODATA) {
6230 mDisableWaitCnt = 1;
6231 }
Eric Laurent65b65452010-06-01 23:49:17 -07006232
6233 // clear auxiliary effect input buffer for next accumulation
6234 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006235 memset(mConfig.inputCfg.buffer.raw, 0,
6236 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006237 }
6238 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006239 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6240 // If an insert effect is idle and input buffer is different from output buffer,
6241 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006242 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006243 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006244 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6245 int16_t *in = mConfig.inputCfg.buffer.s16;
6246 int16_t *out = mConfig.outputCfg.buffer.s16;
6247 for (size_t i = 0; i < frameCnt; i++) {
6248 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006249 }
Eric Laurent65b65452010-06-01 23:49:17 -07006250 }
6251 }
6252}
6253
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006254void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006255{
6256 if (mEffectInterface == NULL) {
6257 return;
6258 }
6259 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6260}
6261
6262status_t AudioFlinger::EffectModule::configure()
6263{
6264 uint32_t channels;
6265 if (mEffectInterface == NULL) {
6266 return NO_INIT;
6267 }
6268
6269 sp<ThreadBase> thread = mThread.promote();
6270 if (thread == 0) {
6271 return DEAD_OBJECT;
6272 }
6273
6274 // TODO: handle configuration of effects replacing track process
6275 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006276 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006277 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006278 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006279 }
6280
6281 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006282 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006283 } else {
6284 mConfig.inputCfg.channels = channels;
6285 }
6286 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006287 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6288 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006289 mConfig.inputCfg.samplingRate = thread->sampleRate();
6290 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6291 mConfig.inputCfg.bufferProvider.cookie = NULL;
6292 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6293 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6294 mConfig.outputCfg.bufferProvider.cookie = NULL;
6295 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6296 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6297 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6298 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006299 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006300 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006301 // - in other sessions:
6302 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6303 // other effect: overwrites output buffer: input buffer == output buffer
6304 // Auxiliary effect:
6305 // accumulates in output buffer: input buffer != output buffer
6306 // Therefore: accumulate <=> input buffer != output buffer
6307 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6308 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6309 } else {
6310 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6311 }
6312 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6313 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6314 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6315 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6316
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006317 LOGV("configure() %p thread %p buffer %p framecount %d",
6318 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6319
Eric Laurent65b65452010-06-01 23:49:17 -07006320 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006321 uint32_t size = sizeof(int);
6322 status_t status = (*mEffectInterface)->command(mEffectInterface,
6323 EFFECT_CMD_CONFIGURE,
6324 sizeof(effect_config_t),
6325 &mConfig,
6326 &size,
6327 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006328 if (status == 0) {
6329 status = cmdStatus;
6330 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006331
6332 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6333 (1000 * mConfig.outputCfg.buffer.frameCount);
6334
Eric Laurent65b65452010-06-01 23:49:17 -07006335 return status;
6336}
6337
6338status_t AudioFlinger::EffectModule::init()
6339{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006340 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006341 if (mEffectInterface == NULL) {
6342 return NO_INIT;
6343 }
6344 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006345 uint32_t size = sizeof(status_t);
6346 status_t status = (*mEffectInterface)->command(mEffectInterface,
6347 EFFECT_CMD_INIT,
6348 0,
6349 NULL,
6350 &size,
6351 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006352 if (status == 0) {
6353 status = cmdStatus;
6354 }
6355 return status;
6356}
6357
Eric Laurent6fccbd02011-10-05 17:42:25 -07006358status_t AudioFlinger::EffectModule::start()
6359{
6360 Mutex::Autolock _l(mLock);
6361 return start_l();
6362}
6363
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006364status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006365{
6366 if (mEffectInterface == NULL) {
6367 return NO_INIT;
6368 }
6369 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006370 uint32_t size = sizeof(status_t);
6371 status_t status = (*mEffectInterface)->command(mEffectInterface,
6372 EFFECT_CMD_ENABLE,
6373 0,
6374 NULL,
6375 &size,
6376 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006377 if (status == 0) {
6378 status = cmdStatus;
6379 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006380 if (status == 0 &&
6381 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6382 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6383 sp<ThreadBase> thread = mThread.promote();
6384 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006385 audio_stream_t *stream = thread->stream();
6386 if (stream != NULL) {
6387 stream->add_audio_effect(stream, mEffectInterface);
6388 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006389 }
6390 }
Eric Laurent65b65452010-06-01 23:49:17 -07006391 return status;
6392}
6393
Eric Laurent21b5c472011-07-26 20:54:46 -07006394status_t AudioFlinger::EffectModule::stop()
6395{
6396 Mutex::Autolock _l(mLock);
6397 return stop_l();
6398}
6399
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006400status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006401{
6402 if (mEffectInterface == NULL) {
6403 return NO_INIT;
6404 }
6405 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006406 uint32_t size = sizeof(status_t);
6407 status_t status = (*mEffectInterface)->command(mEffectInterface,
6408 EFFECT_CMD_DISABLE,
6409 0,
6410 NULL,
6411 &size,
6412 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006413 if (status == 0) {
6414 status = cmdStatus;
6415 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006416 if (status == 0 &&
6417 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6418 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6419 sp<ThreadBase> thread = mThread.promote();
6420 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006421 audio_stream_t *stream = thread->stream();
6422 if (stream != NULL) {
6423 stream->remove_audio_effect(stream, mEffectInterface);
6424 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006425 }
6426 }
Eric Laurent65b65452010-06-01 23:49:17 -07006427 return status;
6428}
6429
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006430status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6431 uint32_t cmdSize,
6432 void *pCmdData,
6433 uint32_t *replySize,
6434 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006435{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006436 Mutex::Autolock _l(mLock);
6437// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006438
Eric Laurent21b5c472011-07-26 20:54:46 -07006439 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006440 return NO_INIT;
6441 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006442 status_t status = (*mEffectInterface)->command(mEffectInterface,
6443 cmdCode,
6444 cmdSize,
6445 pCmdData,
6446 replySize,
6447 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006448 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006449 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006450 for (size_t i = 1; i < mHandles.size(); i++) {
6451 sp<EffectHandle> h = mHandles[i].promote();
6452 if (h != 0) {
6453 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6454 }
6455 }
6456 }
6457 return status;
6458}
6459
6460status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6461{
Eric Laurent6752ec82011-08-10 10:37:50 -07006462
Eric Laurent65b65452010-06-01 23:49:17 -07006463 Mutex::Autolock _l(mLock);
6464 LOGV("setEnabled %p enabled %d", this, enabled);
6465
6466 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006467 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6468 if (enabled && status != NO_ERROR) {
6469 return status;
6470 }
6471
Eric Laurent65b65452010-06-01 23:49:17 -07006472 switch (mState) {
6473 // going from disabled to enabled
6474 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006475 mState = STARTING;
6476 break;
6477 case STOPPED:
6478 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006479 break;
6480 case STOPPING:
6481 mState = ACTIVE;
6482 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006483
6484 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006485 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006486 mState = STOPPED;
6487 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006488 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006489 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006490 break;
6491 case ACTIVE:
6492 mState = STOPPING;
6493 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006494 case DESTROYED:
6495 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006496 }
6497 for (size_t i = 1; i < mHandles.size(); i++) {
6498 sp<EffectHandle> h = mHandles[i].promote();
6499 if (h != 0) {
6500 h->setEnabled(enabled);
6501 }
6502 }
6503 }
6504 return NO_ERROR;
6505}
6506
6507bool AudioFlinger::EffectModule::isEnabled()
6508{
6509 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006510 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006511 case STARTING:
6512 case ACTIVE:
6513 return true;
6514 case IDLE:
6515 case STOPPING:
6516 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006517 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006518 default:
6519 return false;
6520 }
6521}
6522
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006523bool AudioFlinger::EffectModule::isProcessEnabled()
6524{
6525 switch (mState) {
6526 case RESTART:
6527 case ACTIVE:
6528 case STOPPING:
6529 case STOPPED:
6530 return true;
6531 case IDLE:
6532 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006533 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006534 default:
6535 return false;
6536 }
6537}
6538
Eric Laurent65b65452010-06-01 23:49:17 -07006539status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6540{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006541 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006542 status_t status = NO_ERROR;
6543
6544 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6545 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006546 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006547 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6548 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006549 status_t cmdStatus;
6550 uint32_t volume[2];
6551 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006552 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006553 volume[0] = *left;
6554 volume[1] = *right;
6555 if (controller) {
6556 pVolume = volume;
6557 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006558 status = (*mEffectInterface)->command(mEffectInterface,
6559 EFFECT_CMD_SET_VOLUME,
6560 size,
6561 volume,
6562 &size,
6563 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006564 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6565 *left = volume[0];
6566 *right = volume[1];
6567 }
6568 }
6569 return status;
6570}
6571
6572status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6573{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006574 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006575 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006576 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6577 // audio pre processing modules on RecordThread can receive both output and
6578 // input device indication in the same call
6579 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6580 if (dev) {
6581 status_t cmdStatus;
6582 uint32_t size = sizeof(status_t);
6583
6584 status = (*mEffectInterface)->command(mEffectInterface,
6585 EFFECT_CMD_SET_DEVICE,
6586 sizeof(uint32_t),
6587 &dev,
6588 &size,
6589 &cmdStatus);
6590 if (status == NO_ERROR) {
6591 status = cmdStatus;
6592 }
6593 }
6594 dev = device & AUDIO_DEVICE_IN_ALL;
6595 if (dev) {
6596 status_t cmdStatus;
6597 uint32_t size = sizeof(status_t);
6598
6599 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6600 EFFECT_CMD_SET_INPUT_DEVICE,
6601 sizeof(uint32_t),
6602 &dev,
6603 &size,
6604 &cmdStatus);
6605 if (status2 == NO_ERROR) {
6606 status2 = cmdStatus;
6607 }
6608 if (status == NO_ERROR) {
6609 status = status2;
6610 }
Eric Laurent65b65452010-06-01 23:49:17 -07006611 }
6612 }
6613 return status;
6614}
6615
Eric Laurent53334cd2010-06-23 17:38:20 -07006616status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6617{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006618 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006619 status_t status = NO_ERROR;
6620 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006621 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006622 uint32_t size = sizeof(status_t);
6623 status = (*mEffectInterface)->command(mEffectInterface,
6624 EFFECT_CMD_SET_AUDIO_MODE,
6625 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006626 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006627 &size,
6628 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006629 if (status == NO_ERROR) {
6630 status = cmdStatus;
6631 }
6632 }
6633 return status;
6634}
6635
Eric Laurentf82fccd2011-07-27 19:49:51 -07006636void AudioFlinger::EffectModule::setSuspended(bool suspended)
6637{
6638 Mutex::Autolock _l(mLock);
6639 mSuspended = suspended;
6640}
6641bool AudioFlinger::EffectModule::suspended()
6642{
6643 Mutex::Autolock _l(mLock);
6644 return mSuspended;
6645}
6646
Eric Laurent65b65452010-06-01 23:49:17 -07006647status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6648{
6649 const size_t SIZE = 256;
6650 char buffer[SIZE];
6651 String8 result;
6652
6653 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6654 result.append(buffer);
6655
6656 bool locked = tryLock(mLock);
6657 // failed to lock - AudioFlinger is probably deadlocked
6658 if (!locked) {
6659 result.append("\t\tCould not lock Fx mutex:\n");
6660 }
6661
6662 result.append("\t\tSession Status State Engine:\n");
6663 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6664 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6665 result.append(buffer);
6666
6667 result.append("\t\tDescriptor:\n");
6668 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6669 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6670 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6671 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6672 result.append(buffer);
6673 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6674 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6675 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6676 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6677 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006678 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006679 mDescriptor.apiVersion,
6680 mDescriptor.flags);
6681 result.append(buffer);
6682 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6683 mDescriptor.name);
6684 result.append(buffer);
6685 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6686 mDescriptor.implementor);
6687 result.append(buffer);
6688
6689 result.append("\t\t- Input configuration:\n");
6690 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6691 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6692 (uint32_t)mConfig.inputCfg.buffer.raw,
6693 mConfig.inputCfg.buffer.frameCount,
6694 mConfig.inputCfg.samplingRate,
6695 mConfig.inputCfg.channels,
6696 mConfig.inputCfg.format);
6697 result.append(buffer);
6698
6699 result.append("\t\t- Output configuration:\n");
6700 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6701 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6702 (uint32_t)mConfig.outputCfg.buffer.raw,
6703 mConfig.outputCfg.buffer.frameCount,
6704 mConfig.outputCfg.samplingRate,
6705 mConfig.outputCfg.channels,
6706 mConfig.outputCfg.format);
6707 result.append(buffer);
6708
6709 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6710 result.append(buffer);
6711 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6712 for (size_t i = 0; i < mHandles.size(); ++i) {
6713 sp<EffectHandle> handle = mHandles[i].promote();
6714 if (handle != 0) {
6715 handle->dump(buffer, SIZE);
6716 result.append(buffer);
6717 }
6718 }
6719
6720 result.append("\n");
6721
6722 write(fd, result.string(), result.length());
6723
6724 if (locked) {
6725 mLock.unlock();
6726 }
6727
6728 return NO_ERROR;
6729}
6730
6731// ----------------------------------------------------------------------------
6732// EffectHandle implementation
6733// ----------------------------------------------------------------------------
6734
6735#undef LOG_TAG
6736#define LOG_TAG "AudioFlinger::EffectHandle"
6737
6738AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6739 const sp<AudioFlinger::Client>& client,
6740 const sp<IEffectClient>& effectClient,
6741 int32_t priority)
6742 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006743 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006744 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006745{
6746 LOGV("constructor %p", this);
6747
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006748 if (client == 0) {
6749 return;
6750 }
Eric Laurent65b65452010-06-01 23:49:17 -07006751 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6752 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6753 if (mCblkMemory != 0) {
6754 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6755
6756 if (mCblk) {
6757 new(mCblk) effect_param_cblk_t();
6758 mBuffer = (uint8_t *)mCblk + bufOffset;
6759 }
6760 } else {
6761 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6762 return;
6763 }
6764}
6765
6766AudioFlinger::EffectHandle::~EffectHandle()
6767{
6768 LOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006769 disconnect(false);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006770 LOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006771}
6772
6773status_t AudioFlinger::EffectHandle::enable()
6774{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006775 LOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006776 if (!mHasControl) return INVALID_OPERATION;
6777 if (mEffect == 0) return DEAD_OBJECT;
6778
Eric Laurent6752ec82011-08-10 10:37:50 -07006779 if (mEnabled) {
6780 return NO_ERROR;
6781 }
6782
Eric Laurentf82fccd2011-07-27 19:49:51 -07006783 mEnabled = true;
6784
6785 sp<ThreadBase> thread = mEffect->thread().promote();
6786 if (thread != 0) {
6787 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6788 }
6789
6790 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6791 if (mEffect->suspended()) {
6792 return NO_ERROR;
6793 }
6794
Eric Laurent6752ec82011-08-10 10:37:50 -07006795 status_t status = mEffect->setEnabled(true);
6796 if (status != NO_ERROR) {
6797 if (thread != 0) {
6798 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6799 }
6800 mEnabled = false;
6801 }
6802 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006803}
6804
6805status_t AudioFlinger::EffectHandle::disable()
6806{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006807 LOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006808 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006809 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006810
Eric Laurent6752ec82011-08-10 10:37:50 -07006811 if (!mEnabled) {
6812 return NO_ERROR;
6813 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006814 mEnabled = false;
6815
6816 if (mEffect->suspended()) {
6817 return NO_ERROR;
6818 }
6819
6820 status_t status = mEffect->setEnabled(false);
6821
6822 sp<ThreadBase> thread = mEffect->thread().promote();
6823 if (thread != 0) {
6824 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6825 }
6826
6827 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006828}
6829
6830void AudioFlinger::EffectHandle::disconnect()
6831{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006832 disconnect(true);
6833}
6834
6835void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6836{
6837 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006838 if (mEffect == 0) {
6839 return;
6840 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006841 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006842
Eric Laurent6752ec82011-08-10 10:37:50 -07006843 if (mEnabled) {
6844 sp<ThreadBase> thread = mEffect->thread().promote();
6845 if (thread != 0) {
6846 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6847 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006848 }
6849
Eric Laurent65b65452010-06-01 23:49:17 -07006850 // release sp on module => module destructor can be called now
6851 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006852 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006853 if (mCblk) {
6854 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6855 }
6856 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006857 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6858 mClient.clear();
6859 }
6860}
6861
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006862status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6863 uint32_t cmdSize,
6864 void *pCmdData,
6865 uint32_t *replySize,
6866 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006867{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006868// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6869// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006870
6871 // only get parameter command is permitted for applications not controlling the effect
6872 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6873 return INVALID_OPERATION;
6874 }
6875 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006876 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006877
6878 // handle commands that are not forwarded transparently to effect engine
6879 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6880 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6881 // no risk to block the whole media server process or mixer threads is we are stuck here
6882 Mutex::Autolock _l(mCblk->lock);
6883 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6884 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6885 mCblk->serverIndex = 0;
6886 mCblk->clientIndex = 0;
6887 return BAD_VALUE;
6888 }
6889 status_t status = NO_ERROR;
6890 while (mCblk->serverIndex < mCblk->clientIndex) {
6891 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006892 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006893 int *p = (int *)(mBuffer + mCblk->serverIndex);
6894 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006895 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6896 LOGW("command(): invalid parameter block size");
6897 break;
6898 }
Eric Laurent65b65452010-06-01 23:49:17 -07006899 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006900 if (param->psize == 0 || param->vsize == 0) {
6901 LOGW("command(): null parameter or value size");
6902 mCblk->serverIndex += size;
6903 continue;
6904 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006905 uint32_t psize = sizeof(effect_param_t) +
6906 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6907 param->vsize;
6908 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6909 psize,
6910 p,
6911 &rsize,
6912 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006913 // stop at first error encountered
6914 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006915 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006916 *(int *)pReplyData = reply;
6917 break;
6918 } else if (reply != NO_ERROR) {
6919 *(int *)pReplyData = reply;
6920 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006921 }
6922 mCblk->serverIndex += size;
6923 }
6924 mCblk->serverIndex = 0;
6925 mCblk->clientIndex = 0;
6926 return status;
6927 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006928 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006929 return enable();
6930 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006931 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006932 return disable();
6933 }
6934
6935 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6936}
6937
6938sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6939 return mCblkMemory;
6940}
6941
Eric Laurentf82fccd2011-07-27 19:49:51 -07006942void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07006943{
6944 LOGV("setControl %p control %d", this, hasControl);
6945
6946 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006947 mEnabled = enabled;
6948
Eric Laurent65b65452010-06-01 23:49:17 -07006949 if (signal && mEffectClient != 0) {
6950 mEffectClient->controlStatusChanged(hasControl);
6951 }
6952}
6953
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006954void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6955 uint32_t cmdSize,
6956 void *pCmdData,
6957 uint32_t replySize,
6958 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006959{
6960 if (mEffectClient != 0) {
6961 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6962 }
6963}
6964
6965
6966
6967void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6968{
6969 if (mEffectClient != 0) {
6970 mEffectClient->enableStatusChanged(enabled);
6971 }
6972}
6973
6974status_t AudioFlinger::EffectHandle::onTransact(
6975 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6976{
6977 return BnEffect::onTransact(code, data, reply, flags);
6978}
6979
6980
6981void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6982{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006983 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07006984
6985 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6986 (mClient == NULL) ? getpid() : mClient->pid(),
6987 mPriority,
6988 mHasControl,
6989 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006990 mCblk ? mCblk->clientIndex : 0,
6991 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07006992 );
6993
6994 if (locked) {
6995 mCblk->lock.unlock();
6996 }
6997}
6998
6999#undef LOG_TAG
7000#define LOG_TAG "AudioFlinger::EffectChain"
7001
7002AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7003 int sessionId)
Eric Laurent90681d62011-05-09 12:09:06 -07007004 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
7005 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7006 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007007{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007008 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07007009}
7010
7011AudioFlinger::EffectChain::~EffectChain()
7012{
7013 if (mOwnInBuffer) {
7014 delete mInBuffer;
7015 }
7016
7017}
7018
Eric Laurentf82fccd2011-07-27 19:49:51 -07007019// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007020sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007021{
7022 sp<EffectModule> effect;
7023 size_t size = mEffects.size();
7024
7025 for (size_t i = 0; i < size; i++) {
7026 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7027 effect = mEffects[i];
7028 break;
7029 }
7030 }
7031 return effect;
7032}
7033
Eric Laurentf82fccd2011-07-27 19:49:51 -07007034// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007035sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007036{
7037 sp<EffectModule> effect;
7038 size_t size = mEffects.size();
7039
7040 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007041 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7042 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007043 effect = mEffects[i];
7044 break;
7045 }
7046 }
7047 return effect;
7048}
7049
Eric Laurentf82fccd2011-07-27 19:49:51 -07007050// getEffectFromType_l() must be called with ThreadBase::mLock held
7051sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7052 const effect_uuid_t *type)
7053{
7054 sp<EffectModule> effect;
7055 size_t size = mEffects.size();
7056
7057 for (size_t i = 0; i < size; i++) {
7058 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7059 effect = mEffects[i];
7060 break;
7061 }
7062 }
7063 return effect;
7064}
7065
Eric Laurent65b65452010-06-01 23:49:17 -07007066// Must be called with EffectChain::mLock locked
7067void AudioFlinger::EffectChain::process_l()
7068{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007069 sp<ThreadBase> thread = mThread.promote();
7070 if (thread == 0) {
7071 LOGW("process_l(): cannot promote mixer thread");
7072 return;
7073 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007074 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7075 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007076 bool tracksOnSession = false;
7077 if (!isGlobalSession) {
Eric Laurent90681d62011-05-09 12:09:06 -07007078 tracksOnSession = (trackCnt() != 0);
7079 }
7080
7081 // if no track is active, input buffer must be cleared here as the mixer process
7082 // will not do it
7083 if (tracksOnSession &&
7084 activeTrackCnt() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07007085 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurent90681d62011-05-09 12:09:06 -07007086 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007087 }
7088
Eric Laurent65b65452010-06-01 23:49:17 -07007089 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007090 // do not process effect if no track is present in same audio session
7091 if (isGlobalSession || tracksOnSession) {
7092 for (size_t i = 0; i < size; i++) {
7093 mEffects[i]->process();
7094 }
Eric Laurent65b65452010-06-01 23:49:17 -07007095 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007096 for (size_t i = 0; i < size; i++) {
7097 mEffects[i]->updateState();
7098 }
Eric Laurent65b65452010-06-01 23:49:17 -07007099}
7100
Eric Laurent76c40f72010-07-15 12:50:15 -07007101// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007102status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007103{
7104 effect_descriptor_t desc = effect->desc();
7105 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7106
7107 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007108 effect->setChain(this);
7109 sp<ThreadBase> thread = mThread.promote();
7110 if (thread == 0) {
7111 return NO_INIT;
7112 }
7113 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007114
7115 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7116 // Auxiliary effects are inserted at the beginning of mEffects vector as
7117 // they are processed first and accumulated in chain input buffer
7118 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007119
Eric Laurent65b65452010-06-01 23:49:17 -07007120 // the input buffer for auxiliary effect contains mono samples in
7121 // 32 bit format. This is to avoid saturation in AudoMixer
7122 // accumulation stage. Saturation is done in EffectModule::process() before
7123 // calling the process in effect engine
7124 size_t numSamples = thread->frameCount();
7125 int32_t *buffer = new int32_t[numSamples];
7126 memset(buffer, 0, numSamples * sizeof(int32_t));
7127 effect->setInBuffer((int16_t *)buffer);
7128 // auxiliary effects output samples to chain input buffer for further processing
7129 // by insert effects
7130 effect->setOutBuffer(mInBuffer);
7131 } else {
7132 // Insert effects are inserted at the end of mEffects vector as they are processed
7133 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007134 // Insert effect order as a function of indicated preference:
7135 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7136 // another effect is present
7137 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7138 // last effect claiming first position
7139 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7140 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007141 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007142 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7143 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007144
7145 int size = (int)mEffects.size();
7146 int idx_insert = size;
7147 int idx_insert_first = -1;
7148 int idx_insert_last = -1;
7149
7150 for (int i = 0; i < size; i++) {
7151 effect_descriptor_t d = mEffects[i]->desc();
7152 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7153 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7154 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7155 // check invalid effect chaining combinations
7156 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007157 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007158 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007159 return INVALID_OPERATION;
7160 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007161 // remember position of first insert effect and by default
7162 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007163 if (idx_insert == size) {
7164 idx_insert = i;
7165 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007166 // remember position of last insert effect claiming
7167 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007168 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7169 idx_insert_first = i;
7170 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007171 // remember position of first insert effect claiming
7172 // last position
7173 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7174 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007175 idx_insert_last = i;
7176 }
7177 }
7178 }
7179
Eric Laurent53334cd2010-06-23 17:38:20 -07007180 // modify idx_insert from first position if needed
7181 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7182 if (idx_insert_last != -1) {
7183 idx_insert = idx_insert_last;
7184 } else {
7185 idx_insert = size;
7186 }
7187 } else {
7188 if (idx_insert_first != -1) {
7189 idx_insert = idx_insert_first + 1;
7190 }
Eric Laurent65b65452010-06-01 23:49:17 -07007191 }
7192
7193 // always read samples from chain input buffer
7194 effect->setInBuffer(mInBuffer);
7195
7196 // if last effect in the chain, output samples to chain
7197 // output buffer, otherwise to chain input buffer
7198 if (idx_insert == size) {
7199 if (idx_insert != 0) {
7200 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7201 mEffects[idx_insert-1]->configure();
7202 }
7203 effect->setOutBuffer(mOutBuffer);
7204 } else {
7205 effect->setOutBuffer(mInBuffer);
7206 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007207 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007208
Eric Laurent76c40f72010-07-15 12:50:15 -07007209 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007210 }
7211 effect->configure();
7212 return NO_ERROR;
7213}
7214
Eric Laurent76c40f72010-07-15 12:50:15 -07007215// removeEffect_l() must be called with PlaybackThread::mLock held
7216size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007217{
7218 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007219 int size = (int)mEffects.size();
7220 int i;
7221 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7222
7223 for (i = 0; i < size; i++) {
7224 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007225 // calling stop here will remove pre-processing effect from the audio HAL.
7226 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7227 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007228 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7229 mEffects[i]->state() == EffectModule::STOPPING) {
7230 mEffects[i]->stop();
7231 }
Eric Laurent65b65452010-06-01 23:49:17 -07007232 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7233 delete[] effect->inBuffer();
7234 } else {
7235 if (i == size - 1 && i != 0) {
7236 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7237 mEffects[i - 1]->configure();
7238 }
7239 }
7240 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07007241 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007242 break;
7243 }
7244 }
Eric Laurent65b65452010-06-01 23:49:17 -07007245
7246 return mEffects.size();
7247}
7248
Eric Laurent76c40f72010-07-15 12:50:15 -07007249// setDevice_l() must be called with PlaybackThread::mLock held
7250void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007251{
7252 size_t size = mEffects.size();
7253 for (size_t i = 0; i < size; i++) {
7254 mEffects[i]->setDevice(device);
7255 }
7256}
7257
Eric Laurent76c40f72010-07-15 12:50:15 -07007258// setMode_l() must be called with PlaybackThread::mLock held
7259void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007260{
7261 size_t size = mEffects.size();
7262 for (size_t i = 0; i < size; i++) {
7263 mEffects[i]->setMode(mode);
7264 }
7265}
7266
Eric Laurent76c40f72010-07-15 12:50:15 -07007267// setVolume_l() must be called with PlaybackThread::mLock held
7268bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007269{
7270 uint32_t newLeft = *left;
7271 uint32_t newRight = *right;
7272 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007273 int ctrlIdx = -1;
7274 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007275
Eric Laurent76c40f72010-07-15 12:50:15 -07007276 // first update volume controller
7277 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007278 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007279 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7280 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007281 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007282 break;
7283 }
7284 }
7285
7286 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007287 if (hasControl) {
7288 *left = mNewLeftVolume;
7289 *right = mNewRightVolume;
7290 }
7291 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007292 }
7293
7294 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007295 mLeftVolume = newLeft;
7296 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007297
7298 // second get volume update from volume controller
7299 if (ctrlIdx >= 0) {
7300 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007301 mNewLeftVolume = newLeft;
7302 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007303 }
7304 // then indicate volume to all other effects in chain.
7305 // Pass altered volume to effects before volume controller
7306 // and requested volume to effects after controller
7307 uint32_t lVol = newLeft;
7308 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007309
Eric Laurent65b65452010-06-01 23:49:17 -07007310 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007311 if ((int)i == ctrlIdx) continue;
7312 // this also works for ctrlIdx == -1 when there is no volume controller
7313 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007314 lVol = *left;
7315 rVol = *right;
7316 }
7317 mEffects[i]->setVolume(&lVol, &rVol, false);
7318 }
7319 *left = newLeft;
7320 *right = newRight;
7321
7322 return hasControl;
7323}
7324
Eric Laurent65b65452010-06-01 23:49:17 -07007325status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7326{
7327 const size_t SIZE = 256;
7328 char buffer[SIZE];
7329 String8 result;
7330
7331 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7332 result.append(buffer);
7333
7334 bool locked = tryLock(mLock);
7335 // failed to lock - AudioFlinger is probably deadlocked
7336 if (!locked) {
7337 result.append("\tCould not lock mutex:\n");
7338 }
7339
Eric Laurent76c40f72010-07-15 12:50:15 -07007340 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7341 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007342 mEffects.size(),
7343 (uint32_t)mInBuffer,
7344 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007345 mActiveTrackCnt);
7346 result.append(buffer);
7347 write(fd, result.string(), result.size());
7348
7349 for (size_t i = 0; i < mEffects.size(); ++i) {
7350 sp<EffectModule> effect = mEffects[i];
7351 if (effect != 0) {
7352 effect->dump(fd, args);
7353 }
7354 }
7355
7356 if (locked) {
7357 mLock.unlock();
7358 }
7359
7360 return NO_ERROR;
7361}
7362
Eric Laurentf82fccd2011-07-27 19:49:51 -07007363// must be called with ThreadBase::mLock held
7364void AudioFlinger::EffectChain::setEffectSuspended_l(
7365 const effect_uuid_t *type, bool suspend)
7366{
7367 sp<SuspendedEffectDesc> desc;
7368 // use effect type UUID timelow as key as there is no real risk of identical
7369 // timeLow fields among effect type UUIDs.
7370 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7371 if (suspend) {
7372 if (index >= 0) {
7373 desc = mSuspendedEffects.valueAt(index);
7374 } else {
7375 desc = new SuspendedEffectDesc();
7376 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7377 mSuspendedEffects.add(type->timeLow, desc);
7378 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7379 }
7380 if (desc->mRefCount++ == 0) {
7381 sp<EffectModule> effect = getEffectIfEnabled(type);
7382 if (effect != 0) {
7383 desc->mEffect = effect;
7384 effect->setSuspended(true);
7385 effect->setEnabled(false);
7386 }
7387 }
7388 } else {
7389 if (index < 0) {
7390 return;
7391 }
7392 desc = mSuspendedEffects.valueAt(index);
7393 if (desc->mRefCount <= 0) {
7394 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7395 desc->mRefCount = 1;
7396 }
7397 if (--desc->mRefCount == 0) {
7398 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7399 if (desc->mEffect != 0) {
7400 sp<EffectModule> effect = desc->mEffect.promote();
7401 if (effect != 0) {
7402 effect->setSuspended(false);
7403 sp<EffectHandle> handle = effect->controlHandle();
7404 if (handle != 0) {
7405 effect->setEnabled(handle->enabled());
7406 }
7407 }
7408 desc->mEffect.clear();
7409 }
7410 mSuspendedEffects.removeItemsAt(index);
7411 }
7412 }
7413}
7414
7415// must be called with ThreadBase::mLock held
7416void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7417{
7418 sp<SuspendedEffectDesc> desc;
7419
7420 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7421 if (suspend) {
7422 if (index >= 0) {
7423 desc = mSuspendedEffects.valueAt(index);
7424 } else {
7425 desc = new SuspendedEffectDesc();
7426 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7427 LOGV("setEffectSuspendedAll_l() add entry for 0");
7428 }
7429 if (desc->mRefCount++ == 0) {
7430 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7431 for (size_t i = 0; i < effects.size(); i++) {
7432 setEffectSuspended_l(&effects[i]->desc().type, true);
7433 }
7434 }
7435 } else {
7436 if (index < 0) {
7437 return;
7438 }
7439 desc = mSuspendedEffects.valueAt(index);
7440 if (desc->mRefCount <= 0) {
7441 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7442 desc->mRefCount = 1;
7443 }
7444 if (--desc->mRefCount == 0) {
7445 Vector<const effect_uuid_t *> types;
7446 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7447 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7448 continue;
7449 }
7450 types.add(&mSuspendedEffects.valueAt(i)->mType);
7451 }
7452 for (size_t i = 0; i < types.size(); i++) {
7453 setEffectSuspended_l(types[i], false);
7454 }
7455 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7456 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7457 }
7458 }
7459}
7460
Eric Laurent5e7acae2011-09-23 08:40:41 -07007461
7462// The volume effect is used for automated tests only
7463#ifndef OPENSL_ES_H_
7464static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7465 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7466const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7467#endif //OPENSL_ES_H_
7468
Eric Laurent6752ec82011-08-10 10:37:50 -07007469bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7470{
7471 // auxiliary effects and visualizer are never suspended on output mix
7472 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7473 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007474 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7475 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007476 return false;
7477 }
7478 return true;
7479}
7480
Eric Laurentf82fccd2011-07-27 19:49:51 -07007481Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7482{
7483 Vector< sp<EffectModule> > effects;
7484 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007485 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007486 continue;
7487 }
7488 effects.add(mEffects[i]);
7489 }
7490 return effects;
7491}
7492
7493sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7494 const effect_uuid_t *type)
7495{
7496 sp<EffectModule> effect;
7497 effect = getEffectFromType_l(type);
7498 if (effect != 0 && !effect->isEnabled()) {
7499 effect.clear();
7500 }
7501 return effect;
7502}
7503
7504void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7505 bool enabled)
7506{
7507 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7508 if (enabled) {
7509 if (index < 0) {
7510 // if the effect is not suspend check if all effects are suspended
7511 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7512 if (index < 0) {
7513 return;
7514 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007515 if (!isEffectEligibleForSuspend(effect->desc())) {
7516 return;
7517 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007518 setEffectSuspended_l(&effect->desc().type, enabled);
7519 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007520 if (index < 0) {
7521 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7522 return;
7523 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007524 }
7525 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7526 effect->desc().type.timeLow);
7527 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7528 // if effect is requested to suspended but was not yet enabled, supend it now.
7529 if (desc->mEffect == 0) {
7530 desc->mEffect = effect;
7531 effect->setEnabled(false);
7532 effect->setSuspended(true);
7533 }
7534 } else {
7535 if (index < 0) {
7536 return;
7537 }
7538 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7539 effect->desc().type.timeLow);
7540 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7541 desc->mEffect.clear();
7542 effect->setSuspended(false);
7543 }
7544}
7545
Eric Laurent65b65452010-06-01 23:49:17 -07007546#undef LOG_TAG
7547#define LOG_TAG "AudioFlinger"
7548
Eric Laurenta553c252009-07-17 12:17:14 -07007549// ----------------------------------------------------------------------------
7550
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007551status_t AudioFlinger::onTransact(
7552 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7553{
7554 return BnAudioFlinger::onTransact(code, data, reply, flags);
7555}
7556
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007557}; // namespace android