blob: 0dc1eb89fdd2703856215106e252cb7f335e13b9 [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 Laurent65b65452010-06-01 23:49:17 -070054
Glenn Kastenda494f92011-07-08 15:26:12 -070055#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070056#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070057// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
58
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Eric Laurent8ed6ed02010-07-13 04:45:46 -070061
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062namespace android {
63
The Android Open Source Project10592532009-03-18 17:39:46 -070064static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
65static const char* kHardwareLockedString = "Hardware lock is taken\n";
66
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080067//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070068static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070069static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070
71// retry counts for buffer fill timeout
72// 50 * ~20msecs = 1 second
73static const int8_t kMaxTrackRetries = 50;
74static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080075// allow less retry attempts on direct output thread.
76// direct outputs can be a scarce resource in audio hardware and should
77// be released as quickly as possible.
78static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070079
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070080static const int kDumpLockRetries = 50;
81static const int kDumpLockSleep = 20000;
82
Dave Sparksd0ac8c02009-09-30 03:09:03 -070083static const nsecs_t kWarningThrottle = seconds(5);
84
Eric Laurent464d5b32011-06-17 21:29:58 -070085// RecordThread loop sleep time upon application overrun or audio HAL read error
86static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070088// ----------------------------------------------------------------------------
89
90static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070091 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
92 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
93 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
94 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070095}
96
97static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070098 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
99 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
100 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
101 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102}
103
Gloria Wang9b3f1522011-02-24 14:51:45 -0800104// To collect the amplifier usage
105static void addBatteryData(uint32_t params) {
106 sp<IBinder> binder =
107 defaultServiceManager()->getService(String16("media.player"));
108 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
109 if (service.get() == NULL) {
110 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
111 return;
112 }
113
114 service->addBatteryData(params);
115}
116
Dima Zavin31f188892011-04-18 16:57:27 -0700117static int load_audio_interface(const char *if_name, const hw_module_t **mod,
118 audio_hw_device_t **dev)
119{
120 int rc;
121
122 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
123 if (rc)
124 goto out;
125
126 rc = audio_hw_device_open(*mod, dev);
127 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
128 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
129 if (rc)
130 goto out;
131
132 return 0;
133
134out:
135 *mod = NULL;
136 *dev = NULL;
137 return rc;
138}
139
140static const char *audio_interfaces[] = {
141 "primary",
142 "a2dp",
143 "usb",
144};
145#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
146
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700147// ----------------------------------------------------------------------------
148
149AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 : BnAudioFlinger(),
Dima Zavin31f188892011-04-18 16:57:27 -0700151 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700152{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700153}
154
155void AudioFlinger::onFirstRef()
156{
Dima Zavin31f188892011-04-18 16:57:27 -0700157 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700158
Eric Laurent01635942011-01-18 18:39:02 -0800159 Mutex::Autolock _l(mLock);
160
Dima Zavin31f188892011-04-18 16:57:27 -0700161 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700162 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700163
Dima Zavin31f188892011-04-18 16:57:27 -0700164 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
165 const hw_module_t *mod;
166 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700167
Dima Zavin31f188892011-04-18 16:57:27 -0700168 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
169 if (rc)
170 continue;
171
172 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
173 mod->name, mod->id);
174 mAudioHwDevs.push(dev);
175
176 if (!mPrimaryHardwareDev) {
177 mPrimaryHardwareDev = dev;
178 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700179 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700180 }
181 }
Eric Laurenta553c252009-07-17 12:17:14 -0700182
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700183 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700184
Dima Zavin31f188892011-04-18 16:57:27 -0700185 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
186 LOGE("Primary audio interface not found");
187 return;
188 }
189
190 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
191 audio_hw_device_t *dev = mAudioHwDevs[i];
192
193 mHardwareStatus = AUDIO_HW_INIT;
194 rc = dev->init_check(dev);
195 if (rc == 0) {
196 AutoMutex lock(mHardwareLock);
197
198 mMode = AUDIO_MODE_NORMAL;
199 mHardwareStatus = AUDIO_HW_SET_MODE;
200 dev->set_mode(dev, mMode);
201 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
202 dev->set_master_volume(dev, 1.0f);
203 mHardwareStatus = AUDIO_HW_IDLE;
204 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700205 }
206}
207
Dima Zavin2986f5b2011-04-19 19:04:32 -0700208status_t AudioFlinger::initCheck() const
209{
210 Mutex::Autolock _l(mLock);
211 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
212 return NO_INIT;
213 return NO_ERROR;
214}
215
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700216AudioFlinger::~AudioFlinger()
217{
Dima Zavin31f188892011-04-18 16:57:27 -0700218 int num_devs = mAudioHwDevs.size();
219
Eric Laurent7954c462009-08-28 10:39:03 -0700220 while (!mRecordThreads.isEmpty()) {
221 // closeInput() will remove first entry from mRecordThreads
222 closeInput(mRecordThreads.keyAt(0));
223 }
224 while (!mPlaybackThreads.isEmpty()) {
225 // closeOutput() will remove first entry from mPlaybackThreads
226 closeOutput(mPlaybackThreads.keyAt(0));
227 }
Dima Zavin31f188892011-04-18 16:57:27 -0700228
229 for (int i = 0; i < num_devs; i++) {
230 audio_hw_device_t *dev = mAudioHwDevs[i];
231 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700232 }
Dima Zavin31f188892011-04-18 16:57:27 -0700233 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800234}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800235
Dima Zavin31f188892011-04-18 16:57:27 -0700236audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
237{
238 /* first matching HW device is returned */
239 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
240 audio_hw_device_t *dev = mAudioHwDevs[i];
241 if ((dev->get_supported_devices(dev) & devices) == devices)
242 return dev;
243 }
244 return NULL;
245}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700246
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700247status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
248{
249 const size_t SIZE = 256;
250 char buffer[SIZE];
251 String8 result;
252
253 result.append("Clients:\n");
254 for (size_t i = 0; i < mClients.size(); ++i) {
255 wp<Client> wClient = mClients.valueAt(i);
256 if (wClient != 0) {
257 sp<Client> client = wClient.promote();
258 if (client != 0) {
259 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
260 result.append(buffer);
261 }
262 }
263 }
264 write(fd, result.string(), result.size());
265 return NO_ERROR;
266}
267
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700268
269status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
270{
271 const size_t SIZE = 256;
272 char buffer[SIZE];
273 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700274 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700275
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700276 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700277 result.append(buffer);
278 write(fd, result.string(), result.size());
279 return NO_ERROR;
280}
281
282status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287 snprintf(buffer, SIZE, "Permission Denial: "
288 "can't dump AudioFlinger from pid=%d, uid=%d\n",
289 IPCThreadState::self()->getCallingPid(),
290 IPCThreadState::self()->getCallingUid());
291 result.append(buffer);
292 write(fd, result.string(), result.size());
293 return NO_ERROR;
294}
295
The Android Open Source Project10592532009-03-18 17:39:46 -0700296static bool tryLock(Mutex& mutex)
297{
298 bool locked = false;
299 for (int i = 0; i < kDumpLockRetries; ++i) {
300 if (mutex.tryLock() == NO_ERROR) {
301 locked = true;
302 break;
303 }
304 usleep(kDumpLockSleep);
305 }
306 return locked;
307}
308
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700309status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
310{
311 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
312 dumpPermissionDenial(fd, args);
313 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700314 // get state of hardware lock
315 bool hardwareLocked = tryLock(mHardwareLock);
316 if (!hardwareLocked) {
317 String8 result(kHardwareLockedString);
318 write(fd, result.string(), result.size());
319 } else {
320 mHardwareLock.unlock();
321 }
322
323 bool locked = tryLock(mLock);
324
325 // failed to lock - AudioFlinger is probably deadlocked
326 if (!locked) {
327 String8 result(kDeadlockedString);
328 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700329 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700330
331 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333
Eric Laurenta553c252009-07-17 12:17:14 -0700334 // dump playback threads
335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700336 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700337 }
338
339 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700340 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700341 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343
Dima Zavin31f188892011-04-18 16:57:27 -0700344 // dump all hardware devs
345 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
346 audio_hw_device_t *dev = mAudioHwDevs[i];
347 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700348 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700349 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700350 }
351 return NO_ERROR;
352}
353
Eric Laurenta553c252009-07-17 12:17:14 -0700354
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700355// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
357
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700358sp<IAudioTrack> AudioFlinger::createTrack(
359 pid_t pid,
360 int streamType,
361 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700362 uint32_t format,
363 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800364 int frameCount,
365 uint32_t flags,
366 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700367 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700368 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800369 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370{
Eric Laurenta553c252009-07-17 12:17:14 -0700371 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700372 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800374 wp<Client> wclient;
375 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700376 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700377
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700378 if (streamType >= AUDIO_STREAM_CNT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800379 LOGE("invalid stream type");
380 lStatus = BAD_VALUE;
381 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700382 }
383
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800384 {
385 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700386 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700387 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700388 if (thread == NULL) {
389 LOGE("unknown output thread");
390 lStatus = BAD_VALUE;
391 goto Exit;
392 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800393
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800394 wclient = mClients.valueFor(pid);
395
396 if (wclient != NULL) {
397 client = wclient.promote();
398 } else {
399 client = new Client(this, pid);
400 mClients.add(pid, client);
401 }
Eric Laurent65b65452010-06-01 23:49:17 -0700402
Eric Laurent65b65452010-06-01 23:49:17 -0700403 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700404 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700406 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
407 if (mPlaybackThreads.keyAt(i) != output) {
408 // prevent same audio session on different output threads
409 uint32_t sessions = t->hasAudioSession(*sessionId);
410 if (sessions & PlaybackThread::TRACK_SESSION) {
411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
414 // check if an effect with same session ID is waiting for a track to be created
415 if (sessions & PlaybackThread::EFFECT_SESSION) {
416 effectThread = t.get();
417 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700418 }
419 }
Eric Laurent65b65452010-06-01 23:49:17 -0700420 lSessionId = *sessionId;
421 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700422 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700423 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700424 if (sessionId != NULL) {
425 *sessionId = lSessionId;
426 }
427 }
428 LOGV("createTrack() lSessionId: %d", lSessionId);
429
Eric Laurenta553c252009-07-17 12:17:14 -0700430 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700431 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700432
433 // move effect chain to this output thread if an effect on same session was waiting
434 // for a track to be created
435 if (lStatus == NO_ERROR && effectThread != NULL) {
436 Mutex::Autolock _dl(thread->mLock);
437 Mutex::Autolock _sl(effectThread->mLock);
438 moveEffectChain_l(lSessionId, effectThread, thread, true);
439 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700440 }
441 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800442 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700443 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700444 // remove local strong reference to Client before deleting the Track so that the Client
445 // destructor is called by the TrackBase destructor with mLock held
446 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700447 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800448 }
449
450Exit:
451 if(status) {
452 *status = lStatus;
453 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700454 return trackHandle;
455}
456
Eric Laurentddb78e72009-07-28 08:44:33 -0700457uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700458{
Eric Laurenta553c252009-07-17 12:17:14 -0700459 Mutex::Autolock _l(mLock);
460 PlaybackThread *thread = checkPlaybackThread_l(output);
461 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700462 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700463 return 0;
464 }
465 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700466}
467
Eric Laurentddb78e72009-07-28 08:44:33 -0700468int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700469{
Eric Laurenta553c252009-07-17 12:17:14 -0700470 Mutex::Autolock _l(mLock);
471 PlaybackThread *thread = checkPlaybackThread_l(output);
472 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700473 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700474 return 0;
475 }
476 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700477}
478
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700479uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700480{
Eric Laurenta553c252009-07-17 12:17:14 -0700481 Mutex::Autolock _l(mLock);
482 PlaybackThread *thread = checkPlaybackThread_l(output);
483 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700484 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700485 return 0;
486 }
487 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700488}
489
Eric Laurentddb78e72009-07-28 08:44:33 -0700490size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700491{
Eric Laurenta553c252009-07-17 12:17:14 -0700492 Mutex::Autolock _l(mLock);
493 PlaybackThread *thread = checkPlaybackThread_l(output);
494 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700495 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700496 return 0;
497 }
498 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700499}
500
Eric Laurentddb78e72009-07-28 08:44:33 -0700501uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800502{
Eric Laurenta553c252009-07-17 12:17:14 -0700503 Mutex::Autolock _l(mLock);
504 PlaybackThread *thread = checkPlaybackThread_l(output);
505 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700506 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700507 return 0;
508 }
509 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800510}
511
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512status_t AudioFlinger::setMasterVolume(float value)
513{
514 // check calling permissions
515 if (!settingsAllowed()) {
516 return PERMISSION_DENIED;
517 }
518
519 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800520 { // scope for the lock
521 AutoMutex lock(mHardwareLock);
522 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700523 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800524 value = 1.0f;
525 }
526 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700527 }
Eric Laurenta553c252009-07-17 12:17:14 -0700528
Eric Laurent01635942011-01-18 18:39:02 -0800529 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700530 mMasterVolume = value;
531 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700532 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700533
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700534 return NO_ERROR;
535}
536
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700537status_t AudioFlinger::setMode(int mode)
538{
Eric Laurent53334cd2010-06-23 17:38:20 -0700539 status_t ret;
540
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700541 // check calling permissions
542 if (!settingsAllowed()) {
543 return PERMISSION_DENIED;
544 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700545 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700546 LOGW("Illegal value: setMode(%d)", mode);
547 return BAD_VALUE;
548 }
549
Eric Laurent53334cd2010-06-23 17:38:20 -0700550 { // scope for the lock
551 AutoMutex lock(mHardwareLock);
552 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700553 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700554 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800555 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700556
557 if (NO_ERROR == ret) {
558 Mutex::Autolock _l(mLock);
559 mMode = mode;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
561 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700562 }
563
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700564 return ret;
565}
566
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700567status_t AudioFlinger::setMicMute(bool state)
568{
569 // check calling permissions
570 if (!settingsAllowed()) {
571 return PERMISSION_DENIED;
572 }
573
574 AutoMutex lock(mHardwareLock);
575 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700576 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700577 mHardwareStatus = AUDIO_HW_IDLE;
578 return ret;
579}
580
581bool AudioFlinger::getMicMute() const
582{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700583 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700584 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700585 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
587 return state;
588}
589
590status_t AudioFlinger::setMasterMute(bool muted)
591{
592 // check calling permissions
593 if (!settingsAllowed()) {
594 return PERMISSION_DENIED;
595 }
Eric Laurenta553c252009-07-17 12:17:14 -0700596
Eric Laurent01635942011-01-18 18:39:02 -0800597 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700598 mMasterMute = muted;
599 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700600 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700601
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700602 return NO_ERROR;
603}
604
605float AudioFlinger::masterVolume() const
606{
Eric Laurenta553c252009-07-17 12:17:14 -0700607 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700608}
609
610bool AudioFlinger::masterMute() const
611{
Eric Laurenta553c252009-07-17 12:17:14 -0700612 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700613}
614
Eric Laurentddb78e72009-07-28 08:44:33 -0700615status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700616{
617 // check calling permissions
618 if (!settingsAllowed()) {
619 return PERMISSION_DENIED;
620 }
621
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700622 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700623 return BAD_VALUE;
624 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800625
Eric Laurenta553c252009-07-17 12:17:14 -0700626 AutoMutex lock(mLock);
627 PlaybackThread *thread = NULL;
628 if (output) {
629 thread = checkPlaybackThread_l(output);
630 if (thread == NULL) {
631 return BAD_VALUE;
632 }
633 }
634
Eric Laurenta553c252009-07-17 12:17:14 -0700635 mStreamTypes[stream].volume = value;
636
637 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700639 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700640 }
Eric Laurenta553c252009-07-17 12:17:14 -0700641 } else {
642 thread->setStreamVolume(stream, value);
643 }
Eric Laurentef028272009-04-21 07:56:33 -0700644
Eric Laurent415f3e22009-10-21 08:14:22 -0700645 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700646}
647
648status_t AudioFlinger::setStreamMute(int stream, bool muted)
649{
650 // check calling permissions
651 if (!settingsAllowed()) {
652 return PERMISSION_DENIED;
653 }
654
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700655 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
656 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700657 return BAD_VALUE;
658 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700659
Eric Laurent01635942011-01-18 18:39:02 -0800660 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700661 mStreamTypes[stream].mute = muted;
662 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700663 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700665 return NO_ERROR;
666}
667
Eric Laurentddb78e72009-07-28 08:44:33 -0700668float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700669{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700670 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700671 return 0.0f;
672 }
Eric Laurenta553c252009-07-17 12:17:14 -0700673
674 AutoMutex lock(mLock);
675 float volume;
676 if (output) {
677 PlaybackThread *thread = checkPlaybackThread_l(output);
678 if (thread == NULL) {
679 return 0.0f;
680 }
681 volume = thread->streamVolume(stream);
682 } else {
683 volume = mStreamTypes[stream].volume;
684 }
685
Eric Laurentef028272009-04-21 07:56:33 -0700686 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700687}
688
689bool AudioFlinger::streamMute(int stream) const
690{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700691 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700692 return true;
693 }
Eric Laurenta553c252009-07-17 12:17:14 -0700694
695 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700696}
697
Eric Laurentddb78e72009-07-28 08:44:33 -0700698status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700699{
Eric Laurenta553c252009-07-17 12:17:14 -0700700 status_t result;
701
Eric Laurentddb78e72009-07-28 08:44:33 -0700702 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700703 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
704 // check calling permissions
705 if (!settingsAllowed()) {
706 return PERMISSION_DENIED;
The Android Open Source Project9266c5582009-01-15 16:12:10 -0800707 }
Eric Laurenta553c252009-07-17 12:17:14 -0700708
709 // ioHandle == 0 means the parameters are global to the audio hardware interface
710 if (ioHandle == 0) {
711 AutoMutex lock(mHardwareLock);
712 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700713 status_t final_result = NO_ERROR;
714 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
715 audio_hw_device_t *dev = mAudioHwDevs[i];
716 result = dev->set_parameters(dev, keyValuePairs.string());
717 final_result = result ?: final_result;
718 }
Eric Laurenta553c252009-07-17 12:17:14 -0700719 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -0700720 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700721 }
722
Eric Laurentb7d94602009-09-29 11:12:57 -0700723 // hold a strong ref on thread in case closeOutput() or closeInput() is called
724 // and the thread is exited once the lock is released
725 sp<ThreadBase> thread;
726 {
727 Mutex::Autolock _l(mLock);
728 thread = checkPlaybackThread_l(ioHandle);
729 if (thread == NULL) {
730 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700731 } else if (thread.get() == primaryPlaybackThread_l()) {
732 // indicate output device change to all input threads for pre processing
733 AudioParameter param = AudioParameter(keyValuePairs);
734 int value;
735 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
736 for (size_t i = 0; i < mRecordThreads.size(); i++) {
737 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
738 }
739 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700740 }
Eric Laurenta553c252009-07-17 12:17:14 -0700741 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700742 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800743 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800744 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700745 }
Eric Laurenta553c252009-07-17 12:17:14 -0700746 return BAD_VALUE;
747}
748
Eric Laurentddb78e72009-07-28 08:44:33 -0700749String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700750{
Eric Laurentddb78e72009-07-28 08:44:33 -0700751// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700752// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
753
754 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700755 String8 out_s8;
756
Dima Zavin31f188892011-04-18 16:57:27 -0700757 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
758 audio_hw_device_t *dev = mAudioHwDevs[i];
759 char *s = dev->get_parameters(dev, keys.string());
760 out_s8 += String8(s);
761 free(s);
762 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700763 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700764 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700765
766 Mutex::Autolock _l(mLock);
767
Eric Laurenta553c252009-07-17 12:17:14 -0700768 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
769 if (playbackThread != NULL) {
770 return playbackThread->getParameters(keys);
771 }
772 RecordThread *recordThread = checkRecordThread_l(ioHandle);
773 if (recordThread != NULL) {
774 return recordThread->getParameters(keys);
775 }
776 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700777}
778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
780{
Dima Zavin31f188892011-04-18 16:57:27 -0700781 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782}
783
Eric Laurent47d0a922010-02-26 02:47:27 -0800784unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
785{
786 if (ioHandle == 0) {
787 return 0;
788 }
789
790 Mutex::Autolock _l(mLock);
791
792 RecordThread *recordThread = checkRecordThread_l(ioHandle);
793 if (recordThread != NULL) {
794 return recordThread->getInputFramesLost();
795 }
796 return 0;
797}
798
Eric Laurent415f3e22009-10-21 08:14:22 -0700799status_t AudioFlinger::setVoiceVolume(float value)
800{
801 // check calling permissions
802 if (!settingsAllowed()) {
803 return PERMISSION_DENIED;
804 }
805
806 AutoMutex lock(mHardwareLock);
807 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700808 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700809 mHardwareStatus = AUDIO_HW_IDLE;
810
811 return ret;
812}
813
Eric Laurent0986e792010-01-19 17:37:09 -0800814status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
815{
816 status_t status;
817
818 Mutex::Autolock _l(mLock);
819
820 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
821 if (playbackThread != NULL) {
822 return playbackThread->getRenderPosition(halFrames, dspFrames);
823 }
824
825 return BAD_VALUE;
826}
827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
829{
Eric Laurenta553c252009-07-17 12:17:14 -0700830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 Mutex::Autolock _l(mLock);
832
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700833 int pid = IPCThreadState::self()->getCallingPid();
834 if (mNotificationClients.indexOfKey(pid) < 0) {
835 sp<NotificationClient> notificationClient = new NotificationClient(this,
836 client,
837 pid);
838 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700839
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700840 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700841
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700842 sp<IBinder> binder = client->asBinder();
843 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700845 // the config change is always sent from playback or record threads to avoid deadlock
846 // with AudioSystem::gLock
847 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
848 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
849 }
Eric Laurenta553c252009-07-17 12:17:14 -0700850
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700851 for (size_t i = 0; i < mRecordThreads.size(); i++) {
852 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
854 }
855}
856
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700857void AudioFlinger::removeNotificationClient(pid_t pid)
858{
859 Mutex::Autolock _l(mLock);
860
861 int index = mNotificationClients.indexOfKey(pid);
862 if (index >= 0) {
863 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
864 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700865 mNotificationClients.removeItem(pid);
866 }
867}
868
Eric Laurent296a0ec2009-09-15 07:10:12 -0700869// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700870void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
871{
Eric Laurent49f02be2009-11-19 09:00:56 -0800872 size_t size = mNotificationClients.size();
873 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700874 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700875 }
876}
877
Eric Laurentb9481d82009-09-17 05:12:56 -0700878// removeClient_l() must be called with AudioFlinger::mLock held
879void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700880{
Eric Laurentb9481d82009-09-17 05:12:56 -0700881 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 -0700882 mClients.removeItem(pid);
883}
884
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700885
Eric Laurenta553c252009-07-17 12:17:14 -0700886// ----------------------------------------------------------------------------
887
Eric Laurent464d5b32011-06-17 21:29:58 -0700888AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700889 : Thread(false),
890 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700891 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
892 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700893{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700894 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895}
896
Eric Laurenta553c252009-07-17 12:17:14 -0700897AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700899 mParamCond.broadcast();
900 mNewParameters.clear();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700901 // do not lock the mutex in destructor
902 releaseWakeLock_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903}
904
Eric Laurenta553c252009-07-17 12:17:14 -0700905void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700906{
Eric Laurentb7d94602009-09-29 11:12:57 -0700907 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700908 // destroyed in the middle of requestExitAndWait()
909 sp <ThreadBase> strongMe = this;
910
911 LOGV("ThreadBase::exit");
912 {
913 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800914 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700915 requestExit();
916 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700917 }
Eric Laurenta553c252009-07-17 12:17:14 -0700918 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700919}
Eric Laurenta553c252009-07-17 12:17:14 -0700920
921uint32_t AudioFlinger::ThreadBase::sampleRate() const
922{
923 return mSampleRate;
924}
925
926int AudioFlinger::ThreadBase::channelCount() const
927{
Eric Laurentb0a01472010-05-14 05:45:46 -0700928 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700929}
930
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700931uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -0700932{
933 return mFormat;
934}
935
936size_t AudioFlinger::ThreadBase::frameCount() const
937{
938 return mFrameCount;
939}
940
941status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
942{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700943 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700944
Eric Laurent8fce46a2009-08-04 09:45:33 -0700945 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700946 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700947
Eric Laurent8fce46a2009-08-04 09:45:33 -0700948 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700949 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700950 // wait condition with timeout in case the thread loop has exited
951 // before the request could be processed
952 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
953 status = mParamStatus;
954 mWaitWorkCV.signal();
955 } else {
956 status = TIMED_OUT;
957 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700958 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700959}
960
961void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
962{
963 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700964 sendConfigEvent_l(event, param);
965}
966
967// sendConfigEvent_l() must be called with ThreadBase::mLock held
968void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
969{
Eric Laurenta553c252009-07-17 12:17:14 -0700970 ConfigEvent *configEvent = new ConfigEvent();
971 configEvent->mEvent = event;
972 configEvent->mParam = param;
973 mConfigEvents.add(configEvent);
974 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
975 mWaitWorkCV.signal();
976}
977
978void AudioFlinger::ThreadBase::processConfigEvents()
979{
980 mLock.lock();
981 while(!mConfigEvents.isEmpty()) {
982 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
983 ConfigEvent *configEvent = mConfigEvents[0];
984 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700985 // release mLock before locking AudioFlinger mLock: lock order is always
986 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700987 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700988 mAudioFlinger->mLock.lock();
989 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
990 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700991 delete configEvent;
992 mLock.lock();
993 }
994 mLock.unlock();
995}
996
Eric Laurent3fdb1262009-11-07 00:01:32 -0800997status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
998{
999 const size_t SIZE = 256;
1000 char buffer[SIZE];
1001 String8 result;
1002
1003 bool locked = tryLock(mLock);
1004 if (!locked) {
1005 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1006 write(fd, buffer, strlen(buffer));
1007 }
1008
1009 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1010 result.append(buffer);
1011 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1012 result.append(buffer);
1013 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1014 result.append(buffer);
1015 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1016 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001017 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1018 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001019 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1020 result.append(buffer);
1021 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1022 result.append(buffer);
1023
1024 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1025 result.append(buffer);
1026 result.append(" Index Command");
1027 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1028 snprintf(buffer, SIZE, "\n %02d ", i);
1029 result.append(buffer);
1030 result.append(mNewParameters[i]);
1031 }
1032
1033 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1034 result.append(buffer);
1035 snprintf(buffer, SIZE, " Index event param\n");
1036 result.append(buffer);
1037 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1038 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1039 result.append(buffer);
1040 }
1041 result.append("\n");
1042
1043 write(fd, result.string(), result.size());
1044
1045 if (locked) {
1046 mLock.unlock();
1047 }
1048 return NO_ERROR;
1049}
1050
Eric Laurent1345d332011-07-24 17:49:51 -07001051status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1052{
1053 const size_t SIZE = 256;
1054 char buffer[SIZE];
1055 String8 result;
1056
1057 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1058 write(fd, buffer, strlen(buffer));
1059
1060 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1061 sp<EffectChain> chain = mEffectChains[i];
1062 if (chain != 0) {
1063 chain->dump(fd, args);
1064 }
1065 }
1066 return NO_ERROR;
1067}
1068
Eric Laurent6dbdc402011-07-22 09:04:31 -07001069void AudioFlinger::ThreadBase::acquireWakeLock()
1070{
1071 Mutex::Autolock _l(mLock);
1072 acquireWakeLock_l();
1073}
1074
1075void AudioFlinger::ThreadBase::acquireWakeLock_l()
1076{
1077 if (mPowerManager == 0) {
1078 // use checkService() to avoid blocking if power service is not up yet
1079 sp<IBinder> binder =
1080 defaultServiceManager()->checkService(String16("power"));
1081 if (binder == 0) {
1082 LOGW("Thread %s cannot connect to the power manager service", mName);
1083 } else {
1084 mPowerManager = interface_cast<IPowerManager>(binder);
1085 binder->linkToDeath(mDeathRecipient);
1086 }
1087 }
1088 if (mPowerManager != 0) {
1089 sp<IBinder> binder = new BBinder();
1090 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1091 binder,
1092 String16(mName));
1093 if (status == NO_ERROR) {
1094 mWakeLockToken = binder;
1095 }
1096 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1097 }
1098}
1099
1100void AudioFlinger::ThreadBase::releaseWakeLock()
1101{
1102 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001103 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001104}
1105
1106void AudioFlinger::ThreadBase::releaseWakeLock_l()
1107{
1108 if (mWakeLockToken != 0) {
1109 LOGV("releaseWakeLock_l() %s", mName);
1110 if (mPowerManager != 0) {
1111 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1112 }
1113 mWakeLockToken.clear();
1114 }
1115}
1116
1117void AudioFlinger::ThreadBase::clearPowerManager()
1118{
1119 Mutex::Autolock _l(mLock);
1120 releaseWakeLock_l();
1121 mPowerManager.clear();
1122}
1123
1124void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1125{
1126 sp<ThreadBase> thread = mThread.promote();
1127 if (thread != 0) {
1128 thread->clearPowerManager();
1129 }
1130 LOGW("power manager service died !!!");
1131}
Eric Laurent1345d332011-07-24 17:49:51 -07001132
Eric Laurentf82fccd2011-07-27 19:49:51 -07001133void AudioFlinger::ThreadBase::setEffectSuspended(
1134 const effect_uuid_t *type, bool suspend, int sessionId)
1135{
1136 Mutex::Autolock _l(mLock);
1137 setEffectSuspended_l(type, suspend, sessionId);
1138}
1139
1140void AudioFlinger::ThreadBase::setEffectSuspended_l(
1141 const effect_uuid_t *type, bool suspend, int sessionId)
1142{
1143 sp<EffectChain> chain;
1144 chain = getEffectChain_l(sessionId);
1145 if (chain != 0) {
1146 if (type != NULL) {
1147 chain->setEffectSuspended_l(type, suspend);
1148 } else {
1149 chain->setEffectSuspendedAll_l(suspend);
1150 }
1151 }
1152
1153 updateSuspendedSessions_l(type, suspend, sessionId);
1154}
1155
1156void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1157{
1158 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1159 if (index < 0) {
1160 return;
1161 }
1162
1163 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1164 mSuspendedSessions.editValueAt(index);
1165
1166 for (size_t i = 0; i < sessionEffects.size(); i++) {
1167 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1168 for (int j = 0; j < desc->mRefCount; j++) {
1169 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1170 chain->setEffectSuspendedAll_l(true);
1171 } else {
1172 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1173 desc->mType.timeLow);
1174 chain->setEffectSuspended_l(&desc->mType, true);
1175 }
1176 }
1177 }
1178}
1179
1180void AudioFlinger::ThreadBase::updateSuspendedSessionsOnRemoveEffectChain_l(
1181 const sp<EffectChain>& chain)
1182{
1183 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1184 if (index < 0) {
1185 return;
1186 }
1187 LOGV("updateSuspendedSessionsOnRemoveEffectChain_l() removed suspended session %d",
1188 chain->sessionId());
1189 mSuspendedSessions.removeItemsAt(index);
1190}
1191
1192void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1193 bool suspend,
1194 int sessionId)
1195{
1196 int index = mSuspendedSessions.indexOfKey(sessionId);
1197
1198 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1199
1200 if (suspend) {
1201 if (index >= 0) {
1202 sessionEffects = mSuspendedSessions.editValueAt(index);
1203 } else {
1204 mSuspendedSessions.add(sessionId, sessionEffects);
1205 }
1206 } else {
1207 if (index < 0) {
1208 return;
1209 }
1210 sessionEffects = mSuspendedSessions.editValueAt(index);
1211 }
1212
1213
1214 int key = EffectChain::kKeyForSuspendAll;
1215 if (type != NULL) {
1216 key = type->timeLow;
1217 }
1218 index = sessionEffects.indexOfKey(key);
1219
1220 sp <SuspendedSessionDesc> desc;
1221 if (suspend) {
1222 if (index >= 0) {
1223 desc = sessionEffects.valueAt(index);
1224 } else {
1225 desc = new SuspendedSessionDesc();
1226 if (type != NULL) {
1227 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1228 }
1229 sessionEffects.add(key, desc);
1230 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1231 }
1232 desc->mRefCount++;
1233 } else {
1234 if (index < 0) {
1235 return;
1236 }
1237 desc = sessionEffects.valueAt(index);
1238 if (--desc->mRefCount == 0) {
1239 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1240 sessionEffects.removeItemsAt(index);
1241 if (sessionEffects.isEmpty()) {
1242 LOGV("updateSuspendedSessions_l() restore removing session %d",
1243 sessionId);
1244 mSuspendedSessions.removeItem(sessionId);
1245 }
1246 }
1247 }
1248 if (!sessionEffects.isEmpty()) {
1249 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1250 }
1251}
1252
1253void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1254 bool enabled,
1255 int sessionId)
1256{
1257 Mutex::Autolock _l(mLock);
1258
1259 // TODO: implement PlaybackThread or RecordThread specific behavior here
1260
1261 sp<EffectChain> chain = getEffectChain_l(sessionId);
1262 if (chain != 0) {
1263 chain->checkSuspendOnEffectEnabled(effect, enabled);
1264 }
1265}
1266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267// ----------------------------------------------------------------------------
1268
Eric Laurent464d5b32011-06-17 21:29:58 -07001269AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1270 AudioStreamOut* output,
1271 int id,
1272 uint32_t device)
1273 : ThreadBase(audioFlinger, id, device),
Eric Laurentd5603c12009-08-06 08:49:39 -07001274 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001275 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001277 snprintf(mName, kNameLength, "AudioOut_%d", id);
1278
Eric Laurenta553c252009-07-17 12:17:14 -07001279 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280
Eric Laurenta553c252009-07-17 12:17:14 -07001281 mMasterVolume = mAudioFlinger->masterVolume();
1282 mMasterMute = mAudioFlinger->masterMute();
1283
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001284 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001285 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1286 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288}
1289
Eric Laurenta553c252009-07-17 12:17:14 -07001290AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291{
1292 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293}
1294
Eric Laurenta553c252009-07-17 12:17:14 -07001295status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296{
1297 dumpInternals(fd, args);
1298 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001299 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 return NO_ERROR;
1301}
1302
Eric Laurenta553c252009-07-17 12:17:14 -07001303status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304{
1305 const size_t SIZE = 256;
1306 char buffer[SIZE];
1307 String8 result;
1308
Eric Laurenta553c252009-07-17 12:17:14 -07001309 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001311 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 -08001312 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001313 sp<Track> track = mTracks[i];
1314 if (track != 0) {
1315 track->dump(buffer, SIZE);
1316 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
1318 }
1319
Eric Laurenta553c252009-07-17 12:17:14 -07001320 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001322 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 -08001323 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001324 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 if (wTrack != 0) {
1326 sp<Track> track = wTrack.promote();
1327 if (track != 0) {
1328 track->dump(buffer, SIZE);
1329 result.append(buffer);
1330 }
1331 }
1332 }
1333 write(fd, result.string(), result.size());
1334 return NO_ERROR;
1335}
1336
Eric Laurenta553c252009-07-17 12:17:14 -07001337status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338{
1339 const size_t SIZE = 256;
1340 char buffer[SIZE];
1341 String8 result;
1342
Eric Laurent3fdb1262009-11-07 00:01:32 -08001343 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 result.append(buffer);
1345 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1346 result.append(buffer);
1347 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1348 result.append(buffer);
1349 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1350 result.append(buffer);
1351 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1352 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001353 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1354 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001355 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1356 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001358
1359 dumpBase(fd, args);
1360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 return NO_ERROR;
1362}
1363
1364// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001365status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366{
1367 if (mSampleRate == 0) {
1368 LOGE("No working audio driver found.");
1369 return NO_INIT;
1370 }
Eric Laurenta553c252009-07-17 12:17:14 -07001371 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 return NO_ERROR;
1373}
1374
Eric Laurenta553c252009-07-17 12:17:14 -07001375void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001377 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378}
1379
Eric Laurenta553c252009-07-17 12:17:14 -07001380// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1381sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 const sp<AudioFlinger::Client>& client,
1383 int streamType,
1384 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001385 uint32_t format,
1386 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 int frameCount,
1388 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001389 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 status_t *status)
1391{
1392 sp<Track> track;
1393 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001394
1395 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001396 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1397 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1398 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1399 "for output %p with format %d",
1400 sampleRate, format, channelMask, mOutput, mFormat);
1401 lStatus = BAD_VALUE;
1402 goto Exit;
1403 }
Eric Laurenta553c252009-07-17 12:17:14 -07001404 }
1405 } else {
1406 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1407 if (sampleRate > mSampleRate*2) {
1408 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1409 lStatus = BAD_VALUE;
1410 goto Exit;
1411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 }
1413
Eric Laurent464d5b32011-06-17 21:29:58 -07001414 lStatus = initCheck();
1415 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001416 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001417 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419
Eric Laurenta553c252009-07-17 12:17:14 -07001420 { // scope for mLock
1421 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001422
1423 // all tracks in same audio session must share the same routing strategy otherwise
1424 // conflicts will happen when tracks are moved from one output to another by audio policy
1425 // manager
1426 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001427 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001428 for (size_t i = 0; i < mTracks.size(); ++i) {
1429 sp<Track> t = mTracks[i];
1430 if (t != 0) {
1431 if (sessionId == t->sessionId() &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001432 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001433 lStatus = BAD_VALUE;
1434 goto Exit;
1435 }
1436 }
1437 }
1438
Eric Laurenta553c252009-07-17 12:17:14 -07001439 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001440 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001441 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001442 lStatus = NO_MEMORY;
1443 goto Exit;
1444 }
1445 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001446
1447 sp<EffectChain> chain = getEffectChain_l(sessionId);
1448 if (chain != 0) {
1449 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1450 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001451 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001452 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001453 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001454 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001455 lStatus = NO_ERROR;
1456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457Exit:
1458 if(status) {
1459 *status = lStatus;
1460 }
1461 return track;
1462}
1463
Eric Laurenta553c252009-07-17 12:17:14 -07001464uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465{
1466 if (mOutput) {
Dima Zavin31f188892011-04-18 16:57:27 -07001467 return mOutput->stream->get_latency(mOutput->stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
1469 else {
1470 return 0;
1471 }
1472}
1473
Eric Laurenta553c252009-07-17 12:17:14 -07001474status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475{
1476 mMasterVolume = value;
1477 return NO_ERROR;
1478}
1479
Eric Laurenta553c252009-07-17 12:17:14 -07001480status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481{
1482 mMasterMute = muted;
1483 return NO_ERROR;
1484}
1485
Eric Laurenta553c252009-07-17 12:17:14 -07001486float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487{
1488 return mMasterVolume;
1489}
1490
Eric Laurenta553c252009-07-17 12:17:14 -07001491bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492{
1493 return mMasterMute;
1494}
1495
Eric Laurenta553c252009-07-17 12:17:14 -07001496status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497{
1498 mStreamTypes[stream].volume = value;
1499 return NO_ERROR;
1500}
1501
Eric Laurenta553c252009-07-17 12:17:14 -07001502status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503{
1504 mStreamTypes[stream].mute = muted;
1505 return NO_ERROR;
1506}
1507
Eric Laurenta553c252009-07-17 12:17:14 -07001508float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509{
1510 return mStreamTypes[stream].volume;
1511}
1512
Eric Laurenta553c252009-07-17 12:17:14 -07001513bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514{
1515 return mStreamTypes[stream].mute;
1516}
1517
Eric Laurenta553c252009-07-17 12:17:14 -07001518// addTrack_l() must be called with ThreadBase::mLock held
1519status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520{
1521 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001522
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001523 // set retry count for buffer fill
1524 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001525 if (mActiveTracks.indexOf(track) < 0) {
1526 // the track is newly added, make sure it fills up all its
1527 // buffers before playing. This is to ensure the client will
1528 // effectively get the latency it requested.
1529 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001530 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001531 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001532 if (track->mainBuffer() != mMixBuffer) {
1533 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1534 if (chain != 0) {
1535 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001536 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001537 }
1538 }
1539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001541 }
Eric Laurenta553c252009-07-17 12:17:14 -07001542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001544 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545
1546 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001547}
1548
Eric Laurenta553c252009-07-17 12:17:14 -07001549// destroyTrack_l() must be called with ThreadBase::mLock held
1550void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001551{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001552 track->mState = TrackBase::TERMINATED;
1553 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001554 removeTrack_l(track);
1555 }
1556}
1557
1558void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1559{
1560 mTracks.remove(track);
1561 deleteTrackName_l(track->name());
1562 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1563 if (chain != 0) {
1564 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001565 }
1566}
1567
Eric Laurenta553c252009-07-17 12:17:14 -07001568String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001569{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001570 String8 out_s8;
1571 char *s;
1572
Dima Zavin31f188892011-04-18 16:57:27 -07001573 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001574 out_s8 = String8(s);
1575 free(s);
1576 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001577}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001578
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001579// destroyTrack_l() must be called with AudioFlinger::mLock held
1580void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001581 AudioSystem::OutputDescriptor desc;
1582 void *param2 = 0;
1583
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001584 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001585
1586 switch (event) {
1587 case AudioSystem::OUTPUT_OPENED:
1588 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001589 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001590 desc.samplingRate = mSampleRate;
1591 desc.format = mFormat;
1592 desc.frameCount = mFrameCount;
1593 desc.latency = latency();
1594 param2 = &desc;
1595 break;
1596
1597 case AudioSystem::STREAM_CONFIG_CHANGED:
1598 param2 = &param;
1599 case AudioSystem::OUTPUT_CLOSED:
1600 default:
1601 break;
1602 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001603 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001604}
1605
1606void AudioFlinger::PlaybackThread::readOutputParameters()
1607{
Dima Zavin31f188892011-04-18 16:57:27 -07001608 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001609 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1610 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001611 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1612 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1613 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001614
Eric Laurenta553c252009-07-17 12:17:14 -07001615 // FIXME - Current mixer implementation only supports stereo output: Always
1616 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001617 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001618 mMixBuffer = new int16_t[mFrameCount * 2];
1619 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001620
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001621 // force reconfiguration of effect chains and engines to take new buffer size and audio
1622 // parameters into account
1623 // Note that mLock is not held when readOutputParameters() is called from the constructor
1624 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1625 // matter.
1626 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1627 Vector< sp<EffectChain> > effectChains = mEffectChains;
1628 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001629 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001630 }
Eric Laurenta553c252009-07-17 12:17:14 -07001631}
1632
Eric Laurent0986e792010-01-19 17:37:09 -08001633status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1634{
1635 if (halFrames == 0 || dspFrames == 0) {
1636 return BAD_VALUE;
1637 }
Eric Laurent464d5b32011-06-17 21:29:58 -07001638 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001639 return INVALID_OPERATION;
1640 }
Dima Zavin31f188892011-04-18 16:57:27 -07001641 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001642
Dima Zavin31f188892011-04-18 16:57:27 -07001643 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001644}
1645
Eric Laurent493941b2010-07-28 01:32:47 -07001646uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001647{
1648 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001649 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001650 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001651 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001652 }
1653
1654 for (size_t i = 0; i < mTracks.size(); ++i) {
1655 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001656 if (sessionId == track->sessionId() &&
1657 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001658 result |= TRACK_SESSION;
1659 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001660 }
1661 }
1662
Eric Laurent493941b2010-07-28 01:32:47 -07001663 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001664}
1665
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001666uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1667{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001668 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001669 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001670 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1671 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001672 }
1673 for (size_t i = 0; i < mTracks.size(); i++) {
1674 sp<Track> track = mTracks[i];
1675 if (sessionId == track->sessionId() &&
1676 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001677 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001678 }
1679 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001680 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001681}
1682
Eric Laurent53334cd2010-06-23 17:38:20 -07001683
Eric Laurenta553c252009-07-17 12:17:14 -07001684// ----------------------------------------------------------------------------
1685
Dima Zavin31f188892011-04-18 16:57:27 -07001686AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001687 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001688 mAudioMixer(0)
1689{
Eric Laurent464d5b32011-06-17 21:29:58 -07001690 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001691 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1692
1693 // FIXME - Current mixer implementation only supports stereo output
1694 if (mChannelCount == 1) {
1695 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001697}
1698
Eric Laurenta553c252009-07-17 12:17:14 -07001699AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001700{
Eric Laurenta553c252009-07-17 12:17:14 -07001701 delete mAudioMixer;
1702}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703
Eric Laurenta553c252009-07-17 12:17:14 -07001704bool AudioFlinger::MixerThread::threadLoop()
1705{
Eric Laurenta553c252009-07-17 12:17:14 -07001706 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001707 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001708 nsecs_t standbyTime = systemTime();
1709 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001710 // FIXME: Relaxed timing because of a certain device that can't meet latency
1711 // Should be reduced to 2x after the vendor fixes the driver issue
1712 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1713 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001714 bool longStandbyExit = false;
1715 uint32_t activeSleepTime = activeSleepTimeUs();
1716 uint32_t idleSleepTime = idleSleepTimeUs();
1717 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001718 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001719#ifdef DEBUG_CPU_USAGE
1720 ThreadCpuUsage cpu;
1721 const CentralTendencyStatistics& stats = cpu.statistics();
1722#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723
Eric Laurent6dbdc402011-07-22 09:04:31 -07001724 acquireWakeLock();
1725
Eric Laurenta553c252009-07-17 12:17:14 -07001726 while (!exitPending())
1727 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001728#ifdef DEBUG_CPU_USAGE
1729 cpu.sampleAndEnable();
1730 unsigned n = stats.n();
1731 // cpu.elapsed() is expensive, so don't call it every loop
1732 if ((n & 127) == 1) {
1733 long long elapsed = cpu.elapsed();
1734 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1735 double perLoop = elapsed / (double) n;
1736 double perLoop100 = perLoop * 0.01;
1737 double mean = stats.mean();
1738 double stddev = stats.stddev();
1739 double minimum = stats.minimum();
1740 double maximum = stats.maximum();
1741 cpu.resetStatistics();
1742 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",
1743 elapsed * .000000001, n, perLoop * .000001,
1744 mean * .001,
1745 stddev * .001,
1746 minimum * .001,
1747 maximum * .001,
1748 mean / perLoop100,
1749 stddev / perLoop100,
1750 minimum / perLoop100,
1751 maximum / perLoop100);
1752 }
1753 }
1754#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001755 processConfigEvents();
1756
Eric Laurent059b4be2009-11-09 23:32:22 -08001757 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001758 { // scope for mLock
1759
1760 Mutex::Autolock _l(mLock);
1761
1762 if (checkForNewParameters_l()) {
1763 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001764 // FIXME: Relaxed timing because of a certain device that can't meet latency
1765 // Should be reduced to 2x after the vendor fixes the driver issue
1766 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001767 activeSleepTime = activeSleepTimeUs();
1768 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001769 }
1770
1771 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1772
1773 // put audio hardware into standby after short delay
1774 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1775 mSuspended) {
1776 if (!mStandby) {
1777 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001778 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001779 mStandby = true;
1780 mBytesWritten = 0;
1781 }
1782
1783 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1784 // we're about to wait, flush the binder command buffer
1785 IPCThreadState::self()->flushCommands();
1786
1787 if (exitPending()) break;
1788
Eric Laurent6dbdc402011-07-22 09:04:31 -07001789 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001790 // wait until we have something to do...
1791 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1792 mWaitWorkCV.wait(mLock);
1793 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001794 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001795
1796 if (mMasterMute == false) {
1797 char value[PROPERTY_VALUE_MAX];
1798 property_get("ro.audio.silent", value, "0");
1799 if (atoi(value)) {
1800 LOGD("Silence is golden");
1801 setMasterMute(true);
1802 }
1803 }
1804
1805 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001806 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001807 continue;
1808 }
1809 }
1810
Eric Laurent059b4be2009-11-09 23:32:22 -08001811 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001812
1813 // prevent any changes in effect chain list and in each effect chain
1814 // during mixing and effect process as the audio buffers could be deleted
1815 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001816 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001817 }
1818
Eric Laurent059b4be2009-11-09 23:32:22 -08001819 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001820 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001821 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001822 sleepTime = 0;
1823 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001824 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001825 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001826 // If no tracks are ready, sleep once for the duration of an output
1827 // buffer size, then write 0s to the output
1828 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001829 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1830 sleepTime = activeSleepTime;
1831 } else {
1832 sleepTime = idleSleepTime;
1833 }
1834 } else if (mBytesWritten != 0 ||
1835 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001836 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001837 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001838 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001839 }
Eric Laurent65b65452010-06-01 23:49:17 -07001840 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001841 }
1842
1843 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001844 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001845 }
1846 // sleepTime == 0 means we must write to audio hardware
1847 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001848 for (size_t i = 0; i < effectChains.size(); i ++) {
1849 effectChains[i]->process_l();
1850 }
1851 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001852 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07001853 mLastWriteTime = systemTime();
1854 mInWrite = true;
1855 mBytesWritten += mixBufferSize;
1856
Dima Zavin31f188892011-04-18 16:57:27 -07001857 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001858 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001859 mNumWrites++;
1860 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001861 nsecs_t now = systemTime();
1862 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001863 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001864 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001865 if ((now - lastWarning) > kWarningThrottle) {
1866 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1867 ns2ms(delta), mNumDelayedWrites, this);
1868 lastWarning = now;
1869 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001870 if (mStandby) {
1871 longStandbyExit = true;
1872 }
Eric Laurenta553c252009-07-17 12:17:14 -07001873 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001874 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001875 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001876 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001877 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001878 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001879 }
1880
1881 // finally let go of all our tracks, without the lock held
1882 // since we can't guarantee the destructors won't acquire that
1883 // same lock.
1884 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001885
1886 // Effect chains will be actually deleted here if they were removed from
1887 // mEffectChains list during mixing or effects processing
1888 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001889 }
1890
1891 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07001892 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001893 }
Eric Laurenta553c252009-07-17 12:17:14 -07001894
Eric Laurent6dbdc402011-07-22 09:04:31 -07001895 releaseWakeLock();
1896
Eric Laurenta553c252009-07-17 12:17:14 -07001897 LOGV("MixerThread %p exiting", this);
1898 return false;
1899}
1900
1901// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001902uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001903{
1904
Eric Laurent059b4be2009-11-09 23:32:22 -08001905 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001906 // find out which tracks need to be processed
1907 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001908 size_t mixedTracks = 0;
1909 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001910
1911 float masterVolume = mMasterVolume;
1912 bool masterMute = mMasterMute;
1913
Eric Laurent8cc93b92010-08-11 05:20:11 -07001914 if (masterMute) {
1915 masterVolume = 0;
1916 }
Eric Laurent65b65452010-06-01 23:49:17 -07001917 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001918 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001919 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001920 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001921 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001922 masterVolume = (float)((v + (1 << 23)) >> 24);
1923 chain.clear();
1924 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001925
Eric Laurenta553c252009-07-17 12:17:14 -07001926 for (size_t i=0 ; i<count ; i++) {
1927 sp<Track> t = activeTracks[i].promote();
1928 if (t == 0) continue;
1929
1930 Track* const track = t.get();
1931 audio_track_cblk_t* cblk = track->cblk();
1932
1933 // The first time a track is added we wait
1934 // for all its buffers to be filled before processing it
1935 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001936 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001937 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001938 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001939 //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 -07001940
Eric Laurent65b65452010-06-01 23:49:17 -07001941 mixedTracks++;
1942
1943 // track->mainBuffer() != mMixBuffer means there is an effect chain
1944 // connected to the track
1945 chain.clear();
1946 if (track->mainBuffer() != mMixBuffer) {
1947 chain = getEffectChain_l(track->sessionId());
1948 // Delegate volume control to effect in track effect chain if needed
1949 if (chain != 0) {
1950 tracksWithEffect++;
1951 } else {
1952 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1953 track->name(), track->sessionId());
1954 }
1955 }
1956
1957
1958 int param = AudioMixer::VOLUME;
1959 if (track->mFillingUpStatus == Track::FS_FILLED) {
1960 // no ramp for the first volume setting
1961 track->mFillingUpStatus = Track::FS_ACTIVE;
1962 if (track->mState == TrackBase::RESUMING) {
1963 track->mState = TrackBase::ACTIVE;
1964 param = AudioMixer::RAMP_VOLUME;
1965 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08001966 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07001967 } else if (cblk->server != 0) {
1968 // If the track is stopped before the first frame was mixed,
1969 // do not apply ramp
1970 param = AudioMixer::RAMP_VOLUME;
1971 }
1972
Eric Laurenta553c252009-07-17 12:17:14 -07001973 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001974 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001975 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001976 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001977 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001978 if (track->isPausing()) {
1979 track->setPaused();
1980 }
1981 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001982
Glenn Kasten871c16c2010-03-05 12:18:01 -08001983 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001984 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001985 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001986 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1987 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001988
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001989 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001990 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001991 // Delegate volume control to effect in track effect chain if needed
1992 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1993 // Do not ramp volume if volume is controlled by effect
1994 param = AudioMixer::VOLUME;
1995 track->mHasVolumeController = true;
1996 } else {
1997 // force no volume ramp when volume controller was just disabled or removed
1998 // from effect chain to avoid volume spike
1999 if (track->mHasVolumeController) {
2000 param = AudioMixer::VOLUME;
2001 }
2002 track->mHasVolumeController = false;
2003 }
2004
2005 // Convert volumes from 8.24 to 4.12 format
2006 int16_t left, right, aux;
2007 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2008 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2009 left = int16_t(v_clamped);
2010 v_clamped = (vr + (1 << 11)) >> 12;
2011 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2012 right = int16_t(v_clamped);
2013
2014 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2015 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002016
Eric Laurent65b65452010-06-01 23:49:17 -07002017 // XXX: these things DON'T need to be done each time
2018 mAudioMixer->setBufferProvider(track);
2019 mAudioMixer->enable(AudioMixer::MIXING);
2020
2021 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2022 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2023 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002024 mAudioMixer->setParameter(
2025 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002026 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002027 mAudioMixer->setParameter(
2028 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002029 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002030 mAudioMixer->setParameter(
2031 AudioMixer::RESAMPLE,
2032 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002033 (void *)(cblk->sampleRate));
2034 mAudioMixer->setParameter(
2035 AudioMixer::TRACK,
2036 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2037 mAudioMixer->setParameter(
2038 AudioMixer::TRACK,
2039 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002040
2041 // reset retry count
2042 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002043 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002044 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002045 //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 -07002046 if (track->isStopped()) {
2047 track->reset();
2048 }
2049 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2050 // We have consumed all the buffers of this track.
2051 // Remove it from the list of active tracks.
2052 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002053 } else {
2054 // No buffers for this track. Give it a few chances to
2055 // fill a buffer, then remove it from active list.
2056 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07002057 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002058 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002059 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002060 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002061 } else if (mixerStatus != MIXER_TRACKS_READY) {
2062 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002063 }
Eric Laurenta553c252009-07-17 12:17:14 -07002064 }
Eric Laurent65b65452010-06-01 23:49:17 -07002065 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07002066 }
2067 }
2068
2069 // remove all the tracks that need to be...
2070 count = tracksToRemove->size();
2071 if (UNLIKELY(count)) {
2072 for (size_t i=0 ; i<count ; i++) {
2073 const sp<Track>& track = tracksToRemove->itemAt(i);
2074 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002075 if (track->mainBuffer() != mMixBuffer) {
2076 chain = getEffectChain_l(track->sessionId());
2077 if (chain != 0) {
2078 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002079 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002080 }
2081 }
Eric Laurenta553c252009-07-17 12:17:14 -07002082 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002083 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002084 }
2085 }
2086 }
2087
Eric Laurent65b65452010-06-01 23:49:17 -07002088 // mix buffer must be cleared if all tracks are connected to an
2089 // effect chain as in this case the mixer will not write to
2090 // mix buffer and track effects will accumulate into it
2091 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2092 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2093 }
2094
Eric Laurent059b4be2009-11-09 23:32:22 -08002095 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002096}
2097
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002098void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002099{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002100 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2101 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002102 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002103
Eric Laurenta553c252009-07-17 12:17:14 -07002104 size_t size = mTracks.size();
2105 for (size_t i = 0; i < size; i++) {
2106 sp<Track> t = mTracks[i];
2107 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002108 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002109 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002110 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002111 }
2112}
Eric Laurenta553c252009-07-17 12:17:14 -07002113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114
Eric Laurenta553c252009-07-17 12:17:14 -07002115// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002116int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117{
2118 return mAudioMixer->getTrackName();
2119}
2120
Eric Laurenta553c252009-07-17 12:17:14 -07002121// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002122void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123{
Eric Laurent0a080292009-12-07 10:53:10 -08002124 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 mAudioMixer->deleteTrackName(name);
2126}
2127
Eric Laurenta553c252009-07-17 12:17:14 -07002128// checkForNewParameters_l() must be called with ThreadBase::mLock held
2129bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130{
Eric Laurenta553c252009-07-17 12:17:14 -07002131 bool reconfig = false;
2132
Eric Laurent8fce46a2009-08-04 09:45:33 -07002133 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002134 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002135 String8 keyValuePair = mNewParameters[0];
2136 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002137 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002138
Eric Laurenta553c252009-07-17 12:17:14 -07002139 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2140 reconfig = true;
2141 }
2142 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002143 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002144 status = BAD_VALUE;
2145 } else {
2146 reconfig = true;
2147 }
2148 }
2149 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002150 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002151 status = BAD_VALUE;
2152 } else {
2153 reconfig = true;
2154 }
2155 }
2156 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2157 // do not accept frame count changes if tracks are open as the track buffer
2158 // size depends on frame count and correct behavior would not be garantied
2159 // if frame count is changed after track creation
2160 if (!mTracks.isEmpty()) {
2161 status = INVALID_OPERATION;
2162 } else {
2163 reconfig = true;
2164 }
2165 }
Eric Laurent65b65452010-06-01 23:49:17 -07002166 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002167 // when changing the audio output device, call addBatteryData to notify
2168 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002169 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002170 uint32_t params = 0;
2171 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002172 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002173 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2174 }
2175
2176 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002177 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002178 // check if any other device (except speaker) is on
2179 if (value & deviceWithoutSpeaker ) {
2180 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2181 }
2182
2183 if (params != 0) {
2184 addBatteryData(params);
2185 }
2186 }
2187
Eric Laurent65b65452010-06-01 23:49:17 -07002188 // forward device change to effects that have requested to be
2189 // aware of attached audio device.
2190 mDevice = (uint32_t)value;
2191 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002192 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002193 }
2194 }
2195
Eric Laurenta553c252009-07-17 12:17:14 -07002196 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002197 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002198 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002199 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002200 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002201 mStandby = true;
2202 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002203 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002204 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002205 }
2206 if (status == NO_ERROR && reconfig) {
2207 delete mAudioMixer;
2208 readOutputParameters();
2209 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2210 for (size_t i = 0; i < mTracks.size() ; i++) {
2211 int name = getTrackName_l();
2212 if (name < 0) break;
2213 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002214 // limit track sample rate to 2 x new output sample rate
2215 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2216 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2217 }
Eric Laurenta553c252009-07-17 12:17:14 -07002218 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002219 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002220 }
2221 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002222
2223 mNewParameters.removeAt(0);
2224
Eric Laurenta553c252009-07-17 12:17:14 -07002225 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002226 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002227 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002228 }
2229 return reconfig;
2230}
2231
2232status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2233{
2234 const size_t SIZE = 256;
2235 char buffer[SIZE];
2236 String8 result;
2237
2238 PlaybackThread::dumpInternals(fd, args);
2239
2240 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2241 result.append(buffer);
2242 write(fd, result.string(), result.size());
2243 return NO_ERROR;
2244}
2245
Eric Laurent059b4be2009-11-09 23:32:22 -08002246uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002247{
Dima Zavin31f188892011-04-18 16:57:27 -07002248 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002249}
2250
2251uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2252{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002253 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002254}
2255
Eric Laurent8448a792010-08-18 18:13:17 -07002256uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2257{
2258 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2259}
2260
Eric Laurenta553c252009-07-17 12:17:14 -07002261// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002262AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002263 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002264{
Eric Laurent464d5b32011-06-17 21:29:58 -07002265 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002266}
2267
2268AudioFlinger::DirectOutputThread::~DirectOutputThread()
2269{
2270}
2271
2272
Eric Laurent65b65452010-06-01 23:49:17 -07002273static inline int16_t clamp16(int32_t sample)
2274{
2275 if ((sample>>15) ^ (sample>>31))
2276 sample = 0x7FFF ^ (sample>>31);
2277 return sample;
2278}
2279
2280static inline
2281int32_t mul(int16_t in, int16_t v)
2282{
2283#if defined(__arm__) && !defined(__thumb__)
2284 int32_t out;
2285 asm( "smulbb %[out], %[in], %[v] \n"
2286 : [out]"=r"(out)
2287 : [in]"%r"(in), [v]"r"(v)
2288 : );
2289 return out;
2290#else
2291 return in * int32_t(v);
2292#endif
2293}
2294
2295void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2296{
2297 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002298 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002299 return;
2300 }
2301
2302 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002303 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002304 size_t count = mFrameCount * mChannelCount;
2305 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2306 int16_t *dst = mMixBuffer + count-1;
2307 while(count--) {
2308 *dst-- = (int16_t)(*src--^0x80) << 8;
2309 }
2310 }
2311
2312 size_t frameCount = mFrameCount;
2313 int16_t *out = mMixBuffer;
2314 if (ramp) {
2315 if (mChannelCount == 1) {
2316 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2317 int32_t vlInc = d / (int32_t)frameCount;
2318 int32_t vl = ((int32_t)mLeftVolShort << 16);
2319 do {
2320 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2321 out++;
2322 vl += vlInc;
2323 } while (--frameCount);
2324
2325 } else {
2326 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2327 int32_t vlInc = d / (int32_t)frameCount;
2328 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2329 int32_t vrInc = d / (int32_t)frameCount;
2330 int32_t vl = ((int32_t)mLeftVolShort << 16);
2331 int32_t vr = ((int32_t)mRightVolShort << 16);
2332 do {
2333 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2334 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2335 out += 2;
2336 vl += vlInc;
2337 vr += vrInc;
2338 } while (--frameCount);
2339 }
2340 } else {
2341 if (mChannelCount == 1) {
2342 do {
2343 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2344 out++;
2345 } while (--frameCount);
2346 } else {
2347 do {
2348 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2349 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2350 out += 2;
2351 } while (--frameCount);
2352 }
2353 }
2354
2355 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002356 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002357 size_t count = mFrameCount * mChannelCount;
2358 int16_t *src = mMixBuffer;
2359 uint8_t *dst = (uint8_t *)mMixBuffer;
2360 while(count--) {
2361 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2362 }
2363 }
2364
2365 mLeftVolShort = leftVol;
2366 mRightVolShort = rightVol;
2367}
2368
Eric Laurenta553c252009-07-17 12:17:14 -07002369bool AudioFlinger::DirectOutputThread::threadLoop()
2370{
Eric Laurent059b4be2009-11-09 23:32:22 -08002371 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002372 sp<Track> trackToRemove;
2373 sp<Track> activeTrack;
2374 nsecs_t standbyTime = systemTime();
2375 int8_t *curBuf;
2376 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002377 uint32_t activeSleepTime = activeSleepTimeUs();
2378 uint32_t idleSleepTime = idleSleepTimeUs();
2379 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002380 // use shorter standby delay as on normal output to release
2381 // hardware resources as soon as possible
2382 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002383
Eric Laurent6dbdc402011-07-22 09:04:31 -07002384 acquireWakeLock();
2385
Eric Laurenta553c252009-07-17 12:17:14 -07002386 while (!exitPending())
2387 {
Eric Laurent65b65452010-06-01 23:49:17 -07002388 bool rampVolume;
2389 uint16_t leftVol;
2390 uint16_t rightVol;
2391 Vector< sp<EffectChain> > effectChains;
2392
Eric Laurenta553c252009-07-17 12:17:14 -07002393 processConfigEvents();
2394
Eric Laurent059b4be2009-11-09 23:32:22 -08002395 mixerStatus = MIXER_IDLE;
2396
Eric Laurenta553c252009-07-17 12:17:14 -07002397 { // scope for the mLock
2398
2399 Mutex::Autolock _l(mLock);
2400
2401 if (checkForNewParameters_l()) {
2402 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002403 activeSleepTime = activeSleepTimeUs();
2404 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002405 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002406 }
2407
2408 // put audio hardware into standby after short delay
2409 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2410 mSuspended) {
2411 // wait until we have something to do...
2412 if (!mStandby) {
2413 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002414 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002415 mStandby = true;
2416 mBytesWritten = 0;
2417 }
2418
2419 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2420 // we're about to wait, flush the binder command buffer
2421 IPCThreadState::self()->flushCommands();
2422
2423 if (exitPending()) break;
2424
Eric Laurent6dbdc402011-07-22 09:04:31 -07002425 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002426 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2427 mWaitWorkCV.wait(mLock);
2428 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002429 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002430
2431 if (mMasterMute == false) {
2432 char value[PROPERTY_VALUE_MAX];
2433 property_get("ro.audio.silent", value, "0");
2434 if (atoi(value)) {
2435 LOGD("Silence is golden");
2436 setMasterMute(true);
2437 }
2438 }
2439
Eric Laurentef9500f2010-03-11 14:47:00 -08002440 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002441 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002442 continue;
2443 }
2444 }
2445
Eric Laurent65b65452010-06-01 23:49:17 -07002446 effectChains = mEffectChains;
2447
Eric Laurenta553c252009-07-17 12:17:14 -07002448 // find out which tracks need to be processed
2449 if (mActiveTracks.size() != 0) {
2450 sp<Track> t = mActiveTracks[0].promote();
2451 if (t == 0) continue;
2452
2453 Track* const track = t.get();
2454 audio_track_cblk_t* cblk = track->cblk();
2455
2456 // The first time a track is added we wait
2457 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002458 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002459 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002460 {
2461 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2462
Eric Laurent65b65452010-06-01 23:49:17 -07002463 if (track->mFillingUpStatus == Track::FS_FILLED) {
2464 track->mFillingUpStatus = Track::FS_ACTIVE;
2465 mLeftVolFloat = mRightVolFloat = 0;
2466 mLeftVolShort = mRightVolShort = 0;
2467 if (track->mState == TrackBase::RESUMING) {
2468 track->mState = TrackBase::ACTIVE;
2469 rampVolume = true;
2470 }
2471 } else if (cblk->server != 0) {
2472 // If the track is stopped before the first frame was mixed,
2473 // do not apply ramp
2474 rampVolume = true;
2475 }
Eric Laurenta553c252009-07-17 12:17:14 -07002476 // compute volume for this track
2477 float left, right;
2478 if (track->isMuted() || mMasterMute || track->isPausing() ||
2479 mStreamTypes[track->type()].mute) {
2480 left = right = 0;
2481 if (track->isPausing()) {
2482 track->setPaused();
2483 }
2484 } else {
2485 float typeVolume = mStreamTypes[track->type()].volume;
2486 float v = mMasterVolume * typeVolume;
2487 float v_clamped = v * cblk->volume[0];
2488 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2489 left = v_clamped/MAX_GAIN;
2490 v_clamped = v * cblk->volume[1];
2491 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2492 right = v_clamped/MAX_GAIN;
2493 }
2494
Eric Laurent65b65452010-06-01 23:49:17 -07002495 if (left != mLeftVolFloat || right != mRightVolFloat) {
2496 mLeftVolFloat = left;
2497 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002498
Eric Laurent65b65452010-06-01 23:49:17 -07002499 // If audio HAL implements volume control,
2500 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002501 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002502 left = 1.0f;
2503 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002504 }
Eric Laurent65b65452010-06-01 23:49:17 -07002505
2506 // Convert volumes from float to 8.24
2507 uint32_t vl = (uint32_t)(left * (1 << 24));
2508 uint32_t vr = (uint32_t)(right * (1 << 24));
2509
2510 // Delegate volume control to effect in track effect chain if needed
2511 // only one effect chain can be present on DirectOutputThread, so if
2512 // there is one, the track is connected to it
2513 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002514 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002515 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002516 rampVolume = false;
2517 }
2518 }
2519
2520 // Convert volumes from 8.24 to 4.12 format
2521 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2522 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2523 leftVol = (uint16_t)v_clamped;
2524 v_clamped = (vr + (1 << 11)) >> 12;
2525 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2526 rightVol = (uint16_t)v_clamped;
2527 } else {
2528 leftVol = mLeftVolShort;
2529 rightVol = mRightVolShort;
2530 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002531 }
2532
2533 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002534 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002535 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002536 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002537 } else {
2538 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2539 if (track->isStopped()) {
2540 track->reset();
2541 }
2542 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2543 // We have consumed all the buffers of this track.
2544 // Remove it from the list of active tracks.
2545 trackToRemove = track;
2546 } else {
2547 // No buffers for this track. Give it a few chances to
2548 // fill a buffer, then remove it from active list.
2549 if (--(track->mRetryCount) <= 0) {
2550 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2551 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002552 } else {
2553 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002554 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002555 }
Eric Laurenta553c252009-07-17 12:17:14 -07002556 }
2557 }
2558
2559 // remove all the tracks that need to be...
2560 if (UNLIKELY(trackToRemove != 0)) {
2561 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002562 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002563 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2564 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002565 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002566 }
Eric Laurenta553c252009-07-17 12:17:14 -07002567 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002568 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002569 }
2570 }
Eric Laurent65b65452010-06-01 23:49:17 -07002571
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002572 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002573 }
2574
Eric Laurent059b4be2009-11-09 23:32:22 -08002575 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002576 AudioBufferProvider::Buffer buffer;
2577 size_t frameCount = mFrameCount;
2578 curBuf = (int8_t *)mMixBuffer;
2579 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002580 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002581 buffer.frameCount = frameCount;
2582 activeTrack->getNextBuffer(&buffer);
2583 if (UNLIKELY(buffer.raw == 0)) {
2584 memset(curBuf, 0, frameCount * mFrameSize);
2585 break;
2586 }
2587 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2588 frameCount -= buffer.frameCount;
2589 curBuf += buffer.frameCount * mFrameSize;
2590 activeTrack->releaseBuffer(&buffer);
2591 }
2592 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002593 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002594 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002595 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002596 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2597 sleepTime = activeSleepTime;
2598 } else {
2599 sleepTime = idleSleepTime;
2600 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002601 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002602 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002603 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002604 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002605 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002606
Eric Laurentf69a3f82009-09-22 00:35:48 -07002607 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002608 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002609 }
2610 // sleepTime == 0 means we must write to audio hardware
2611 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002612 if (mixerStatus == MIXER_TRACKS_READY) {
2613 applyVolume(leftVol, rightVol, rampVolume);
2614 }
2615 for (size_t i = 0; i < effectChains.size(); i ++) {
2616 effectChains[i]->process_l();
2617 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002618 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002619
Eric Laurentf69a3f82009-09-22 00:35:48 -07002620 mLastWriteTime = systemTime();
2621 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002622 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002623 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002624 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002625 mNumWrites++;
2626 mInWrite = false;
2627 mStandby = false;
2628 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002629 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002630 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002631 }
2632
2633 // finally let go of removed track, without the lock held
2634 // since we can't guarantee the destructors won't acquire that
2635 // same lock.
2636 trackToRemove.clear();
2637 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002638
2639 // Effect chains will be actually deleted here if they were removed from
2640 // mEffectChains list during mixing or effects processing
2641 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002642 }
2643
2644 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002645 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002646 }
Eric Laurenta553c252009-07-17 12:17:14 -07002647
Eric Laurent6dbdc402011-07-22 09:04:31 -07002648 releaseWakeLock();
2649
Eric Laurenta553c252009-07-17 12:17:14 -07002650 LOGV("DirectOutputThread %p exiting", this);
2651 return false;
2652}
2653
2654// getTrackName_l() must be called with ThreadBase::mLock held
2655int AudioFlinger::DirectOutputThread::getTrackName_l()
2656{
2657 return 0;
2658}
2659
2660// deleteTrackName_l() must be called with ThreadBase::mLock held
2661void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2662{
2663}
2664
2665// checkForNewParameters_l() must be called with ThreadBase::mLock held
2666bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2667{
2668 bool reconfig = false;
2669
Eric Laurent8fce46a2009-08-04 09:45:33 -07002670 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002671 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002672 String8 keyValuePair = mNewParameters[0];
2673 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002674 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002675
Eric Laurenta553c252009-07-17 12:17:14 -07002676 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2677 // do not accept frame count changes if tracks are open as the track buffer
2678 // size depends on frame count and correct behavior would not be garantied
2679 // if frame count is changed after track creation
2680 if (!mTracks.isEmpty()) {
2681 status = INVALID_OPERATION;
2682 } else {
2683 reconfig = true;
2684 }
2685 }
2686 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002687 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002688 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002689 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002690 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002691 mStandby = true;
2692 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002693 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002694 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002695 }
2696 if (status == NO_ERROR && reconfig) {
2697 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002698 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002699 }
2700 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002701
2702 mNewParameters.removeAt(0);
2703
Eric Laurenta553c252009-07-17 12:17:14 -07002704 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002705 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002706 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002707 }
2708 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002709}
2710
Eric Laurent059b4be2009-11-09 23:32:22 -08002711uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002712{
2713 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002714 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin31f188892011-04-18 16:57:27 -07002715 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Eric Laurent059b4be2009-11-09 23:32:22 -08002716 } else {
2717 time = 10000;
2718 }
2719 return time;
2720}
2721
2722uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2723{
2724 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002725 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002726 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002727 } else {
2728 time = 10000;
2729 }
2730 return time;
2731}
2732
Eric Laurent8448a792010-08-18 18:13:17 -07002733uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2734{
2735 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002736 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002737 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2738 } else {
2739 time = 10000;
2740 }
2741 return time;
2742}
2743
2744
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002745// ----------------------------------------------------------------------------
2746
Eric Laurent49f02be2009-11-19 09:00:56 -08002747AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002748 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002749{
Eric Laurent464d5b32011-06-17 21:29:58 -07002750 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002751 addOutputTrack(mainThread);
2752}
2753
2754AudioFlinger::DuplicatingThread::~DuplicatingThread()
2755{
Eric Laurent0a080292009-12-07 10:53:10 -08002756 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2757 mOutputTracks[i]->destroy();
2758 }
Eric Laurenta553c252009-07-17 12:17:14 -07002759 mOutputTracks.clear();
2760}
2761
2762bool AudioFlinger::DuplicatingThread::threadLoop()
2763{
Eric Laurenta553c252009-07-17 12:17:14 -07002764 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002765 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002766 nsecs_t standbyTime = systemTime();
2767 size_t mixBufferSize = mFrameCount*mFrameSize;
2768 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002769 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002770 uint32_t activeSleepTime = activeSleepTimeUs();
2771 uint32_t idleSleepTime = idleSleepTimeUs();
2772 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002773 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002774
Eric Laurent6dbdc402011-07-22 09:04:31 -07002775 acquireWakeLock();
2776
Eric Laurenta553c252009-07-17 12:17:14 -07002777 while (!exitPending())
2778 {
2779 processConfigEvents();
2780
Eric Laurent059b4be2009-11-09 23:32:22 -08002781 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002782 { // scope for the mLock
2783
2784 Mutex::Autolock _l(mLock);
2785
2786 if (checkForNewParameters_l()) {
2787 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002788 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002789 activeSleepTime = activeSleepTimeUs();
2790 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002791 }
2792
2793 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2794
2795 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2796 outputTracks.add(mOutputTracks[i]);
2797 }
2798
2799 // put audio hardware into standby after short delay
2800 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2801 mSuspended) {
2802 if (!mStandby) {
2803 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002804 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002805 }
2806 mStandby = true;
2807 mBytesWritten = 0;
2808 }
2809
2810 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2811 // we're about to wait, flush the binder command buffer
2812 IPCThreadState::self()->flushCommands();
2813 outputTracks.clear();
2814
2815 if (exitPending()) break;
2816
Eric Laurent6dbdc402011-07-22 09:04:31 -07002817 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002818 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2819 mWaitWorkCV.wait(mLock);
2820 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002821 acquireWakeLock_l();
2822
Eric Laurenta553c252009-07-17 12:17:14 -07002823 if (mMasterMute == false) {
2824 char value[PROPERTY_VALUE_MAX];
2825 property_get("ro.audio.silent", value, "0");
2826 if (atoi(value)) {
2827 LOGD("Silence is golden");
2828 setMasterMute(true);
2829 }
2830 }
2831
2832 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002833 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002834 continue;
2835 }
2836 }
2837
Eric Laurent059b4be2009-11-09 23:32:22 -08002838 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002839
2840 // prevent any changes in effect chain list and in each effect chain
2841 // during mixing and effect process as the audio buffers could be deleted
2842 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002843 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002844 }
Eric Laurenta553c252009-07-17 12:17:14 -07002845
Eric Laurent059b4be2009-11-09 23:32:22 -08002846 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002847 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002848 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002849 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002850 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002851 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002852 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002853 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002854 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002855 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002856 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002857 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2858 sleepTime = activeSleepTime;
2859 } else {
2860 sleepTime = idleSleepTime;
2861 }
Eric Laurent62443f52009-10-05 20:29:18 -07002862 } else if (mBytesWritten != 0) {
2863 // flush remaining overflow buffers in output tracks
2864 for (size_t i = 0; i < outputTracks.size(); i++) {
2865 if (outputTracks[i]->isActive()) {
2866 sleepTime = 0;
2867 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002868 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002869 break;
2870 }
2871 }
Eric Laurenta553c252009-07-17 12:17:14 -07002872 }
2873 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002874
2875 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002876 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002877 }
2878 // sleepTime == 0 means we must write to audio hardware
2879 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002880 for (size_t i = 0; i < effectChains.size(); i ++) {
2881 effectChains[i]->process_l();
2882 }
2883 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002884 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002885
Eric Laurent62443f52009-10-05 20:29:18 -07002886 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002887 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002888 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002889 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002890 mStandby = false;
2891 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002892 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002893 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002894 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002895 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002896 }
2897
2898 // finally let go of all our tracks, without the lock held
2899 // since we can't guarantee the destructors won't acquire that
2900 // same lock.
2901 tracksToRemove.clear();
2902 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002903
2904 // Effect chains will be actually deleted here if they were removed from
2905 // mEffectChains list during mixing or effects processing
2906 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002907 }
2908
Eric Laurent6dbdc402011-07-22 09:04:31 -07002909 releaseWakeLock();
2910
Eric Laurenta553c252009-07-17 12:17:14 -07002911 return false;
2912}
2913
2914void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2915{
2916 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2917 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002918 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002919 mSampleRate,
2920 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002921 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07002922 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002923 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002924 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07002925 mOutputTracks.add(outputTrack);
2926 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002927 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002928 }
Eric Laurenta553c252009-07-17 12:17:14 -07002929}
2930
2931void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2932{
2933 Mutex::Autolock _l(mLock);
2934 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2935 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002936 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002937 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002938 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002939 return;
2940 }
2941 }
2942 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2943}
2944
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002945void AudioFlinger::DuplicatingThread::updateWaitTime()
2946{
2947 mWaitTimeMs = UINT_MAX;
2948 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2949 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2950 if (strong != NULL) {
2951 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2952 if (waitTimeMs < mWaitTimeMs) {
2953 mWaitTimeMs = waitTimeMs;
2954 }
2955 }
2956 }
2957}
2958
2959
2960bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2961{
2962 for (size_t i = 0; i < outputTracks.size(); i++) {
2963 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2964 if (thread == 0) {
2965 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2966 return false;
2967 }
2968 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2969 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2970 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2971 return false;
2972 }
2973 }
2974 return true;
2975}
2976
2977uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2978{
2979 return (mWaitTimeMs * 1000) / 2;
2980}
2981
Eric Laurenta553c252009-07-17 12:17:14 -07002982// ----------------------------------------------------------------------------
2983
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002984// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002985AudioFlinger::ThreadBase::TrackBase::TrackBase(
2986 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002987 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002988 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002989 uint32_t format,
2990 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002991 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002993 const sp<IMemory>& sharedBuffer,
2994 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002995 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002996 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002997 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002998 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002999 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003000 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003001 mClientTid(-1),
3002 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003003 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3004 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003005{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003006 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3007
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003008 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003009 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003010 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003011 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3012 if (sharedBuffer == 0) {
3013 size += bufferSize;
3014 }
3015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 if (client != NULL) {
3017 mCblkMemory = client->heap()->allocate(size);
3018 if (mCblkMemory != 0) {
3019 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3020 if (mCblk) { // construct the shared structure in-place.
3021 new(mCblk) audio_track_cblk_t();
3022 // clear all buffers
3023 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003024 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003025 mChannelCount = channelCount;
3026 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 if (sharedBuffer == 0) {
3028 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3029 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3030 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003031 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003032 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 } else {
3034 mBuffer = sharedBuffer->pointer();
3035 }
3036 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 } else {
3039 LOGE("not enough memory for AudioTrack size=%u", size);
3040 client->heap()->dump("AudioTrack");
3041 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 } else {
3044 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3045 if (mCblk) { // construct the shared structure in-place.
3046 new(mCblk) audio_track_cblk_t();
3047 // clear all buffers
3048 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003049 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003050 mChannelCount = channelCount;
3051 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3053 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3054 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003055 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003056 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3058 }
3059 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003060}
3061
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003062AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003063{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003065 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3066 if (mClient == NULL) {
3067 delete mCblk;
3068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003070 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003071 if (mClient != NULL) {
3072 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3073 mClient.clear();
3074 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003075}
3076
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003077void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003078{
3079 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003080 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003081 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003082 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003083}
3084
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003085bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003086 bool result;
3087 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003088
3089 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003090 if (!result) {
3091 LOGV("stepServer failed acquiring cblk mutex");
3092 mFlags |= STEPSERVER_FAILED;
3093 }
3094 return result;
3095}
3096
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003097void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003098 audio_track_cblk_t* cblk = this->cblk();
3099
3100 cblk->user = 0;
3101 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003102 cblk->userBase = 0;
3103 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003105 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003106}
3107
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003108sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003109{
3110 return mCblkMemory;
3111}
3112
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003113int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003114 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003115}
3116
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003117int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003118 return (const int)mChannelCount;
3119}
3120
3121uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3122 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003123}
3124
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003125void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003126 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003127 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3128 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003129
3130 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003131 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3132 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003133 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 -07003134 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003135 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003136 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003137 return 0;
3138 }
3139
3140 return bufferStart;
3141}
3142
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003143// ----------------------------------------------------------------------------
3144
Eric Laurenta553c252009-07-17 12:17:14 -07003145// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3146AudioFlinger::PlaybackThread::Track::Track(
3147 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003148 const sp<Client>& client,
3149 int streamType,
3150 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003151 uint32_t format,
3152 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003153 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003154 const sp<IMemory>& sharedBuffer,
3155 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003156 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003157 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3158 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003159{
Eric Laurent8a77a992009-09-09 05:16:08 -07003160 if (mCblk != NULL) {
3161 sp<ThreadBase> baseThread = thread.promote();
3162 if (baseThread != 0) {
3163 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3164 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003165 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003166 }
3167 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3168 if (mName < 0) {
3169 LOGE("no more track names available");
3170 }
3171 mVolume[0] = 1.0f;
3172 mVolume[1] = 1.0f;
3173 mStreamType = streamType;
3174 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3175 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003176 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003177 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003178}
3179
Eric Laurenta553c252009-07-17 12:17:14 -07003180AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003181{
Eric Laurenta553c252009-07-17 12:17:14 -07003182 LOGV("PlaybackThread::Track destructor");
3183 sp<ThreadBase> thread = mThread.promote();
3184 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003185 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003186 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003187 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003188}
3189
Eric Laurenta553c252009-07-17 12:17:14 -07003190void AudioFlinger::PlaybackThread::Track::destroy()
3191{
3192 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3193 // by removing it from mTracks vector, so there is a risk that this Tracks's
3194 // desctructor is called. As the destructor needs to lock mLock,
3195 // we must acquire a strong reference on this Track before locking mLock
3196 // here so that the destructor is called only when exiting this function.
3197 // On the other hand, as long as Track::destroy() is only called by
3198 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3199 // this Track with its member mTrack.
3200 sp<Track> keep(this);
3201 { // scope for mLock
3202 sp<ThreadBase> thread = mThread.promote();
3203 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003204 if (!isOutputTrack()) {
3205 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003206 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003207 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003208 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003209
3210 // to track the speaker usage
3211 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003212 }
3213 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003214 }
Eric Laurenta553c252009-07-17 12:17:14 -07003215 Mutex::Autolock _l(thread->mLock);
3216 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3217 playbackThread->destroyTrack_l(this);
3218 }
3219 }
3220}
3221
3222void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003223{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003224 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 -07003225 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003227 mStreamType,
3228 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003229 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003230 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003231 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003232 mState,
3233 mMute,
3234 mFillingUpStatus,
3235 mCblk->sampleRate,
3236 mCblk->volume[0],
3237 mCblk->volume[1],
3238 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003239 mCblk->user,
3240 (int)mMainBuffer,
3241 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003242}
3243
Eric Laurenta553c252009-07-17 12:17:14 -07003244status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003245{
3246 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003247 uint32_t framesReady;
3248 uint32_t framesReq = buffer->frameCount;
3249
3250 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003251 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3252 if (!step()) goto getNextBuffer_exit;
3253 LOGV("stepServer recovered");
3254 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3255 }
3256
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003257 framesReady = cblk->framesReady();
3258
3259 if (LIKELY(framesReady)) {
3260 uint32_t s = cblk->server;
3261 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3262
3263 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3264 if (framesReq > framesReady) {
3265 framesReq = framesReady;
3266 }
3267 if (s + framesReq > bufferEnd) {
3268 framesReq = bufferEnd - s;
3269 }
3270
3271 buffer->raw = getBuffer(s, framesReq);
3272 if (buffer->raw == 0) goto getNextBuffer_exit;
3273
3274 buffer->frameCount = framesReq;
3275 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003276 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003277
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003278getNextBuffer_exit:
3279 buffer->raw = 0;
3280 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003281 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 -07003282 return NOT_ENOUGH_DATA;
3283}
3284
Eric Laurenta553c252009-07-17 12:17:14 -07003285bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003286 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003287
3288 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003289 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003290 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003291 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003292 return true;
3293 }
3294 return false;
3295}
3296
Eric Laurenta553c252009-07-17 12:17:14 -07003297status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003298{
Eric Laurent49f02be2009-11-19 09:00:56 -08003299 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003300 LOGV("start(%d), calling thread %d session %d",
3301 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003302 sp<ThreadBase> thread = mThread.promote();
3303 if (thread != 0) {
3304 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003305 int state = mState;
3306 // here the track could be either new, or restarted
3307 // in both cases "unstop" the track
3308 if (mState == PAUSED) {
3309 mState = TrackBase::RESUMING;
3310 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3311 } else {
3312 mState = TrackBase::ACTIVE;
3313 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3314 }
3315
3316 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3317 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003318 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003319 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003320 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003321 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003322
3323 // to track the speaker usage
3324 if (status == NO_ERROR) {
3325 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3326 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003327 }
3328 if (status == NO_ERROR) {
3329 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3330 playbackThread->addTrack_l(this);
3331 } else {
3332 mState = state;
3333 }
3334 } else {
3335 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003336 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003337 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003338}
3339
Eric Laurenta553c252009-07-17 12:17:14 -07003340void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003341{
Eric Laurenta553c252009-07-17 12:17:14 -07003342 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3343 sp<ThreadBase> thread = mThread.promote();
3344 if (thread != 0) {
3345 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003346 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003347 if (mState > STOPPED) {
3348 mState = STOPPED;
3349 // If the track is not active (PAUSED and buffers full), flush buffers
3350 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3351 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3352 reset();
3353 }
Eric Laurent62443f52009-10-05 20:29:18 -07003354 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003355 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003356 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3357 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003358 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003359 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003360 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003361 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003362
3363 // to track the speaker usage
3364 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003365 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003366 }
3367}
3368
Eric Laurenta553c252009-07-17 12:17:14 -07003369void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003370{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003372 sp<ThreadBase> thread = mThread.promote();
3373 if (thread != 0) {
3374 Mutex::Autolock _l(thread->mLock);
3375 if (mState == ACTIVE || mState == RESUMING) {
3376 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003377 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003378 if (!isOutputTrack()) {
3379 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003380 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003381 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003382 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003383 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003384
3385 // to track the speaker usage
3386 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003387 }
Eric Laurenta553c252009-07-17 12:17:14 -07003388 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003389 }
3390}
3391
Eric Laurenta553c252009-07-17 12:17:14 -07003392void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003393{
3394 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003395 sp<ThreadBase> thread = mThread.promote();
3396 if (thread != 0) {
3397 Mutex::Autolock _l(thread->mLock);
3398 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3399 return;
3400 }
3401 // No point remaining in PAUSED state after a flush => go to
3402 // STOPPED state
3403 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003404
Eric Laurentae29b762011-03-28 18:37:07 -07003405 // do not reset the track if it is still in the process of being stopped or paused.
3406 // this will be done by prepareTracks_l() when the track is stopped.
3407 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3408 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3409 reset();
3410 }
Eric Laurenta553c252009-07-17 12:17:14 -07003411 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003412}
3413
Eric Laurenta553c252009-07-17 12:17:14 -07003414void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003415{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003416 // Do not reset twice to avoid discarding data written just after a flush and before
3417 // the audioflinger thread detects the track is stopped.
3418 if (!mResetDone) {
3419 TrackBase::reset();
3420 // Force underrun condition to avoid false underrun callback until first data is
3421 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003422 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3423 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003424 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003425 mResetDone = true;
3426 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003427}
3428
Eric Laurenta553c252009-07-17 12:17:14 -07003429void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003430{
3431 mMute = muted;
3432}
3433
Eric Laurenta553c252009-07-17 12:17:14 -07003434void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003435{
3436 mVolume[0] = left;
3437 mVolume[1] = right;
3438}
3439
Eric Laurent65b65452010-06-01 23:49:17 -07003440status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3441{
3442 status_t status = DEAD_OBJECT;
3443 sp<ThreadBase> thread = mThread.promote();
3444 if (thread != 0) {
3445 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3446 status = playbackThread->attachAuxEffect(this, EffectId);
3447 }
3448 return status;
3449}
3450
3451void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3452{
3453 mAuxEffectId = EffectId;
3454 mAuxBuffer = buffer;
3455}
3456
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003457// ----------------------------------------------------------------------------
3458
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003459// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003460AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3461 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003464 uint32_t format,
3465 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003467 uint32_t flags,
3468 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003469 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003470 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003471 mOverflow(false)
3472{
Eric Laurent8a77a992009-09-09 05:16:08 -07003473 if (mCblk != NULL) {
3474 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003475 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003476 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003477 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003478 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003479 } else {
3480 mCblk->frameSize = sizeof(int8_t);
3481 }
3482 }
Eric Laurenta553c252009-07-17 12:17:14 -07003483}
3484
3485AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486{
Eric Laurent49f02be2009-11-19 09:00:56 -08003487 sp<ThreadBase> thread = mThread.promote();
3488 if (thread != 0) {
3489 AudioSystem::releaseInput(thread->id());
3490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491}
3492
Eric Laurenta553c252009-07-17 12:17:14 -07003493status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494{
3495 audio_track_cblk_t* cblk = this->cblk();
3496 uint32_t framesAvail;
3497 uint32_t framesReq = buffer->frameCount;
3498
3499 // Check if last stepServer failed, try to step now
3500 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3501 if (!step()) goto getNextBuffer_exit;
3502 LOGV("stepServer recovered");
3503 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3504 }
3505
3506 framesAvail = cblk->framesAvailable_l();
3507
3508 if (LIKELY(framesAvail)) {
3509 uint32_t s = cblk->server;
3510 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3511
3512 if (framesReq > framesAvail) {
3513 framesReq = framesAvail;
3514 }
3515 if (s + framesReq > bufferEnd) {
3516 framesReq = bufferEnd - s;
3517 }
3518
3519 buffer->raw = getBuffer(s, framesReq);
3520 if (buffer->raw == 0) goto getNextBuffer_exit;
3521
3522 buffer->frameCount = framesReq;
3523 return NO_ERROR;
3524 }
3525
3526getNextBuffer_exit:
3527 buffer->raw = 0;
3528 buffer->frameCount = 0;
3529 return NOT_ENOUGH_DATA;
3530}
3531
Eric Laurenta553c252009-07-17 12:17:14 -07003532status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533{
Eric Laurenta553c252009-07-17 12:17:14 -07003534 sp<ThreadBase> thread = mThread.promote();
3535 if (thread != 0) {
3536 RecordThread *recordThread = (RecordThread *)thread.get();
3537 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003538 } else {
3539 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541}
3542
Eric Laurenta553c252009-07-17 12:17:14 -07003543void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544{
Eric Laurenta553c252009-07-17 12:17:14 -07003545 sp<ThreadBase> thread = mThread.promote();
3546 if (thread != 0) {
3547 RecordThread *recordThread = (RecordThread *)thread.get();
3548 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003549 TrackBase::reset();
3550 // Force overerrun condition to avoid false overrun callback until first data is
3551 // read from buffer
3552 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554}
3555
Eric Laurent3fdb1262009-11-07 00:01:32 -08003556void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3557{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003558 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003559 (mClient == NULL) ? getpid() : mClient->pid(),
3560 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003561 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003562 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003563 mFrameCount,
3564 mState,
3565 mCblk->sampleRate,
3566 mCblk->server,
3567 mCblk->user);
3568}
3569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570
3571// ----------------------------------------------------------------------------
3572
Eric Laurenta553c252009-07-17 12:17:14 -07003573AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3574 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003575 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003577 uint32_t format,
3578 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003580 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003581 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582{
Eric Laurenta553c252009-07-17 12:17:14 -07003583
3584 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003585 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003586 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003587 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3588 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3589 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003590 playbackThread->mTracks.add(this);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003591 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3592 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3593 mCblk, mBuffer, mCblk->buffers,
3594 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003595 } else {
3596 LOGW("Error creating output track on thread %p", playbackThread);
3597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598}
3599
Eric Laurenta553c252009-07-17 12:17:14 -07003600AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601{
Eric Laurent6c30a712009-08-10 23:22:32 -07003602 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603}
3604
Eric Laurenta553c252009-07-17 12:17:14 -07003605status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606{
3607 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003608 if (status != NO_ERROR) {
3609 return status;
3610 }
3611
3612 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 mRetryCount = 127;
3614 return status;
3615}
3616
Eric Laurenta553c252009-07-17 12:17:14 -07003617void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618{
3619 Track::stop();
3620 clearBufferQueue();
3621 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003622 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623}
3624
Eric Laurenta553c252009-07-17 12:17:14 -07003625bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626{
3627 Buffer *pInBuffer;
3628 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003629 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003630 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 inBuffer.frameCount = frames;
3632 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003633
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003634 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003635
Eric Laurent62443f52009-10-05 20:29:18 -07003636 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003637 start();
3638 sp<ThreadBase> thread = mThread.promote();
3639 if (thread != 0) {
3640 MixerThread *mixerThread = (MixerThread *)thread.get();
3641 if (mCblk->frameCount > frames){
3642 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3643 uint32_t startFrames = (mCblk->frameCount - frames);
3644 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003645 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003646 pInBuffer->frameCount = startFrames;
3647 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003648 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003649 mBufferQueue.add(pInBuffer);
3650 } else {
3651 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 }
Eric Laurenta553c252009-07-17 12:17:14 -07003654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 }
3656
Eric Laurenta553c252009-07-17 12:17:14 -07003657 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 // First write pending buffers, then new data
3659 if (mBufferQueue.size()) {
3660 pInBuffer = mBufferQueue.itemAt(0);
3661 } else {
3662 pInBuffer = &inBuffer;
3663 }
Eric Laurenta553c252009-07-17 12:17:14 -07003664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 if (pInBuffer->frameCount == 0) {
3666 break;
3667 }
Eric Laurenta553c252009-07-17 12:17:14 -07003668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 if (mOutBuffer.frameCount == 0) {
3670 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003671 nsecs_t startTime = systemTime();
3672 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003673 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003674 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 break;
3676 }
Eric Laurenta553c252009-07-17 12:17:14 -07003677 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003678 if (waitTimeLeftMs >= waitTimeMs) {
3679 waitTimeLeftMs -= waitTimeMs;
3680 } else {
3681 waitTimeLeftMs = 0;
3682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
Eric Laurenta553c252009-07-17 12:17:14 -07003684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003686 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 mCblk->stepUser(outFrames);
3688 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003689 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003691 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 if (pInBuffer->frameCount == 0) {
3694 if (mBufferQueue.size()) {
3695 mBufferQueue.removeAt(0);
3696 delete [] pInBuffer->mBuffer;
3697 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003698 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 -08003699 } else {
3700 break;
3701 }
3702 }
3703 }
Eric Laurenta553c252009-07-17 12:17:14 -07003704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 // If we could not write all frames, allocate a buffer and queue it for next time.
3706 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003707 sp<ThreadBase> thread = mThread.promote();
3708 if (thread != 0 && !thread->standby()) {
3709 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3710 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003711 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003712 pInBuffer->frameCount = inBuffer.frameCount;
3713 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003714 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003715 mBufferQueue.add(pInBuffer);
3716 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3717 } else {
3718 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 }
3721 }
Eric Laurenta553c252009-07-17 12:17:14 -07003722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003724 // 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 -08003725 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003726 if (frames == 0 && mBufferQueue.size() == 0) {
3727 if (mCblk->user < mCblk->frameCount) {
3728 frames = mCblk->frameCount - mCblk->user;
3729 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003730 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003731 pInBuffer->frameCount = frames;
3732 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003733 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003734 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003735 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003736 stop();
3737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
3739
Eric Laurenta553c252009-07-17 12:17:14 -07003740 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741}
3742
Eric Laurenta553c252009-07-17 12:17:14 -07003743status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744{
3745 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 status_t result;
3747 audio_track_cblk_t* cblk = mCblk;
3748 uint32_t framesReq = buffer->frameCount;
3749
Eric Laurenta553c252009-07-17 12:17:14 -07003750// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 uint32_t framesAvail = cblk->framesAvailable();
3754
Eric Laurenta553c252009-07-17 12:17:14 -07003755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003757 Mutex::Autolock _l(cblk->lock);
3758 goto start_loop_here;
3759 while (framesAvail == 0) {
3760 active = mActive;
3761 if (UNLIKELY(!active)) {
3762 LOGV("Not active and NO_MORE_BUFFERS");
3763 return AudioTrack::NO_MORE_BUFFERS;
3764 }
3765 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3766 if (result != NO_ERROR) {
3767 return AudioTrack::NO_MORE_BUFFERS;
3768 }
3769 // read the server count again
3770 start_loop_here:
3771 framesAvail = cblk->framesAvailable_l();
3772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
3774
Eric Laurenta553c252009-07-17 12:17:14 -07003775// if (framesAvail < framesReq) {
3776// return AudioTrack::NO_MORE_BUFFERS;
3777// }
3778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 if (framesReq > framesAvail) {
3780 framesReq = framesAvail;
3781 }
3782
3783 uint32_t u = cblk->user;
3784 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3785
3786 if (u + framesReq > bufferEnd) {
3787 framesReq = bufferEnd - u;
3788 }
3789
3790 buffer->frameCount = framesReq;
3791 buffer->raw = (void *)cblk->buffer(u);
3792 return NO_ERROR;
3793}
3794
3795
Eric Laurenta553c252009-07-17 12:17:14 -07003796void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797{
3798 size_t size = mBufferQueue.size();
3799 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 for (size_t i = 0; i < size; i++) {
3802 pBuffer = mBufferQueue.itemAt(i);
3803 delete [] pBuffer->mBuffer;
3804 delete pBuffer;
3805 }
3806 mBufferQueue.clear();
3807}
3808
3809// ----------------------------------------------------------------------------
3810
3811AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3812 : RefBase(),
3813 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003814 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 mPid(pid)
3816{
3817 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3818}
3819
Eric Laurentb9481d82009-09-17 05:12:56 -07003820// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821AudioFlinger::Client::~Client()
3822{
Eric Laurentb9481d82009-09-17 05:12:56 -07003823 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824}
3825
3826const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3827{
3828 return mMemoryDealer;
3829}
3830
3831// ----------------------------------------------------------------------------
3832
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003833AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3834 const sp<IAudioFlingerClient>& client,
3835 pid_t pid)
3836 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3837{
3838}
3839
3840AudioFlinger::NotificationClient::~NotificationClient()
3841{
3842 mClient.clear();
3843}
3844
3845void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3846{
3847 sp<NotificationClient> keep(this);
3848 {
3849 mAudioFlinger->removeNotificationClient(mPid);
3850 }
3851}
3852
3853// ----------------------------------------------------------------------------
3854
Eric Laurenta553c252009-07-17 12:17:14 -07003855AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003856 : BnAudioTrack(),
3857 mTrack(track)
3858{
3859}
3860
3861AudioFlinger::TrackHandle::~TrackHandle() {
3862 // just stop the track on deletion, associated resources
3863 // will be freed from the main thread once all pending buffers have
3864 // been played. Unless it's not in the active track list, in which
3865 // case we free everything now...
3866 mTrack->destroy();
3867}
3868
3869status_t AudioFlinger::TrackHandle::start() {
3870 return mTrack->start();
3871}
3872
3873void AudioFlinger::TrackHandle::stop() {
3874 mTrack->stop();
3875}
3876
3877void AudioFlinger::TrackHandle::flush() {
3878 mTrack->flush();
3879}
3880
3881void AudioFlinger::TrackHandle::mute(bool e) {
3882 mTrack->mute(e);
3883}
3884
3885void AudioFlinger::TrackHandle::pause() {
3886 mTrack->pause();
3887}
3888
3889void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3890 mTrack->setVolume(left, right);
3891}
3892
3893sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3894 return mTrack->getCblk();
3895}
3896
Eric Laurent65b65452010-06-01 23:49:17 -07003897status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3898{
3899 return mTrack->attachAuxEffect(EffectId);
3900}
3901
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003902status_t AudioFlinger::TrackHandle::onTransact(
3903 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3904{
3905 return BnAudioTrack::onTransact(code, data, reply, flags);
3906}
3907
3908// ----------------------------------------------------------------------------
3909
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003910sp<IAudioRecord> AudioFlinger::openRecord(
3911 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003912 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003913 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003914 uint32_t format,
3915 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003916 int frameCount,
3917 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003918 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003919 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003920{
Eric Laurenta553c252009-07-17 12:17:14 -07003921 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003922 sp<RecordHandle> recordHandle;
3923 sp<Client> client;
3924 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003925 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003926 RecordThread *thread;
3927 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003928 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003929
3930 // check calling permissions
3931 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003932 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003933 goto Exit;
3934 }
3935
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003936 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003937 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003938 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003939 thread = checkRecordThread_l(input);
3940 if (thread == NULL) {
3941 lStatus = BAD_VALUE;
3942 goto Exit;
3943 }
3944
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003945 wclient = mClients.valueFor(pid);
3946 if (wclient != NULL) {
3947 client = wclient.promote();
3948 } else {
3949 client = new Client(this, pid);
3950 mClients.add(pid, client);
3951 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003952
Eric Laurent65b65452010-06-01 23:49:17 -07003953 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003954 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003955 lSessionId = *sessionId;
3956 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07003957 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07003958 if (sessionId != NULL) {
3959 *sessionId = lSessionId;
3960 }
3961 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003962 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07003963 recordTrack = thread->createRecordTrack_l(client,
3964 sampleRate,
3965 format,
3966 channelMask,
3967 frameCount,
3968 flags,
3969 lSessionId,
3970 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003971 }
Eric Laurent464d5b32011-06-17 21:29:58 -07003972 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003973 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3974 // destructor is called by the TrackBase destructor with mLock held
3975 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 goto Exit;
3978 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003979
3980 // return to handle to client
3981 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003982 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003983
3984Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003985 if (status) {
3986 *status = lStatus;
3987 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003988 return recordHandle;
3989}
3990
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003991// ----------------------------------------------------------------------------
3992
Eric Laurenta553c252009-07-17 12:17:14 -07003993AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003994 : BnAudioRecord(),
3995 mRecordTrack(recordTrack)
3996{
3997}
3998
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003999AudioFlinger::RecordHandle::~RecordHandle() {
4000 stop();
4001}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004002
4003status_t AudioFlinger::RecordHandle::start() {
4004 LOGV("RecordHandle::start()");
4005 return mRecordTrack->start();
4006}
4007
4008void AudioFlinger::RecordHandle::stop() {
4009 LOGV("RecordHandle::stop()");
4010 mRecordTrack->stop();
4011}
4012
4013sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4014 return mRecordTrack->getCblk();
4015}
4016
4017status_t AudioFlinger::RecordHandle::onTransact(
4018 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4019{
4020 return BnAudioRecord::onTransact(code, data, reply, flags);
4021}
4022
4023// ----------------------------------------------------------------------------
4024
Eric Laurent464d5b32011-06-17 21:29:58 -07004025AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4026 AudioStreamIn *input,
4027 uint32_t sampleRate,
4028 uint32_t channels,
4029 int id,
4030 uint32_t device) :
4031 ThreadBase(audioFlinger, id, device),
4032 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004033{
Eric Laurent464d5b32011-06-17 21:29:58 -07004034 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004035
4036 snprintf(mName, kNameLength, "AudioIn_%d", id);
4037
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004038 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004039 mReqSampleRate = sampleRate;
4040 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004041}
4042
Eric Laurenta553c252009-07-17 12:17:14 -07004043
4044AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004045{
Eric Laurenta553c252009-07-17 12:17:14 -07004046 delete[] mRsmpInBuffer;
4047 if (mResampler != 0) {
4048 delete mResampler;
4049 delete[] mRsmpOutBuffer;
4050 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004051}
4052
Eric Laurenta553c252009-07-17 12:17:14 -07004053void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004054{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004055 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004056}
Eric Laurent49f02be2009-11-19 09:00:56 -08004057
Eric Laurenta553c252009-07-17 12:17:14 -07004058bool AudioFlinger::RecordThread::threadLoop()
4059{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004060 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004061 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004062 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004063
Eric Laurent4712baa2010-09-30 16:12:31 -07004064 nsecs_t lastWarning = 0;
4065
Eric Laurent6dbdc402011-07-22 09:04:31 -07004066 acquireWakeLock();
4067
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004068 // start recording
4069 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004070
Eric Laurenta553c252009-07-17 12:17:14 -07004071 processConfigEvents();
4072
4073 { // scope for mLock
4074 Mutex::Autolock _l(mLock);
4075 checkForNewParameters_l();
4076 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4077 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004078 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004079 mStandby = true;
4080 }
4081
4082 if (exitPending()) break;
4083
Eric Laurent6dbdc402011-07-22 09:04:31 -07004084 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004085 LOGV("RecordThread: loop stopping");
4086 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004087 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004088 LOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004089 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004090 continue;
4091 }
4092 if (mActiveTrack != 0) {
4093 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004094 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004095 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004096 mStandby = true;
4097 }
Eric Laurenta553c252009-07-17 12:17:14 -07004098 mActiveTrack.clear();
4099 mStartStopCond.broadcast();
4100 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004101 if (mReqChannelCount != mActiveTrack->channelCount()) {
4102 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004103 mStartStopCond.broadcast();
4104 } else if (mBytesRead != 0) {
4105 // record start succeeds only if first read from audio input
4106 // succeeds
4107 if (mBytesRead > 0) {
4108 mActiveTrack->mState = TrackBase::ACTIVE;
4109 } else {
4110 mActiveTrack.clear();
4111 }
4112 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004113 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004114 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004115 }
Eric Laurenta553c252009-07-17 12:17:14 -07004116 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004117 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004118 }
4119
4120 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004121 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4122 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004123 unlockEffectChains(effectChains);
4124 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004125 continue;
4126 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004127 for (size_t i = 0; i < effectChains.size(); i ++) {
4128 effectChains[i]->process_l();
4129 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004130
Eric Laurenta553c252009-07-17 12:17:14 -07004131 buffer.frameCount = mFrameCount;
4132 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4133 size_t framesOut = buffer.frameCount;
4134 if (mResampler == 0) {
4135 // no resampling
4136 while (framesOut) {
4137 size_t framesIn = mFrameCount - mRsmpInIndex;
4138 if (framesIn) {
4139 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4140 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4141 if (framesIn > framesOut)
4142 framesIn = framesOut;
4143 mRsmpInIndex += framesIn;
4144 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004145 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004146 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004147 memcpy(dst, src, framesIn * mFrameSize);
4148 } else {
4149 int16_t *src16 = (int16_t *)src;
4150 int16_t *dst16 = (int16_t *)dst;
4151 if (mChannelCount == 1) {
4152 while (framesIn--) {
4153 *dst16++ = *src16;
4154 *dst16++ = *src16++;
4155 }
4156 } else {
4157 while (framesIn--) {
4158 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4159 src16 += 2;
4160 }
4161 }
4162 }
4163 }
4164 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004165 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004166 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004167 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004168 framesOut = 0;
4169 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004170 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004171 mRsmpInIndex = 0;
4172 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004173 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004174 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004175 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004176 // Force input into standby so that it tries to
4177 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004178 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004179 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004180 }
Eric Laurenta553c252009-07-17 12:17:14 -07004181 mRsmpInIndex = mFrameCount;
4182 framesOut = 0;
4183 buffer.frameCount = 0;
4184 }
4185 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004186 }
4187 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004188 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004189
Eric Laurenta553c252009-07-17 12:17:14 -07004190 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4191 // alter output frame count as if we were expecting stereo samples
4192 if (mChannelCount == 1 && mReqChannelCount == 1) {
4193 framesOut >>= 1;
4194 }
4195 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4196 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4197 // are 32 bit aligned which should be always true.
4198 if (mChannelCount == 2 && mReqChannelCount == 1) {
4199 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4200 // the resampler always outputs stereo samples: do post stereo to mono conversion
4201 int16_t *src = (int16_t *)mRsmpOutBuffer;
4202 int16_t *dst = buffer.i16;
4203 while (framesOut--) {
4204 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4205 src += 2;
4206 }
4207 } else {
4208 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4209 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004210
Eric Laurenta553c252009-07-17 12:17:14 -07004211 }
4212 mActiveTrack->releaseBuffer(&buffer);
4213 mActiveTrack->overflow();
4214 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004215 // client isn't retrieving buffers fast enough
4216 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004217 if (!mActiveTrack->setOverflow()) {
4218 nsecs_t now = systemTime();
4219 if ((now - lastWarning) > kWarningThrottle) {
4220 LOGW("RecordThread: buffer overflow");
4221 lastWarning = now;
4222 }
4223 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004224 // Release the processor for a while before asking for a new buffer.
4225 // This will give the application more chance to read from the buffer and
4226 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004227 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004228 }
4229 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004230 // enable changes in effect chain
4231 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004232 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004233 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004234
Eric Laurenta553c252009-07-17 12:17:14 -07004235 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004236 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004237 }
Eric Laurenta553c252009-07-17 12:17:14 -07004238 mActiveTrack.clear();
4239
Eric Laurent49f02be2009-11-19 09:00:56 -08004240 mStartStopCond.broadcast();
4241
Eric Laurent6dbdc402011-07-22 09:04:31 -07004242 releaseWakeLock();
4243
Eric Laurenta553c252009-07-17 12:17:14 -07004244 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004245 return false;
4246}
4247
Eric Laurent464d5b32011-06-17 21:29:58 -07004248
4249sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4250 const sp<AudioFlinger::Client>& client,
4251 uint32_t sampleRate,
4252 int format,
4253 int channelMask,
4254 int frameCount,
4255 uint32_t flags,
4256 int sessionId,
4257 status_t *status)
4258{
4259 sp<RecordTrack> track;
4260 status_t lStatus;
4261
4262 lStatus = initCheck();
4263 if (lStatus != NO_ERROR) {
4264 LOGE("Audio driver not initialized.");
4265 goto Exit;
4266 }
4267
4268 { // scope for mLock
4269 Mutex::Autolock _l(mLock);
4270
4271 track = new RecordTrack(this, client, sampleRate,
4272 format, channelMask, frameCount, flags, sessionId);
4273
4274 if (track->getCblk() == NULL) {
4275 lStatus = NO_MEMORY;
4276 goto Exit;
4277 }
4278
4279 mTrack = track.get();
4280
4281 }
4282 lStatus = NO_ERROR;
4283
4284Exit:
4285 if (status) {
4286 *status = lStatus;
4287 }
4288 return track;
4289}
4290
Eric Laurenta553c252009-07-17 12:17:14 -07004291status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004292{
Eric Laurenta553c252009-07-17 12:17:14 -07004293 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004294 sp <ThreadBase> strongMe = this;
4295 status_t status = NO_ERROR;
4296 {
4297 AutoMutex lock(&mLock);
4298 if (mActiveTrack != 0) {
4299 if (recordTrack != mActiveTrack.get()) {
4300 status = -EBUSY;
4301 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004302 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004303 }
4304 return status;
4305 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004306
Eric Laurent49f02be2009-11-19 09:00:56 -08004307 recordTrack->mState = TrackBase::IDLE;
4308 mActiveTrack = recordTrack;
4309 mLock.unlock();
4310 status_t status = AudioSystem::startInput(mId);
4311 mLock.lock();
4312 if (status != NO_ERROR) {
4313 mActiveTrack.clear();
4314 return status;
4315 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004316 mRsmpInIndex = mFrameCount;
4317 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004318 if (mResampler != NULL) {
4319 mResampler->reset();
4320 }
4321 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004322 // signal thread to start
4323 LOGV("Signal record thread");
4324 mWaitWorkCV.signal();
4325 // do not wait for mStartStopCond if exiting
4326 if (mExiting) {
4327 mActiveTrack.clear();
4328 status = INVALID_OPERATION;
4329 goto startError;
4330 }
4331 mStartStopCond.wait(mLock);
4332 if (mActiveTrack == 0) {
4333 LOGV("Record failed to start");
4334 status = BAD_VALUE;
4335 goto startError;
4336 }
Eric Laurenta553c252009-07-17 12:17:14 -07004337 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004338 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004339 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004340startError:
4341 AudioSystem::stopInput(mId);
4342 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004343}
4344
Eric Laurenta553c252009-07-17 12:17:14 -07004345void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4346 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004347 sp <ThreadBase> strongMe = this;
4348 {
4349 AutoMutex lock(&mLock);
4350 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4351 mActiveTrack->mState = TrackBase::PAUSING;
4352 // do not wait for mStartStopCond if exiting
4353 if (mExiting) {
4354 return;
4355 }
4356 mStartStopCond.wait(mLock);
4357 // if we have been restarted, recordTrack == mActiveTrack.get() here
4358 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4359 mLock.unlock();
4360 AudioSystem::stopInput(mId);
4361 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004362 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004363 }
4364 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004365 }
4366}
4367
Eric Laurenta553c252009-07-17 12:17:14 -07004368status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369{
4370 const size_t SIZE = 256;
4371 char buffer[SIZE];
4372 String8 result;
4373 pid_t pid = 0;
4374
Eric Laurent3fdb1262009-11-07 00:01:32 -08004375 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4376 result.append(buffer);
4377
4378 if (mActiveTrack != 0) {
4379 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004380 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004381 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004383
4384 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4385 result.append(buffer);
4386 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4387 result.append(buffer);
4388 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4389 result.append(buffer);
4390 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4391 result.append(buffer);
4392 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4393 result.append(buffer);
4394
4395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 } else {
4397 result.append("No record client\n");
4398 }
4399 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004400
4401 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004402 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 return NO_ERROR;
4405}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004406
Eric Laurenta553c252009-07-17 12:17:14 -07004407status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4408{
4409 size_t framesReq = buffer->frameCount;
4410 size_t framesReady = mFrameCount - mRsmpInIndex;
4411 int channelCount;
4412
4413 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004414 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004415 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004416 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004417 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004418 // Force input into standby so that it tries to
4419 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004420 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004421 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004422 }
Eric Laurenta553c252009-07-17 12:17:14 -07004423 buffer->raw = 0;
4424 buffer->frameCount = 0;
4425 return NOT_ENOUGH_DATA;
4426 }
4427 mRsmpInIndex = 0;
4428 framesReady = mFrameCount;
4429 }
4430
4431 if (framesReq > framesReady) {
4432 framesReq = framesReady;
4433 }
4434
4435 if (mChannelCount == 1 && mReqChannelCount == 2) {
4436 channelCount = 1;
4437 } else {
4438 channelCount = 2;
4439 }
4440 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4441 buffer->frameCount = framesReq;
4442 return NO_ERROR;
4443}
4444
4445void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4446{
4447 mRsmpInIndex += buffer->frameCount;
4448 buffer->frameCount = 0;
4449}
4450
4451bool AudioFlinger::RecordThread::checkForNewParameters_l()
4452{
4453 bool reconfig = false;
4454
Eric Laurent8fce46a2009-08-04 09:45:33 -07004455 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004456 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004457 String8 keyValuePair = mNewParameters[0];
4458 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004459 int value;
4460 int reqFormat = mFormat;
4461 int reqSamplingRate = mReqSampleRate;
4462 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004463
Eric Laurenta553c252009-07-17 12:17:14 -07004464 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4465 reqSamplingRate = value;
4466 reconfig = true;
4467 }
4468 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4469 reqFormat = value;
4470 reconfig = true;
4471 }
4472 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004473 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004474 reconfig = true;
4475 }
4476 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4477 // do not accept frame count changes if tracks are open as the track buffer
4478 // size depends on frame count and correct behavior would not be garantied
4479 // if frame count is changed after track creation
4480 if (mActiveTrack != 0) {
4481 status = INVALID_OPERATION;
4482 } else {
4483 reconfig = true;
4484 }
4485 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004486 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4487 // forward device change to effects that have requested to be
4488 // aware of attached audio device.
4489 for (size_t i = 0; i < mEffectChains.size(); i++) {
4490 mEffectChains[i]->setDevice_l(value);
4491 }
4492 // store input device and output device but do not forward output device to audio HAL.
4493 // Note that status is ignored by the caller for output device
4494 // (see AudioFlinger::setParameters()
4495 if (value & AUDIO_DEVICE_OUT_ALL) {
4496 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4497 status = BAD_VALUE;
4498 } else {
4499 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4500 }
4501 mDevice |= (uint32_t)value;
4502 }
Eric Laurenta553c252009-07-17 12:17:14 -07004503 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004504 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004505 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004506 mInput->stream->common.standby(&mInput->stream->common);
4507 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004508 }
4509 if (reconfig) {
4510 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004511 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004512 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004513 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4514 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004515 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004516 status = NO_ERROR;
4517 }
4518 if (status == NO_ERROR) {
4519 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004520 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004521 }
4522 }
4523 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004524
4525 mNewParameters.removeAt(0);
4526
Eric Laurenta553c252009-07-17 12:17:14 -07004527 mParamStatus = status;
4528 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004529 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004530 }
4531 return reconfig;
4532}
4533
4534String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4535{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004536 char *s;
4537 String8 out_s8;
4538
Dima Zavin31f188892011-04-18 16:57:27 -07004539 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004540 out_s8 = String8(s);
4541 free(s);
4542 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004543}
4544
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004545void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004546 AudioSystem::OutputDescriptor desc;
4547 void *param2 = 0;
4548
4549 switch (event) {
4550 case AudioSystem::INPUT_OPENED:
4551 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004552 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004553 desc.samplingRate = mSampleRate;
4554 desc.format = mFormat;
4555 desc.frameCount = mFrameCount;
4556 desc.latency = 0;
4557 param2 = &desc;
4558 break;
4559
4560 case AudioSystem::INPUT_CLOSED:
4561 default:
4562 break;
4563 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004564 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004565}
4566
4567void AudioFlinger::RecordThread::readInputParameters()
4568{
4569 if (mRsmpInBuffer) delete mRsmpInBuffer;
4570 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4571 if (mResampler) delete mResampler;
4572 mResampler = 0;
4573
Dima Zavin31f188892011-04-18 16:57:27 -07004574 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004575 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4576 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004577 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4578 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4579 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004580 mFrameCount = mInputBytes / mFrameSize;
4581 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4582
4583 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4584 {
4585 int channelCount;
4586 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4587 // stereo to mono post process as the resampler always outputs stereo.
4588 if (mChannelCount == 1 && mReqChannelCount == 2) {
4589 channelCount = 1;
4590 } else {
4591 channelCount = 2;
4592 }
4593 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4594 mResampler->setSampleRate(mSampleRate);
4595 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4596 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4597
4598 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4599 if (mChannelCount == 1 && mReqChannelCount == 1) {
4600 mFrameCount >>= 1;
4601 }
4602
4603 }
4604 mRsmpInIndex = mFrameCount;
4605}
4606
Eric Laurent47d0a922010-02-26 02:47:27 -08004607unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4608{
Dima Zavin31f188892011-04-18 16:57:27 -07004609 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004610}
4611
Eric Laurent464d5b32011-06-17 21:29:58 -07004612uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4613{
4614 Mutex::Autolock _l(mLock);
4615 uint32_t result = 0;
4616 if (getEffectChain_l(sessionId) != 0) {
4617 result = EFFECT_SESSION;
4618 }
4619
4620 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4621 result |= TRACK_SESSION;
4622 }
4623
4624 return result;
4625}
4626
Eric Laurenta553c252009-07-17 12:17:14 -07004627// ----------------------------------------------------------------------------
4628
Eric Laurentddb78e72009-07-28 08:44:33 -07004629int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004630 uint32_t *pSamplingRate,
4631 uint32_t *pFormat,
4632 uint32_t *pChannels,
4633 uint32_t *pLatencyMs,
4634 uint32_t flags)
4635{
4636 status_t status;
4637 PlaybackThread *thread = NULL;
4638 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4639 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4640 uint32_t format = pFormat ? *pFormat : 0;
4641 uint32_t channels = pChannels ? *pChannels : 0;
4642 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004643 audio_stream_out_t *outStream;
4644 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004645
4646 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4647 pDevices ? *pDevices : 0,
4648 samplingRate,
4649 format,
4650 channels,
4651 flags);
4652
4653 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004654 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004655 }
Dima Zavin31f188892011-04-18 16:57:27 -07004656
Eric Laurenta553c252009-07-17 12:17:14 -07004657 Mutex::Autolock _l(mLock);
4658
Dima Zavin31f188892011-04-18 16:57:27 -07004659 outHwDev = findSuitableHwDev_l(*pDevices);
4660 if (outHwDev == NULL)
4661 return 0;
4662
4663 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4664 &channels, &samplingRate, &outStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004665 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004666 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004667 samplingRate,
4668 format,
4669 channels,
4670 status);
4671
4672 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004673 if (outStream != NULL) {
4674 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004675 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004676
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004677 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4678 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4679 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004680 thread = new DirectOutputThread(this, output, id, *pDevices);
4681 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004682 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004683 thread = new MixerThread(this, output, id, *pDevices);
4684 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004685 }
Eric Laurent65b65452010-06-01 23:49:17 -07004686 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004687
4688 if (pSamplingRate) *pSamplingRate = samplingRate;
4689 if (pFormat) *pFormat = format;
4690 if (pChannels) *pChannels = channels;
4691 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004692
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004693 // notify client processes of the new output creation
4694 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004695 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004696 }
4697
Eric Laurent9cc489a22009-12-05 05:20:01 -08004698 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004699}
4700
Eric Laurentddb78e72009-07-28 08:44:33 -07004701int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004702{
4703 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004704 MixerThread *thread1 = checkMixerThread_l(output1);
4705 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004706
Eric Laurentddb78e72009-07-28 08:44:33 -07004707 if (thread1 == NULL || thread2 == NULL) {
4708 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4709 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004710 }
4711
Eric Laurent464d5b32011-06-17 21:29:58 -07004712 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004713 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004714 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004715 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004716 // notify client processes of the new output creation
4717 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004718 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004719}
4720
Eric Laurentddb78e72009-07-28 08:44:33 -07004721status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004722{
Eric Laurent49018a52009-08-04 08:37:05 -07004723 // keep strong reference on the playback thread so that
4724 // it is not destroyed while exit() is executed
4725 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004726 {
4727 Mutex::Autolock _l(mLock);
4728 thread = checkPlaybackThread_l(output);
4729 if (thread == NULL) {
4730 return BAD_VALUE;
4731 }
4732
Eric Laurentddb78e72009-07-28 08:44:33 -07004733 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004734
Eric Laurent464d5b32011-06-17 21:29:58 -07004735 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004737 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004738 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004739 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004740 }
4741 }
4742 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004743 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004744 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004745 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004746 }
4747 thread->exit();
4748
Eric Laurent464d5b32011-06-17 21:29:58 -07004749 if (thread->type() != ThreadBase::DUPLICATING) {
Dima Zavin31f188892011-04-18 16:57:27 -07004750 AudioStreamOut *out = thread->getOutput();
4751 out->hwDev->close_output_stream(out->hwDev, out->stream);
4752 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07004753 }
Eric Laurenta553c252009-07-17 12:17:14 -07004754 return NO_ERROR;
4755}
4756
Eric Laurentddb78e72009-07-28 08:44:33 -07004757status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004758{
4759 Mutex::Autolock _l(mLock);
4760 PlaybackThread *thread = checkPlaybackThread_l(output);
4761
4762 if (thread == NULL) {
4763 return BAD_VALUE;
4764 }
4765
Eric Laurentddb78e72009-07-28 08:44:33 -07004766 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004767 thread->suspend();
4768
4769 return NO_ERROR;
4770}
4771
Eric Laurentddb78e72009-07-28 08:44:33 -07004772status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004773{
4774 Mutex::Autolock _l(mLock);
4775 PlaybackThread *thread = checkPlaybackThread_l(output);
4776
4777 if (thread == NULL) {
4778 return BAD_VALUE;
4779 }
4780
Eric Laurentddb78e72009-07-28 08:44:33 -07004781 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004782
4783 thread->restore();
4784
4785 return NO_ERROR;
4786}
4787
Eric Laurentddb78e72009-07-28 08:44:33 -07004788int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004789 uint32_t *pSamplingRate,
4790 uint32_t *pFormat,
4791 uint32_t *pChannels,
4792 uint32_t acoustics)
4793{
4794 status_t status;
4795 RecordThread *thread = NULL;
4796 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4797 uint32_t format = pFormat ? *pFormat : 0;
4798 uint32_t channels = pChannels ? *pChannels : 0;
4799 uint32_t reqSamplingRate = samplingRate;
4800 uint32_t reqFormat = format;
4801 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07004802 audio_stream_in_t *inStream;
4803 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004804
4805 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004806 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004807 }
Dima Zavin31f188892011-04-18 16:57:27 -07004808
Eric Laurenta553c252009-07-17 12:17:14 -07004809 Mutex::Autolock _l(mLock);
4810
Dima Zavin31f188892011-04-18 16:57:27 -07004811 inHwDev = findSuitableHwDev_l(*pDevices);
4812 if (inHwDev == NULL)
4813 return 0;
4814
4815 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4816 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004817 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07004818 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004819 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004820 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004821 samplingRate,
4822 format,
4823 channels,
4824 acoustics,
4825 status);
4826
4827 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4828 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4829 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07004830 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004831 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07004832 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004833 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004834 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07004835 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4836 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004837 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07004838 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07004839 }
4840
Dima Zavin31f188892011-04-18 16:57:27 -07004841 if (inStream != NULL) {
4842 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4843
Eric Laurent464d5b32011-06-17 21:29:58 -07004844 int id = nextUniqueId();
4845 // Start record thread
4846 // RecorThread require both input and output device indication to forward to audio
4847 // pre processing modules
4848 uint32_t device = (*pDevices) | primaryOutputDevice_l();
4849 thread = new RecordThread(this,
4850 input,
4851 reqSamplingRate,
4852 reqChannels,
4853 id,
4854 device);
Eric Laurent65b65452010-06-01 23:49:17 -07004855 mRecordThreads.add(id, thread);
4856 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004857 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4858 if (pFormat) *pFormat = format;
4859 if (pChannels) *pChannels = reqChannels;
4860
Dima Zavin31f188892011-04-18 16:57:27 -07004861 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004862
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004863 // notify client processes of the new input creation
4864 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004865 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004866 }
4867
Eric Laurent9cc489a22009-12-05 05:20:01 -08004868 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004869}
4870
Eric Laurentddb78e72009-07-28 08:44:33 -07004871status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004872{
Eric Laurent49018a52009-08-04 08:37:05 -07004873 // keep strong reference on the record thread so that
4874 // it is not destroyed while exit() is executed
4875 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004876 {
4877 Mutex::Autolock _l(mLock);
4878 thread = checkRecordThread_l(input);
4879 if (thread == NULL) {
4880 return BAD_VALUE;
4881 }
4882
Eric Laurentddb78e72009-07-28 08:44:33 -07004883 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004884 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004885 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004886 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004887 }
4888 thread->exit();
4889
Dima Zavin31f188892011-04-18 16:57:27 -07004890 AudioStreamIn *in = thread->getInput();
4891 in->hwDev->close_input_stream(in->hwDev, in->stream);
4892 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07004893
Eric Laurenta553c252009-07-17 12:17:14 -07004894 return NO_ERROR;
4895}
4896
Eric Laurentddb78e72009-07-28 08:44:33 -07004897status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004898{
4899 Mutex::Autolock _l(mLock);
4900 MixerThread *dstThread = checkMixerThread_l(output);
4901 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004902 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004903 return BAD_VALUE;
4904 }
4905
Eric Laurentddb78e72009-07-28 08:44:33 -07004906 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004907 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004908
4909 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004910 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004911 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07004912 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004913 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004914 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004915 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004916 }
Eric Laurentd069f322009-09-01 05:56:26 -07004917
Eric Laurenta553c252009-07-17 12:17:14 -07004918 return NO_ERROR;
4919}
4920
Eric Laurent65b65452010-06-01 23:49:17 -07004921
4922int AudioFlinger::newAudioSessionId()
4923{
Eric Laurent464d5b32011-06-17 21:29:58 -07004924 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004925}
4926
Eric Laurenta553c252009-07-17 12:17:14 -07004927// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004928AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004929{
4930 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004931 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4932 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004933 }
Eric Laurenta553c252009-07-17 12:17:14 -07004934 return thread;
4935}
4936
4937// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004938AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004939{
4940 PlaybackThread *thread = checkPlaybackThread_l(output);
4941 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004942 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004943 thread = NULL;
4944 }
4945 }
4946 return (MixerThread *)thread;
4947}
4948
4949// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004950AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004951{
4952 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004953 if (mRecordThreads.indexOfKey(input) >= 0) {
4954 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004955 }
Eric Laurenta553c252009-07-17 12:17:14 -07004956 return thread;
4957}
4958
Eric Laurent464d5b32011-06-17 21:29:58 -07004959uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07004960{
Eric Laurent464d5b32011-06-17 21:29:58 -07004961 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07004962}
4963
Eric Laurent464d5b32011-06-17 21:29:58 -07004964AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
4965{
4966 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4967 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4968 if (thread->getOutput()->hwDev == mPrimaryHardwareDev) {
4969 return thread;
4970 }
4971 }
4972 return NULL;
4973}
4974
4975uint32_t AudioFlinger::primaryOutputDevice_l()
4976{
4977 PlaybackThread *thread = primaryPlaybackThread_l();
4978
4979 if (thread == NULL) {
4980 return 0;
4981 }
4982
4983 return thread->device();
4984}
4985
4986
Eric Laurent65b65452010-06-01 23:49:17 -07004987// ----------------------------------------------------------------------------
4988// Effect management
4989// ----------------------------------------------------------------------------
4990
4991
Eric Laurent65b65452010-06-01 23:49:17 -07004992status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4993{
4994 Mutex::Autolock _l(mLock);
4995 return EffectQueryNumberEffects(numEffects);
4996}
4997
Eric Laurent53334cd2010-06-23 17:38:20 -07004998status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004999{
5000 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005001 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005002}
5003
5004status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5005{
5006 Mutex::Autolock _l(mLock);
5007 return EffectGetDescriptor(pUuid, descriptor);
5008}
5009
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005010
Eric Laurent65b65452010-06-01 23:49:17 -07005011sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5012 effect_descriptor_t *pDesc,
5013 const sp<IEffectClient>& effectClient,
5014 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005015 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005016 int sessionId,
5017 status_t *status,
5018 int *id,
5019 int *enabled)
5020{
5021 status_t lStatus = NO_ERROR;
5022 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005023 effect_descriptor_t desc;
5024 sp<Client> client;
5025 wp<Client> wclient;
5026
Eric Laurent464d5b32011-06-17 21:29:58 -07005027 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5028 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005029
5030 if (pDesc == NULL) {
5031 lStatus = BAD_VALUE;
5032 goto Exit;
5033 }
5034
Eric Laurent98c92592010-09-23 16:10:16 -07005035 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005036 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005037 lStatus = PERMISSION_DENIED;
5038 goto Exit;
5039 }
5040
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005041 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005042 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005043 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005044 lStatus = PERMISSION_DENIED;
5045 goto Exit;
5046 }
5047
Eric Laurent464d5b32011-06-17 21:29:58 -07005048 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005049 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005050 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005051 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005052 lStatus = BAD_VALUE;
5053 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005054 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005055 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005056 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005057 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005058 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005059 }
5060 }
5061
Eric Laurent65b65452010-06-01 23:49:17 -07005062 {
5063 Mutex::Autolock _l(mLock);
5064
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005065
Eric Laurent65b65452010-06-01 23:49:17 -07005066 if (!EffectIsNullUuid(&pDesc->uuid)) {
5067 // if uuid is specified, request effect descriptor
5068 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5069 if (lStatus < 0) {
5070 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5071 goto Exit;
5072 }
5073 } else {
5074 // if uuid is not specified, look for an available implementation
5075 // of the required type in effect factory
5076 if (EffectIsNullUuid(&pDesc->type)) {
5077 LOGW("createEffect() no effect type");
5078 lStatus = BAD_VALUE;
5079 goto Exit;
5080 }
5081 uint32_t numEffects = 0;
5082 effect_descriptor_t d;
5083 bool found = false;
5084
5085 lStatus = EffectQueryNumberEffects(&numEffects);
5086 if (lStatus < 0) {
5087 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5088 goto Exit;
5089 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005090 for (uint32_t i = 0; i < numEffects; i++) {
5091 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005092 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005093 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005094 continue;
5095 }
5096 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5097 // If matching type found save effect descriptor. If the session is
5098 // 0 and the effect is not auxiliary, continue enumeration in case
5099 // an auxiliary version of this effect type is available
5100 found = true;
5101 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005102 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005103 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5104 break;
5105 }
5106 }
5107 }
5108 if (!found) {
5109 lStatus = BAD_VALUE;
5110 LOGW("createEffect() effect not found");
5111 goto Exit;
5112 }
5113 // For same effect type, chose auxiliary version over insert version if
5114 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005115 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005116 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5117 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5118 }
5119 }
5120
5121 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005122 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005123 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5124 lStatus = INVALID_OPERATION;
5125 goto Exit;
5126 }
5127
Eric Laurentf82fccd2011-07-27 19:49:51 -07005128 // check recording permission for visualizer
5129 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5130 !recordingAllowed()) {
5131 lStatus = PERMISSION_DENIED;
5132 goto Exit;
5133 }
5134
Eric Laurent65b65452010-06-01 23:49:17 -07005135 // return effect descriptor
5136 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5137
5138 // If output is not specified try to find a matching audio session ID in one of the
5139 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005140 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5141 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005142 // Note: io is never 0 when creating an effect on an input
5143 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005144 // look for the thread where the specified audio session is present
5145 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5146 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005147 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005148 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005149 }
Eric Laurent65b65452010-06-01 23:49:17 -07005150 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005151 if (io == 0) {
5152 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5153 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5154 io = mRecordThreads.keyAt(i);
5155 break;
5156 }
5157 }
5158 }
Eric Laurent98c92592010-09-23 16:10:16 -07005159 // If no output thread contains the requested session ID, default to
5160 // first output. The effect chain will be moved to the correct output
5161 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005162 if (io == 0 && mPlaybackThreads.size()) {
5163 io = mPlaybackThreads.keyAt(0);
5164 }
5165 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5166 }
5167 ThreadBase *thread = checkRecordThread_l(io);
5168 if (thread == NULL) {
5169 thread = checkPlaybackThread_l(io);
5170 if (thread == NULL) {
5171 LOGE("createEffect() unknown output thread");
5172 lStatus = BAD_VALUE;
5173 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005174 }
Eric Laurent65b65452010-06-01 23:49:17 -07005175 }
Eric Laurent98c92592010-09-23 16:10:16 -07005176
Eric Laurent65b65452010-06-01 23:49:17 -07005177 wclient = mClients.valueFor(pid);
5178
5179 if (wclient != NULL) {
5180 client = wclient.promote();
5181 } else {
5182 client = new Client(this, pid);
5183 mClients.add(pid, client);
5184 }
5185
5186 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005187 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5188 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005189 if (handle != 0 && id != NULL) {
5190 *id = handle->id();
5191 }
5192 }
5193
5194Exit:
5195 if(status) {
5196 *status = lStatus;
5197 }
5198 return handle;
5199}
5200
Eric Laurentf82fccd2011-07-27 19:49:51 -07005201status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005202{
5203 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005204 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005205 Mutex::Autolock _l(mLock);
5206 if (srcOutput == dstOutput) {
5207 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5208 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005209 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005210 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5211 if (srcThread == NULL) {
5212 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5213 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005214 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005215 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5216 if (dstThread == NULL) {
5217 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5218 return BAD_VALUE;
5219 }
5220
5221 Mutex::Autolock _dl(dstThread->mLock);
5222 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005223 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005224
Eric Laurent53334cd2010-06-23 17:38:20 -07005225 return NO_ERROR;
5226}
5227
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005228// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005229status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005230 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005231 AudioFlinger::PlaybackThread *dstThread,
5232 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005233{
5234 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005235 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005236
Eric Laurentf82fccd2011-07-27 19:49:51 -07005237 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005238 if (chain == 0) {
5239 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005240 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005241 return INVALID_OPERATION;
5242 }
5243
Eric Laurent493941b2010-07-28 01:32:47 -07005244 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005245 // so that a new chain is created with correct parameters when first effect is added. This is
5246 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
5247 // removed.
5248 srcThread->removeEffectChain_l(chain);
5249
5250 // transfer all effects one by one so that new effect chain is created on new thread with
5251 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005252 int dstOutput = dstThread->id();
5253 sp<EffectChain> dstChain;
5254 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005255 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5256 while (effect != 0) {
5257 srcThread->removeEffect_l(effect);
5258 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07005259 // if the move request is not received from audio policy manager, the effect must be
5260 // re-registered with the new strategy and output
5261 if (dstChain == 0) {
5262 dstChain = effect->chain().promote();
5263 if (dstChain == 0) {
5264 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5265 srcThread->addEffect_l(effect);
5266 return NO_INIT;
5267 }
5268 strategy = dstChain->strategy();
5269 }
5270 if (reRegister) {
5271 AudioSystem::unregisterEffect(effect->id());
5272 AudioSystem::registerEffect(&effect->desc(),
5273 dstOutput,
5274 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005275 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005276 effect->id());
5277 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005278 effect = chain->getEffectFromId_l(0);
5279 }
5280
5281 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005282}
5283
Eric Laurent464d5b32011-06-17 21:29:58 -07005284
Eric Laurent65b65452010-06-01 23:49:17 -07005285// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005286sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005287 const sp<AudioFlinger::Client>& client,
5288 const sp<IEffectClient>& effectClient,
5289 int32_t priority,
5290 int sessionId,
5291 effect_descriptor_t *desc,
5292 int *enabled,
5293 status_t *status
5294 )
5295{
5296 sp<EffectModule> effect;
5297 sp<EffectHandle> handle;
5298 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005299 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005300 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005301 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005302 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005303
Eric Laurent464d5b32011-06-17 21:29:58 -07005304 lStatus = initCheck();
5305 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005306 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005307 goto Exit;
5308 }
5309
5310 // Do not allow effects with session ID 0 on direct output or duplicating threads
5311 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005312 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005313 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5314 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005315 lStatus = BAD_VALUE;
5316 goto Exit;
5317 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005318 // Only Pre processor effects are allowed on input threads and only on input threads
5319 if ((mType == RECORD &&
5320 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5321 (mType != RECORD &&
5322 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5323 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5324 desc->name, desc->flags, mType);
5325 lStatus = BAD_VALUE;
5326 goto Exit;
5327 }
Eric Laurent65b65452010-06-01 23:49:17 -07005328
5329 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5330
5331 { // scope for mLock
5332 Mutex::Autolock _l(mLock);
5333
5334 // check for existing effect chain with the requested audio session
5335 chain = getEffectChain_l(sessionId);
5336 if (chain == 0) {
5337 // create a new chain for this session
5338 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5339 chain = new EffectChain(this, sessionId);
5340 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005341 chain->setStrategy(getStrategyForSession_l(sessionId));
5342 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005343 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005344 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005345 }
5346
5347 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5348
5349 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005350 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005351 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005352 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005353 if (lStatus != NO_ERROR) {
5354 goto Exit;
5355 }
5356 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005357 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005358 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005359 lStatus = effect->status();
5360 if (lStatus != NO_ERROR) {
5361 goto Exit;
5362 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005363 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005364 if (lStatus != NO_ERROR) {
5365 goto Exit;
5366 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005367 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005368
5369 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005370 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005371 }
5372 // create effect handle and connect it to effect module
5373 handle = new EffectHandle(effect, client, effectClient, priority);
5374 lStatus = effect->addHandle(handle);
5375 if (enabled) {
5376 *enabled = (int)effect->isEnabled();
5377 }
5378 }
5379
5380Exit:
5381 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005382 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005383 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005384 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005385 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005386 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005387 AudioSystem::unregisterEffect(effect->id());
5388 }
5389 if (chainCreated) {
5390 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005391 }
Eric Laurent65b65452010-06-01 23:49:17 -07005392 handle.clear();
5393 }
5394
5395 if(status) {
5396 *status = lStatus;
5397 }
5398 return handle;
5399}
5400
Eric Laurent464d5b32011-06-17 21:29:58 -07005401sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5402{
5403 sp<EffectModule> effect;
5404
5405 sp<EffectChain> chain = getEffectChain_l(sessionId);
5406 if (chain != 0) {
5407 effect = chain->getEffectFromId_l(effectId);
5408 }
5409 return effect;
5410}
5411
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005412// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5413// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005414status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005415{
5416 // check for existing effect chain with the requested audio session
5417 int sessionId = effect->sessionId();
5418 sp<EffectChain> chain = getEffectChain_l(sessionId);
5419 bool chainCreated = false;
5420
5421 if (chain == 0) {
5422 // create a new chain for this session
5423 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5424 chain = new EffectChain(this, sessionId);
5425 addEffectChain_l(chain);
5426 chain->setStrategy(getStrategyForSession_l(sessionId));
5427 chainCreated = true;
5428 }
5429 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5430
5431 if (chain->getEffectFromId_l(effect->id()) != 0) {
5432 LOGW("addEffect_l() %p effect %s already present in chain %p",
5433 this, effect->desc().name, chain.get());
5434 return BAD_VALUE;
5435 }
5436
5437 status_t status = chain->addEffect_l(effect);
5438 if (status != NO_ERROR) {
5439 if (chainCreated) {
5440 removeEffectChain_l(chain);
5441 }
5442 return status;
5443 }
5444
5445 effect->setDevice(mDevice);
5446 effect->setMode(mAudioFlinger->getMode());
5447 return NO_ERROR;
5448}
5449
Eric Laurent464d5b32011-06-17 21:29:58 -07005450void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005451
5452 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005453 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005454 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5455 detachAuxEffect_l(effect->id());
5456 }
5457
5458 sp<EffectChain> chain = effect->chain().promote();
5459 if (chain != 0) {
5460 // remove effect chain if removing last effect
5461 if (chain->removeEffect_l(effect) == 0) {
5462 removeEffectChain_l(chain);
5463 }
5464 } else {
5465 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5466 }
5467}
5468
Eric Laurent464d5b32011-06-17 21:29:58 -07005469void AudioFlinger::ThreadBase::lockEffectChains_l(
5470 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5471{
5472 effectChains = mEffectChains;
5473 for (size_t i = 0; i < mEffectChains.size(); i++) {
5474 mEffectChains[i]->lock();
5475 }
5476}
5477
5478void AudioFlinger::ThreadBase::unlockEffectChains(
5479 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5480{
5481 for (size_t i = 0; i < effectChains.size(); i++) {
5482 effectChains[i]->unlock();
5483 }
5484}
5485
5486sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5487{
5488 Mutex::Autolock _l(mLock);
5489 return getEffectChain_l(sessionId);
5490}
5491
5492sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5493{
5494 sp<EffectChain> chain;
5495
5496 size_t size = mEffectChains.size();
5497 for (size_t i = 0; i < size; i++) {
5498 if (mEffectChains[i]->sessionId() == sessionId) {
5499 chain = mEffectChains[i];
5500 break;
5501 }
5502 }
5503 return chain;
5504}
5505
5506void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5507{
5508 Mutex::Autolock _l(mLock);
5509 size_t size = mEffectChains.size();
5510 for (size_t i = 0; i < size; i++) {
5511 mEffectChains[i]->setMode_l(mode);
5512 }
5513}
5514
5515void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005516 const wp<EffectHandle>& handle) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005517
Eric Laurent53334cd2010-06-23 17:38:20 -07005518 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005519 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005520 // delete the effect module if removing last handle on it
5521 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005522 removeEffect_l(effect);
5523 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07005524 }
5525}
5526
Eric Laurent65b65452010-06-01 23:49:17 -07005527status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5528{
5529 int session = chain->sessionId();
5530 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005531 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005532
5533 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005534 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005535 // Only one effect chain can be present in direct output thread and it uses
5536 // the mix buffer as input
5537 if (mType != DIRECT) {
5538 size_t numSamples = mFrameCount * mChannelCount;
5539 buffer = new int16_t[numSamples];
5540 memset(buffer, 0, numSamples * sizeof(int16_t));
5541 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5542 ownsBuffer = true;
5543 }
Eric Laurent65b65452010-06-01 23:49:17 -07005544
Eric Laurent53334cd2010-06-23 17:38:20 -07005545 // Attach all tracks with same session ID to this chain.
5546 for (size_t i = 0; i < mTracks.size(); ++i) {
5547 sp<Track> track = mTracks[i];
5548 if (session == track->sessionId()) {
5549 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5550 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005551 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005552 }
5553 }
5554
5555 // indicate all active tracks in the chain
5556 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5557 sp<Track> track = mActiveTracks[i].promote();
5558 if (track == 0) continue;
5559 if (session == track->sessionId()) {
5560 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005561 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005562 }
Eric Laurent65b65452010-06-01 23:49:17 -07005563 }
5564 }
5565
Eric Laurent53334cd2010-06-23 17:38:20 -07005566 chain->setInBuffer(buffer, ownsBuffer);
5567 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005568 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005569 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005570 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5571 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005572 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005573 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5574 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005575 // Effect chain for other sessions are inserted at beginning of effect
5576 // chains list to be processed before output mix effects. Relative order between other
5577 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005578 size_t size = mEffectChains.size();
5579 size_t i = 0;
5580 for (i = 0; i < size; i++) {
5581 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005582 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005583 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005584 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005585
5586 return NO_ERROR;
5587}
5588
5589size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5590{
5591 int session = chain->sessionId();
5592
5593 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5594
5595 for (size_t i = 0; i < mEffectChains.size(); i++) {
5596 if (chain == mEffectChains[i]) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005597 updateSuspendedSessionsOnRemoveEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005598 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005599 // detach all active tracks from the chain
5600 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5601 sp<Track> track = mActiveTracks[i].promote();
5602 if (track == 0) continue;
5603 if (session == track->sessionId()) {
5604 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5605 chain.get(), session);
5606 chain->decActiveTrackCnt();
5607 }
5608 }
5609
Eric Laurent65b65452010-06-01 23:49:17 -07005610 // detach all tracks with same session ID from this chain
5611 for (size_t i = 0; i < mTracks.size(); ++i) {
5612 sp<Track> track = mTracks[i];
5613 if (session == track->sessionId()) {
5614 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005615 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005616 }
5617 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005618 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005619 }
5620 }
5621 return mEffectChains.size();
5622}
5623
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005624status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5625 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005626{
5627 Mutex::Autolock _l(mLock);
5628 return attachAuxEffect_l(track, EffectId);
5629}
5630
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005631status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5632 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005633{
5634 status_t status = NO_ERROR;
5635
5636 if (EffectId == 0) {
5637 track->setAuxBuffer(0, NULL);
5638 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005639 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5640 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005641 if (effect != 0) {
5642 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5643 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5644 } else {
5645 status = INVALID_OPERATION;
5646 }
5647 } else {
5648 status = BAD_VALUE;
5649 }
5650 }
5651 return status;
5652}
5653
5654void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5655{
5656 for (size_t i = 0; i < mTracks.size(); ++i) {
5657 sp<Track> track = mTracks[i];
5658 if (track->auxEffectId() == effectId) {
5659 attachAuxEffect_l(track, 0);
5660 }
5661 }
5662}
5663
Eric Laurent464d5b32011-06-17 21:29:58 -07005664status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5665{
5666 // only one chain per input thread
5667 if (mEffectChains.size() != 0) {
5668 return INVALID_OPERATION;
5669 }
5670 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5671
5672 chain->setInBuffer(NULL);
5673 chain->setOutBuffer(NULL);
5674
Eric Laurentf82fccd2011-07-27 19:49:51 -07005675 checkSuspendOnAddEffectChain_l(chain);
5676
Eric Laurent464d5b32011-06-17 21:29:58 -07005677 mEffectChains.add(chain);
5678
5679 return NO_ERROR;
5680}
5681
5682size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5683{
5684 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5685 LOGW_IF(mEffectChains.size() != 1,
5686 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5687 chain.get(), mEffectChains.size(), this);
5688 if (mEffectChains.size() == 1) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005689 updateSuspendedSessionsOnRemoveEffectChain_l(chain);
Eric Laurent464d5b32011-06-17 21:29:58 -07005690 mEffectChains.removeAt(0);
5691 }
5692 return 0;
5693}
5694
Eric Laurent65b65452010-06-01 23:49:17 -07005695// ----------------------------------------------------------------------------
5696// EffectModule implementation
5697// ----------------------------------------------------------------------------
5698
5699#undef LOG_TAG
5700#define LOG_TAG "AudioFlinger::EffectModule"
5701
5702AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5703 const wp<AudioFlinger::EffectChain>& chain,
5704 effect_descriptor_t *desc,
5705 int id,
5706 int sessionId)
5707 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07005708 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07005709{
5710 LOGV("Constructor %p", this);
5711 int lStatus;
5712 sp<ThreadBase> thread = mThread.promote();
5713 if (thread == 0) {
5714 return;
5715 }
Eric Laurent65b65452010-06-01 23:49:17 -07005716
5717 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5718
5719 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07005720 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07005721
Eric Laurent65b65452010-06-01 23:49:17 -07005722 if (mStatus != NO_ERROR) {
5723 return;
5724 }
5725 lStatus = init();
5726 if (lStatus < 0) {
5727 mStatus = lStatus;
5728 goto Error;
5729 }
5730
5731 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5732 return;
5733Error:
5734 EffectRelease(mEffectInterface);
5735 mEffectInterface = NULL;
5736 LOGV("Constructor Error %d", mStatus);
5737}
5738
5739AudioFlinger::EffectModule::~EffectModule()
5740{
5741 LOGV("Destructor %p", this);
5742 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005743 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5744 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
5745 sp<ThreadBase> thread = mThread.promote();
5746 if (thread != 0) {
5747 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5748 }
5749 }
Eric Laurent65b65452010-06-01 23:49:17 -07005750 // release effect engine
5751 EffectRelease(mEffectInterface);
5752 }
5753}
5754
5755status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5756{
5757 status_t status;
5758
5759 Mutex::Autolock _l(mLock);
5760 // First handle in mHandles has highest priority and controls the effect module
5761 int priority = handle->priority();
5762 size_t size = mHandles.size();
5763 sp<EffectHandle> h;
5764 size_t i;
5765 for (i = 0; i < size; i++) {
5766 h = mHandles[i].promote();
5767 if (h == 0) continue;
5768 if (h->priority() <= priority) break;
5769 }
5770 // if inserted in first place, move effect control from previous owner to this handle
5771 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005772 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005773 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005774 enabled = h->enabled();
5775 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07005776 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07005777 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07005778 status = NO_ERROR;
5779 } else {
5780 status = ALREADY_EXISTS;
5781 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07005782 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07005783 mHandles.insertAt(handle, i);
5784 return status;
5785}
5786
5787size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5788{
5789 Mutex::Autolock _l(mLock);
5790 size_t size = mHandles.size();
5791 size_t i;
5792 for (i = 0; i < size; i++) {
5793 if (mHandles[i] == handle) break;
5794 }
5795 if (i == size) {
5796 return size;
5797 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07005798 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
5799
5800 bool enabled = false;
5801 EffectHandle *hdl = handle.unsafe_get();
5802 if (hdl) {
5803 LOGV("removeHandle() unsafe_get OK");
5804 enabled = hdl->enabled();
5805 }
Eric Laurent65b65452010-06-01 23:49:17 -07005806 mHandles.removeAt(i);
5807 size = mHandles.size();
5808 // if removed from first place, move effect control from this handle to next in line
5809 if (i == 0 && size != 0) {
5810 sp<EffectHandle> h = mHandles[0].promote();
5811 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005812 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07005813 }
5814 }
5815
Eric Laurent21b5c472011-07-26 20:54:46 -07005816 // Prevent calls to process() and other functions on effect interface from now on.
5817 // The effect engine will be released by the destructor when the last strong reference on
5818 // this object is released which can happen after next process is called.
5819 if (size == 0) {
5820 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005821 }
5822
Eric Laurent65b65452010-06-01 23:49:17 -07005823 return size;
5824}
5825
Eric Laurentf82fccd2011-07-27 19:49:51 -07005826sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
5827{
5828 Mutex::Autolock _l(mLock);
5829 sp<EffectHandle> handle;
5830 if (mHandles.size() != 0) {
5831 handle = mHandles[0].promote();
5832 }
5833 return handle;
5834}
5835
5836
5837
Eric Laurent65b65452010-06-01 23:49:17 -07005838void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5839{
Eric Laurentf82fccd2011-07-27 19:49:51 -07005840 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07005841 // keep a strong reference on this EffectModule to avoid calling the
5842 // destructor before we exit
5843 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005844 {
5845 sp<ThreadBase> thread = mThread.promote();
5846 if (thread != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005847 thread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005848 }
5849 }
5850}
5851
Eric Laurent7d850f22010-07-09 13:34:17 -07005852void AudioFlinger::EffectModule::updateState() {
5853 Mutex::Autolock _l(mLock);
5854
5855 switch (mState) {
5856 case RESTART:
5857 reset_l();
5858 // FALL THROUGH
5859
5860 case STARTING:
5861 // clear auxiliary effect input buffer for next accumulation
5862 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5863 memset(mConfig.inputCfg.buffer.raw,
5864 0,
5865 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5866 }
5867 start_l();
5868 mState = ACTIVE;
5869 break;
5870 case STOPPING:
5871 stop_l();
5872 mDisableWaitCnt = mMaxDisableWaitCnt;
5873 mState = STOPPED;
5874 break;
5875 case STOPPED:
5876 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5877 // turn off sequence.
5878 if (--mDisableWaitCnt == 0) {
5879 reset_l();
5880 mState = IDLE;
5881 }
5882 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07005883 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07005884 break;
5885 }
5886}
5887
Eric Laurent65b65452010-06-01 23:49:17 -07005888void AudioFlinger::EffectModule::process()
5889{
5890 Mutex::Autolock _l(mLock);
5891
Eric Laurent21b5c472011-07-26 20:54:46 -07005892 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07005893 mConfig.inputCfg.buffer.raw == NULL ||
5894 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005895 return;
5896 }
5897
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005898 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005899 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5900 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5901 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5902 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005903 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005904 }
5905
Eric Laurent65b65452010-06-01 23:49:17 -07005906 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005907 int ret = (*mEffectInterface)->process(mEffectInterface,
5908 &mConfig.inputCfg.buffer,
5909 &mConfig.outputCfg.buffer);
5910
5911 // force transition to IDLE state when engine is ready
5912 if (mState == STOPPED && ret == -ENODATA) {
5913 mDisableWaitCnt = 1;
5914 }
Eric Laurent65b65452010-06-01 23:49:17 -07005915
5916 // clear auxiliary effect input buffer for next accumulation
5917 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005918 memset(mConfig.inputCfg.buffer.raw, 0,
5919 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07005920 }
5921 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08005922 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5923 // If an insert effect is idle and input buffer is different from output buffer,
5924 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07005925 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07005926 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005927 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5928 int16_t *in = mConfig.inputCfg.buffer.s16;
5929 int16_t *out = mConfig.outputCfg.buffer.s16;
5930 for (size_t i = 0; i < frameCnt; i++) {
5931 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07005932 }
Eric Laurent65b65452010-06-01 23:49:17 -07005933 }
5934 }
5935}
5936
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005937void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005938{
5939 if (mEffectInterface == NULL) {
5940 return;
5941 }
5942 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5943}
5944
5945status_t AudioFlinger::EffectModule::configure()
5946{
5947 uint32_t channels;
5948 if (mEffectInterface == NULL) {
5949 return NO_INIT;
5950 }
5951
5952 sp<ThreadBase> thread = mThread.promote();
5953 if (thread == 0) {
5954 return DEAD_OBJECT;
5955 }
5956
5957 // TODO: handle configuration of effects replacing track process
5958 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07005959 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07005960 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07005961 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07005962 }
5963
5964 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07005965 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07005966 } else {
5967 mConfig.inputCfg.channels = channels;
5968 }
5969 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07005970 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5971 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07005972 mConfig.inputCfg.samplingRate = thread->sampleRate();
5973 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5974 mConfig.inputCfg.bufferProvider.cookie = NULL;
5975 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5976 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5977 mConfig.outputCfg.bufferProvider.cookie = NULL;
5978 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5979 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5980 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5981 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005982 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005983 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005984 // - in other sessions:
5985 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5986 // other effect: overwrites output buffer: input buffer == output buffer
5987 // Auxiliary effect:
5988 // accumulates in output buffer: input buffer != output buffer
5989 // Therefore: accumulate <=> input buffer != output buffer
5990 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5991 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5992 } else {
5993 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5994 }
5995 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5996 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5997 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5998 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5999
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006000 LOGV("configure() %p thread %p buffer %p framecount %d",
6001 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6002
Eric Laurent65b65452010-06-01 23:49:17 -07006003 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006004 uint32_t size = sizeof(int);
6005 status_t status = (*mEffectInterface)->command(mEffectInterface,
6006 EFFECT_CMD_CONFIGURE,
6007 sizeof(effect_config_t),
6008 &mConfig,
6009 &size,
6010 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006011 if (status == 0) {
6012 status = cmdStatus;
6013 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006014
6015 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6016 (1000 * mConfig.outputCfg.buffer.frameCount);
6017
Eric Laurent65b65452010-06-01 23:49:17 -07006018 return status;
6019}
6020
6021status_t AudioFlinger::EffectModule::init()
6022{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006023 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006024 if (mEffectInterface == NULL) {
6025 return NO_INIT;
6026 }
6027 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006028 uint32_t size = sizeof(status_t);
6029 status_t status = (*mEffectInterface)->command(mEffectInterface,
6030 EFFECT_CMD_INIT,
6031 0,
6032 NULL,
6033 &size,
6034 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006035 if (status == 0) {
6036 status = cmdStatus;
6037 }
6038 return status;
6039}
6040
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006041status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006042{
6043 if (mEffectInterface == NULL) {
6044 return NO_INIT;
6045 }
6046 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006047 uint32_t size = sizeof(status_t);
6048 status_t status = (*mEffectInterface)->command(mEffectInterface,
6049 EFFECT_CMD_ENABLE,
6050 0,
6051 NULL,
6052 &size,
6053 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006054 if (status == 0) {
6055 status = cmdStatus;
6056 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006057 if (status == 0 &&
6058 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6059 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6060 sp<ThreadBase> thread = mThread.promote();
6061 if (thread != 0) {
6062 thread->stream()->add_audio_effect(thread->stream(), mEffectInterface);
6063 }
6064 }
Eric Laurent65b65452010-06-01 23:49:17 -07006065 return status;
6066}
6067
Eric Laurent21b5c472011-07-26 20:54:46 -07006068status_t AudioFlinger::EffectModule::stop()
6069{
6070 Mutex::Autolock _l(mLock);
6071 return stop_l();
6072}
6073
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006074status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006075{
6076 if (mEffectInterface == NULL) {
6077 return NO_INIT;
6078 }
6079 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006080 uint32_t size = sizeof(status_t);
6081 status_t status = (*mEffectInterface)->command(mEffectInterface,
6082 EFFECT_CMD_DISABLE,
6083 0,
6084 NULL,
6085 &size,
6086 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006087 if (status == 0) {
6088 status = cmdStatus;
6089 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006090 if (status == 0 &&
6091 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6092 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6093 sp<ThreadBase> thread = mThread.promote();
6094 if (thread != 0) {
6095 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
6096 }
6097 }
Eric Laurent65b65452010-06-01 23:49:17 -07006098 return status;
6099}
6100
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006101status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6102 uint32_t cmdSize,
6103 void *pCmdData,
6104 uint32_t *replySize,
6105 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006106{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006107 Mutex::Autolock _l(mLock);
6108// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006109
Eric Laurent21b5c472011-07-26 20:54:46 -07006110 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006111 return NO_INIT;
6112 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006113 status_t status = (*mEffectInterface)->command(mEffectInterface,
6114 cmdCode,
6115 cmdSize,
6116 pCmdData,
6117 replySize,
6118 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006119 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006120 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006121 for (size_t i = 1; i < mHandles.size(); i++) {
6122 sp<EffectHandle> h = mHandles[i].promote();
6123 if (h != 0) {
6124 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6125 }
6126 }
6127 }
6128 return status;
6129}
6130
6131status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6132{
6133 Mutex::Autolock _l(mLock);
6134 LOGV("setEnabled %p enabled %d", this, enabled);
6135
6136 if (enabled != isEnabled()) {
6137 switch (mState) {
6138 // going from disabled to enabled
6139 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006140 mState = STARTING;
6141 break;
6142 case STOPPED:
6143 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006144 break;
6145 case STOPPING:
6146 mState = ACTIVE;
6147 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006148
6149 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006150 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006151 mState = STOPPED;
6152 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006153 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006154 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006155 break;
6156 case ACTIVE:
6157 mState = STOPPING;
6158 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006159 case DESTROYED:
6160 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006161 }
6162 for (size_t i = 1; i < mHandles.size(); i++) {
6163 sp<EffectHandle> h = mHandles[i].promote();
6164 if (h != 0) {
6165 h->setEnabled(enabled);
6166 }
6167 }
6168 }
6169 return NO_ERROR;
6170}
6171
6172bool AudioFlinger::EffectModule::isEnabled()
6173{
6174 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006175 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006176 case STARTING:
6177 case ACTIVE:
6178 return true;
6179 case IDLE:
6180 case STOPPING:
6181 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006182 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006183 default:
6184 return false;
6185 }
6186}
6187
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006188bool AudioFlinger::EffectModule::isProcessEnabled()
6189{
6190 switch (mState) {
6191 case RESTART:
6192 case ACTIVE:
6193 case STOPPING:
6194 case STOPPED:
6195 return true;
6196 case IDLE:
6197 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006198 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006199 default:
6200 return false;
6201 }
6202}
6203
Eric Laurent65b65452010-06-01 23:49:17 -07006204status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6205{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006206 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006207 status_t status = NO_ERROR;
6208
6209 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6210 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006211 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006212 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6213 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006214 status_t cmdStatus;
6215 uint32_t volume[2];
6216 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006217 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006218 volume[0] = *left;
6219 volume[1] = *right;
6220 if (controller) {
6221 pVolume = volume;
6222 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006223 status = (*mEffectInterface)->command(mEffectInterface,
6224 EFFECT_CMD_SET_VOLUME,
6225 size,
6226 volume,
6227 &size,
6228 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006229 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6230 *left = volume[0];
6231 *right = volume[1];
6232 }
6233 }
6234 return status;
6235}
6236
6237status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6238{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006239 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006240 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006241 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6242 // audio pre processing modules on RecordThread can receive both output and
6243 // input device indication in the same call
6244 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6245 if (dev) {
6246 status_t cmdStatus;
6247 uint32_t size = sizeof(status_t);
6248
6249 status = (*mEffectInterface)->command(mEffectInterface,
6250 EFFECT_CMD_SET_DEVICE,
6251 sizeof(uint32_t),
6252 &dev,
6253 &size,
6254 &cmdStatus);
6255 if (status == NO_ERROR) {
6256 status = cmdStatus;
6257 }
6258 }
6259 dev = device & AUDIO_DEVICE_IN_ALL;
6260 if (dev) {
6261 status_t cmdStatus;
6262 uint32_t size = sizeof(status_t);
6263
6264 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6265 EFFECT_CMD_SET_INPUT_DEVICE,
6266 sizeof(uint32_t),
6267 &dev,
6268 &size,
6269 &cmdStatus);
6270 if (status2 == NO_ERROR) {
6271 status2 = cmdStatus;
6272 }
6273 if (status == NO_ERROR) {
6274 status = status2;
6275 }
Eric Laurent65b65452010-06-01 23:49:17 -07006276 }
6277 }
6278 return status;
6279}
6280
Eric Laurent53334cd2010-06-23 17:38:20 -07006281status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6282{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006283 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006284 status_t status = NO_ERROR;
6285 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006286 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006287 uint32_t size = sizeof(status_t);
6288 status = (*mEffectInterface)->command(mEffectInterface,
6289 EFFECT_CMD_SET_AUDIO_MODE,
6290 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006291 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006292 &size,
6293 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006294 if (status == NO_ERROR) {
6295 status = cmdStatus;
6296 }
6297 }
6298 return status;
6299}
6300
Eric Laurentf82fccd2011-07-27 19:49:51 -07006301void AudioFlinger::EffectModule::setSuspended(bool suspended)
6302{
6303 Mutex::Autolock _l(mLock);
6304 mSuspended = suspended;
6305}
6306bool AudioFlinger::EffectModule::suspended()
6307{
6308 Mutex::Autolock _l(mLock);
6309 return mSuspended;
6310}
6311
Eric Laurent65b65452010-06-01 23:49:17 -07006312status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6313{
6314 const size_t SIZE = 256;
6315 char buffer[SIZE];
6316 String8 result;
6317
6318 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6319 result.append(buffer);
6320
6321 bool locked = tryLock(mLock);
6322 // failed to lock - AudioFlinger is probably deadlocked
6323 if (!locked) {
6324 result.append("\t\tCould not lock Fx mutex:\n");
6325 }
6326
6327 result.append("\t\tSession Status State Engine:\n");
6328 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6329 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6330 result.append(buffer);
6331
6332 result.append("\t\tDescriptor:\n");
6333 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6334 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6335 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6336 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6337 result.append(buffer);
6338 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6339 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6340 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6341 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6342 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006343 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006344 mDescriptor.apiVersion,
6345 mDescriptor.flags);
6346 result.append(buffer);
6347 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6348 mDescriptor.name);
6349 result.append(buffer);
6350 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6351 mDescriptor.implementor);
6352 result.append(buffer);
6353
6354 result.append("\t\t- Input configuration:\n");
6355 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6356 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6357 (uint32_t)mConfig.inputCfg.buffer.raw,
6358 mConfig.inputCfg.buffer.frameCount,
6359 mConfig.inputCfg.samplingRate,
6360 mConfig.inputCfg.channels,
6361 mConfig.inputCfg.format);
6362 result.append(buffer);
6363
6364 result.append("\t\t- Output configuration:\n");
6365 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6366 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6367 (uint32_t)mConfig.outputCfg.buffer.raw,
6368 mConfig.outputCfg.buffer.frameCount,
6369 mConfig.outputCfg.samplingRate,
6370 mConfig.outputCfg.channels,
6371 mConfig.outputCfg.format);
6372 result.append(buffer);
6373
6374 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6375 result.append(buffer);
6376 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6377 for (size_t i = 0; i < mHandles.size(); ++i) {
6378 sp<EffectHandle> handle = mHandles[i].promote();
6379 if (handle != 0) {
6380 handle->dump(buffer, SIZE);
6381 result.append(buffer);
6382 }
6383 }
6384
6385 result.append("\n");
6386
6387 write(fd, result.string(), result.length());
6388
6389 if (locked) {
6390 mLock.unlock();
6391 }
6392
6393 return NO_ERROR;
6394}
6395
6396// ----------------------------------------------------------------------------
6397// EffectHandle implementation
6398// ----------------------------------------------------------------------------
6399
6400#undef LOG_TAG
6401#define LOG_TAG "AudioFlinger::EffectHandle"
6402
6403AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6404 const sp<AudioFlinger::Client>& client,
6405 const sp<IEffectClient>& effectClient,
6406 int32_t priority)
6407 : BnEffect(),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006408 mEffect(effect), mEffectClient(effectClient), mClient(client),
6409 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006410{
6411 LOGV("constructor %p", this);
6412
6413 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6414 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6415 if (mCblkMemory != 0) {
6416 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6417
6418 if (mCblk) {
6419 new(mCblk) effect_param_cblk_t();
6420 mBuffer = (uint8_t *)mCblk + bufOffset;
6421 }
6422 } else {
6423 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6424 return;
6425 }
6426}
6427
6428AudioFlinger::EffectHandle::~EffectHandle()
6429{
6430 LOGV("Destructor %p", this);
6431 disconnect();
Eric Laurentf82fccd2011-07-27 19:49:51 -07006432 LOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006433}
6434
6435status_t AudioFlinger::EffectHandle::enable()
6436{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006437 LOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006438 if (!mHasControl) return INVALID_OPERATION;
6439 if (mEffect == 0) return DEAD_OBJECT;
6440
Eric Laurentf82fccd2011-07-27 19:49:51 -07006441 mEnabled = true;
6442
6443 sp<ThreadBase> thread = mEffect->thread().promote();
6444 if (thread != 0) {
6445 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6446 }
6447
6448 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6449 if (mEffect->suspended()) {
6450 return NO_ERROR;
6451 }
6452
Eric Laurent65b65452010-06-01 23:49:17 -07006453 return mEffect->setEnabled(true);
6454}
6455
6456status_t AudioFlinger::EffectHandle::disable()
6457{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006458 LOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006459 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006460 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006461
Eric Laurentf82fccd2011-07-27 19:49:51 -07006462 mEnabled = false;
6463
6464 if (mEffect->suspended()) {
6465 return NO_ERROR;
6466 }
6467
6468 status_t status = mEffect->setEnabled(false);
6469
6470 sp<ThreadBase> thread = mEffect->thread().promote();
6471 if (thread != 0) {
6472 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6473 }
6474
6475 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006476}
6477
6478void AudioFlinger::EffectHandle::disconnect()
6479{
Eric Laurentf82fccd2011-07-27 19:49:51 -07006480 LOGV("disconnect %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006481 if (mEffect == 0) {
6482 return;
6483 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006484
Eric Laurent65b65452010-06-01 23:49:17 -07006485 mEffect->disconnect(this);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006486
6487 sp<ThreadBase> thread = mEffect->thread().promote();
6488 if (thread != 0) {
6489 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6490 }
6491
Eric Laurent65b65452010-06-01 23:49:17 -07006492 // release sp on module => module destructor can be called now
6493 mEffect.clear();
6494 if (mCblk) {
6495 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6496 }
6497 mCblkMemory.clear(); // and free the shared memory
6498 if (mClient != 0) {
6499 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6500 mClient.clear();
6501 }
6502}
6503
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006504status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6505 uint32_t cmdSize,
6506 void *pCmdData,
6507 uint32_t *replySize,
6508 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006509{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006510// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6511// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006512
6513 // only get parameter command is permitted for applications not controlling the effect
6514 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6515 return INVALID_OPERATION;
6516 }
6517 if (mEffect == 0) return DEAD_OBJECT;
6518
6519 // handle commands that are not forwarded transparently to effect engine
6520 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6521 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6522 // no risk to block the whole media server process or mixer threads is we are stuck here
6523 Mutex::Autolock _l(mCblk->lock);
6524 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6525 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6526 mCblk->serverIndex = 0;
6527 mCblk->clientIndex = 0;
6528 return BAD_VALUE;
6529 }
6530 status_t status = NO_ERROR;
6531 while (mCblk->serverIndex < mCblk->clientIndex) {
6532 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006533 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006534 int *p = (int *)(mBuffer + mCblk->serverIndex);
6535 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006536 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6537 LOGW("command(): invalid parameter block size");
6538 break;
6539 }
Eric Laurent65b65452010-06-01 23:49:17 -07006540 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006541 if (param->psize == 0 || param->vsize == 0) {
6542 LOGW("command(): null parameter or value size");
6543 mCblk->serverIndex += size;
6544 continue;
6545 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006546 uint32_t psize = sizeof(effect_param_t) +
6547 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6548 param->vsize;
6549 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6550 psize,
6551 p,
6552 &rsize,
6553 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006554 // stop at first error encountered
6555 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006556 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006557 *(int *)pReplyData = reply;
6558 break;
6559 } else if (reply != NO_ERROR) {
6560 *(int *)pReplyData = reply;
6561 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006562 }
6563 mCblk->serverIndex += size;
6564 }
6565 mCblk->serverIndex = 0;
6566 mCblk->clientIndex = 0;
6567 return status;
6568 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006569 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006570 return enable();
6571 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006572 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006573 return disable();
6574 }
6575
6576 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6577}
6578
6579sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6580 return mCblkMemory;
6581}
6582
Eric Laurentf82fccd2011-07-27 19:49:51 -07006583void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07006584{
6585 LOGV("setControl %p control %d", this, hasControl);
6586
6587 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006588 mEnabled = enabled;
6589
Eric Laurent65b65452010-06-01 23:49:17 -07006590 if (signal && mEffectClient != 0) {
6591 mEffectClient->controlStatusChanged(hasControl);
6592 }
6593}
6594
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006595void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6596 uint32_t cmdSize,
6597 void *pCmdData,
6598 uint32_t replySize,
6599 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006600{
6601 if (mEffectClient != 0) {
6602 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6603 }
6604}
6605
6606
6607
6608void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6609{
6610 if (mEffectClient != 0) {
6611 mEffectClient->enableStatusChanged(enabled);
6612 }
6613}
6614
6615status_t AudioFlinger::EffectHandle::onTransact(
6616 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6617{
6618 return BnEffect::onTransact(code, data, reply, flags);
6619}
6620
6621
6622void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6623{
6624 bool locked = tryLock(mCblk->lock);
6625
6626 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6627 (mClient == NULL) ? getpid() : mClient->pid(),
6628 mPriority,
6629 mHasControl,
6630 !locked,
6631 mCblk->clientIndex,
6632 mCblk->serverIndex
6633 );
6634
6635 if (locked) {
6636 mCblk->lock.unlock();
6637 }
6638}
6639
6640#undef LOG_TAG
6641#define LOG_TAG "AudioFlinger::EffectChain"
6642
6643AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6644 int sessionId)
Eric Laurent90681d62011-05-09 12:09:06 -07006645 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6646 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6647 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006648{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006649 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006650}
6651
6652AudioFlinger::EffectChain::~EffectChain()
6653{
6654 if (mOwnInBuffer) {
6655 delete mInBuffer;
6656 }
6657
6658}
6659
Eric Laurentf82fccd2011-07-27 19:49:51 -07006660// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07006661sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006662{
6663 sp<EffectModule> effect;
6664 size_t size = mEffects.size();
6665
6666 for (size_t i = 0; i < size; i++) {
6667 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6668 effect = mEffects[i];
6669 break;
6670 }
6671 }
6672 return effect;
6673}
6674
Eric Laurentf82fccd2011-07-27 19:49:51 -07006675// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07006676sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006677{
6678 sp<EffectModule> effect;
6679 size_t size = mEffects.size();
6680
6681 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006682 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6683 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006684 effect = mEffects[i];
6685 break;
6686 }
6687 }
6688 return effect;
6689}
6690
Eric Laurentf82fccd2011-07-27 19:49:51 -07006691// getEffectFromType_l() must be called with ThreadBase::mLock held
6692sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
6693 const effect_uuid_t *type)
6694{
6695 sp<EffectModule> effect;
6696 size_t size = mEffects.size();
6697
6698 for (size_t i = 0; i < size; i++) {
6699 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
6700 effect = mEffects[i];
6701 break;
6702 }
6703 }
6704 return effect;
6705}
6706
Eric Laurent65b65452010-06-01 23:49:17 -07006707// Must be called with EffectChain::mLock locked
6708void AudioFlinger::EffectChain::process_l()
6709{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006710 sp<ThreadBase> thread = mThread.promote();
6711 if (thread == 0) {
6712 LOGW("process_l(): cannot promote mixer thread");
6713 return;
6714 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006715 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6716 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006717 bool tracksOnSession = false;
6718 if (!isGlobalSession) {
Eric Laurent90681d62011-05-09 12:09:06 -07006719 tracksOnSession = (trackCnt() != 0);
6720 }
6721
6722 // if no track is active, input buffer must be cleared here as the mixer process
6723 // will not do it
6724 if (tracksOnSession &&
6725 activeTrackCnt() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006726 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurent90681d62011-05-09 12:09:06 -07006727 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006728 }
6729
Eric Laurent65b65452010-06-01 23:49:17 -07006730 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006731 // do not process effect if no track is present in same audio session
6732 if (isGlobalSession || tracksOnSession) {
6733 for (size_t i = 0; i < size; i++) {
6734 mEffects[i]->process();
6735 }
Eric Laurent65b65452010-06-01 23:49:17 -07006736 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006737 for (size_t i = 0; i < size; i++) {
6738 mEffects[i]->updateState();
6739 }
Eric Laurent65b65452010-06-01 23:49:17 -07006740}
6741
Eric Laurent76c40f72010-07-15 12:50:15 -07006742// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006743status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006744{
6745 effect_descriptor_t desc = effect->desc();
6746 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6747
6748 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006749 effect->setChain(this);
6750 sp<ThreadBase> thread = mThread.promote();
6751 if (thread == 0) {
6752 return NO_INIT;
6753 }
6754 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006755
6756 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6757 // Auxiliary effects are inserted at the beginning of mEffects vector as
6758 // they are processed first and accumulated in chain input buffer
6759 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006760
Eric Laurent65b65452010-06-01 23:49:17 -07006761 // the input buffer for auxiliary effect contains mono samples in
6762 // 32 bit format. This is to avoid saturation in AudoMixer
6763 // accumulation stage. Saturation is done in EffectModule::process() before
6764 // calling the process in effect engine
6765 size_t numSamples = thread->frameCount();
6766 int32_t *buffer = new int32_t[numSamples];
6767 memset(buffer, 0, numSamples * sizeof(int32_t));
6768 effect->setInBuffer((int16_t *)buffer);
6769 // auxiliary effects output samples to chain input buffer for further processing
6770 // by insert effects
6771 effect->setOutBuffer(mInBuffer);
6772 } else {
6773 // Insert effects are inserted at the end of mEffects vector as they are processed
6774 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006775 // Insert effect order as a function of indicated preference:
6776 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6777 // another effect is present
6778 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6779 // last effect claiming first position
6780 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6781 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006782 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006783 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6784 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006785
6786 int size = (int)mEffects.size();
6787 int idx_insert = size;
6788 int idx_insert_first = -1;
6789 int idx_insert_last = -1;
6790
6791 for (int i = 0; i < size; i++) {
6792 effect_descriptor_t d = mEffects[i]->desc();
6793 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6794 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6795 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6796 // check invalid effect chaining combinations
6797 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006798 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006799 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006800 return INVALID_OPERATION;
6801 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006802 // remember position of first insert effect and by default
6803 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006804 if (idx_insert == size) {
6805 idx_insert = i;
6806 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006807 // remember position of last insert effect claiming
6808 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006809 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6810 idx_insert_first = i;
6811 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006812 // remember position of first insert effect claiming
6813 // last position
6814 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6815 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006816 idx_insert_last = i;
6817 }
6818 }
6819 }
6820
Eric Laurent53334cd2010-06-23 17:38:20 -07006821 // modify idx_insert from first position if needed
6822 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6823 if (idx_insert_last != -1) {
6824 idx_insert = idx_insert_last;
6825 } else {
6826 idx_insert = size;
6827 }
6828 } else {
6829 if (idx_insert_first != -1) {
6830 idx_insert = idx_insert_first + 1;
6831 }
Eric Laurent65b65452010-06-01 23:49:17 -07006832 }
6833
6834 // always read samples from chain input buffer
6835 effect->setInBuffer(mInBuffer);
6836
6837 // if last effect in the chain, output samples to chain
6838 // output buffer, otherwise to chain input buffer
6839 if (idx_insert == size) {
6840 if (idx_insert != 0) {
6841 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6842 mEffects[idx_insert-1]->configure();
6843 }
6844 effect->setOutBuffer(mOutBuffer);
6845 } else {
6846 effect->setOutBuffer(mInBuffer);
6847 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006848 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006849
Eric Laurent76c40f72010-07-15 12:50:15 -07006850 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006851 }
6852 effect->configure();
6853 return NO_ERROR;
6854}
6855
Eric Laurent76c40f72010-07-15 12:50:15 -07006856// removeEffect_l() must be called with PlaybackThread::mLock held
6857size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006858{
6859 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006860 int size = (int)mEffects.size();
6861 int i;
6862 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6863
6864 for (i = 0; i < size; i++) {
6865 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006866 // calling stop here will remove pre-processing effect from the audio HAL.
6867 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
6868 // the middle of a read from audio HAL
6869 mEffects[i]->stop();
Eric Laurent65b65452010-06-01 23:49:17 -07006870 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6871 delete[] effect->inBuffer();
6872 } else {
6873 if (i == size - 1 && i != 0) {
6874 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6875 mEffects[i - 1]->configure();
6876 }
6877 }
6878 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006879 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006880 break;
6881 }
6882 }
Eric Laurent65b65452010-06-01 23:49:17 -07006883
6884 return mEffects.size();
6885}
6886
Eric Laurent76c40f72010-07-15 12:50:15 -07006887// setDevice_l() must be called with PlaybackThread::mLock held
6888void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006889{
6890 size_t size = mEffects.size();
6891 for (size_t i = 0; i < size; i++) {
6892 mEffects[i]->setDevice(device);
6893 }
6894}
6895
Eric Laurent76c40f72010-07-15 12:50:15 -07006896// setMode_l() must be called with PlaybackThread::mLock held
6897void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006898{
6899 size_t size = mEffects.size();
6900 for (size_t i = 0; i < size; i++) {
6901 mEffects[i]->setMode(mode);
6902 }
6903}
6904
Eric Laurent76c40f72010-07-15 12:50:15 -07006905// setVolume_l() must be called with PlaybackThread::mLock held
6906bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006907{
6908 uint32_t newLeft = *left;
6909 uint32_t newRight = *right;
6910 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006911 int ctrlIdx = -1;
6912 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006913
Eric Laurent76c40f72010-07-15 12:50:15 -07006914 // first update volume controller
6915 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006916 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006917 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6918 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006919 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006920 break;
6921 }
6922 }
6923
6924 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006925 if (hasControl) {
6926 *left = mNewLeftVolume;
6927 *right = mNewRightVolume;
6928 }
6929 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006930 }
6931
6932 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006933 mLeftVolume = newLeft;
6934 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006935
6936 // second get volume update from volume controller
6937 if (ctrlIdx >= 0) {
6938 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006939 mNewLeftVolume = newLeft;
6940 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006941 }
6942 // then indicate volume to all other effects in chain.
6943 // Pass altered volume to effects before volume controller
6944 // and requested volume to effects after controller
6945 uint32_t lVol = newLeft;
6946 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006947
Eric Laurent65b65452010-06-01 23:49:17 -07006948 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006949 if ((int)i == ctrlIdx) continue;
6950 // this also works for ctrlIdx == -1 when there is no volume controller
6951 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006952 lVol = *left;
6953 rVol = *right;
6954 }
6955 mEffects[i]->setVolume(&lVol, &rVol, false);
6956 }
6957 *left = newLeft;
6958 *right = newRight;
6959
6960 return hasControl;
6961}
6962
Eric Laurent65b65452010-06-01 23:49:17 -07006963status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6964{
6965 const size_t SIZE = 256;
6966 char buffer[SIZE];
6967 String8 result;
6968
6969 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6970 result.append(buffer);
6971
6972 bool locked = tryLock(mLock);
6973 // failed to lock - AudioFlinger is probably deadlocked
6974 if (!locked) {
6975 result.append("\tCould not lock mutex:\n");
6976 }
6977
Eric Laurent76c40f72010-07-15 12:50:15 -07006978 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6979 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006980 mEffects.size(),
6981 (uint32_t)mInBuffer,
6982 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006983 mActiveTrackCnt);
6984 result.append(buffer);
6985 write(fd, result.string(), result.size());
6986
6987 for (size_t i = 0; i < mEffects.size(); ++i) {
6988 sp<EffectModule> effect = mEffects[i];
6989 if (effect != 0) {
6990 effect->dump(fd, args);
6991 }
6992 }
6993
6994 if (locked) {
6995 mLock.unlock();
6996 }
6997
6998 return NO_ERROR;
6999}
7000
Eric Laurentf82fccd2011-07-27 19:49:51 -07007001// must be called with ThreadBase::mLock held
7002void AudioFlinger::EffectChain::setEffectSuspended_l(
7003 const effect_uuid_t *type, bool suspend)
7004{
7005 sp<SuspendedEffectDesc> desc;
7006 // use effect type UUID timelow as key as there is no real risk of identical
7007 // timeLow fields among effect type UUIDs.
7008 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7009 if (suspend) {
7010 if (index >= 0) {
7011 desc = mSuspendedEffects.valueAt(index);
7012 } else {
7013 desc = new SuspendedEffectDesc();
7014 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7015 mSuspendedEffects.add(type->timeLow, desc);
7016 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7017 }
7018 if (desc->mRefCount++ == 0) {
7019 sp<EffectModule> effect = getEffectIfEnabled(type);
7020 if (effect != 0) {
7021 desc->mEffect = effect;
7022 effect->setSuspended(true);
7023 effect->setEnabled(false);
7024 }
7025 }
7026 } else {
7027 if (index < 0) {
7028 return;
7029 }
7030 desc = mSuspendedEffects.valueAt(index);
7031 if (desc->mRefCount <= 0) {
7032 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7033 desc->mRefCount = 1;
7034 }
7035 if (--desc->mRefCount == 0) {
7036 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7037 if (desc->mEffect != 0) {
7038 sp<EffectModule> effect = desc->mEffect.promote();
7039 if (effect != 0) {
7040 effect->setSuspended(false);
7041 sp<EffectHandle> handle = effect->controlHandle();
7042 if (handle != 0) {
7043 effect->setEnabled(handle->enabled());
7044 }
7045 }
7046 desc->mEffect.clear();
7047 }
7048 mSuspendedEffects.removeItemsAt(index);
7049 }
7050 }
7051}
7052
7053// must be called with ThreadBase::mLock held
7054void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7055{
7056 sp<SuspendedEffectDesc> desc;
7057
7058 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7059 if (suspend) {
7060 if (index >= 0) {
7061 desc = mSuspendedEffects.valueAt(index);
7062 } else {
7063 desc = new SuspendedEffectDesc();
7064 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7065 LOGV("setEffectSuspendedAll_l() add entry for 0");
7066 }
7067 if (desc->mRefCount++ == 0) {
7068 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7069 for (size_t i = 0; i < effects.size(); i++) {
7070 setEffectSuspended_l(&effects[i]->desc().type, true);
7071 }
7072 }
7073 } else {
7074 if (index < 0) {
7075 return;
7076 }
7077 desc = mSuspendedEffects.valueAt(index);
7078 if (desc->mRefCount <= 0) {
7079 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7080 desc->mRefCount = 1;
7081 }
7082 if (--desc->mRefCount == 0) {
7083 Vector<const effect_uuid_t *> types;
7084 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7085 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7086 continue;
7087 }
7088 types.add(&mSuspendedEffects.valueAt(i)->mType);
7089 }
7090 for (size_t i = 0; i < types.size(); i++) {
7091 setEffectSuspended_l(types[i], false);
7092 }
7093 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7094 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7095 }
7096 }
7097}
7098
7099Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7100{
7101 Vector< sp<EffectModule> > effects;
7102 for (size_t i = 0; i < mEffects.size(); i++) {
7103 effect_descriptor_t desc = mEffects[i]->desc();
7104 // auxiliary effects and vizualizer are never suspended on output mix
7105 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) && (
7106 ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7107 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0))) {
7108 continue;
7109 }
7110 effects.add(mEffects[i]);
7111 }
7112 return effects;
7113}
7114
7115sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7116 const effect_uuid_t *type)
7117{
7118 sp<EffectModule> effect;
7119 effect = getEffectFromType_l(type);
7120 if (effect != 0 && !effect->isEnabled()) {
7121 effect.clear();
7122 }
7123 return effect;
7124}
7125
7126void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7127 bool enabled)
7128{
7129 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7130 if (enabled) {
7131 if (index < 0) {
7132 // if the effect is not suspend check if all effects are suspended
7133 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7134 if (index < 0) {
7135 return;
7136 }
7137 setEffectSuspended_l(&effect->desc().type, enabled);
7138 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7139 }
7140 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7141 effect->desc().type.timeLow);
7142 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7143 // if effect is requested to suspended but was not yet enabled, supend it now.
7144 if (desc->mEffect == 0) {
7145 desc->mEffect = effect;
7146 effect->setEnabled(false);
7147 effect->setSuspended(true);
7148 }
7149 } else {
7150 if (index < 0) {
7151 return;
7152 }
7153 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7154 effect->desc().type.timeLow);
7155 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7156 desc->mEffect.clear();
7157 effect->setSuspended(false);
7158 }
7159}
7160
Eric Laurent65b65452010-06-01 23:49:17 -07007161#undef LOG_TAG
7162#define LOG_TAG "AudioFlinger"
7163
Eric Laurenta553c252009-07-17 12:17:14 -07007164// ----------------------------------------------------------------------------
7165
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007166status_t AudioFlinger::onTransact(
7167 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7168{
7169 return BnAudioFlinger::onTransact(code, data, reply, flags);
7170}
7171
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007172}; // namespace android