blob: ed21fa8dd07061facf11aee36067e3e641655a77 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -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"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
38
39#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
53#include <media/EffectVisualizerApi.h>
54
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070055#include <cpustats/ThreadCpuUsage.h>
56// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
57
Mathias Agopian65ab4712010-07-14 17:59:35 -070058// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Eric Laurentde070132010-07-13 04:45:46 -070060
Mathias Agopian65ab4712010-07-14 17:59:35 -070061namespace android {
62
63static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
64static const char* kHardwareLockedString = "Hardware lock is taken\n";
65
66//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
67static const float MAX_GAIN = 4096.0f;
68static const float MAX_GAIN_INT = 0x1000;
69
70// retry counts for buffer fill timeout
71// 50 * ~20msecs = 1 second
72static const int8_t kMaxTrackRetries = 50;
73static const int8_t kMaxTrackStartupRetries = 50;
74// allow less retry attempts on direct output thread.
75// direct outputs can be a scarce resource in audio hardware and should
76// be released as quickly as possible.
77static const int8_t kMaxTrackRetriesDirect = 2;
78
79static const int kDumpLockRetries = 50;
80static const int kDumpLockSleep = 20000;
81
82static const nsecs_t kWarningThrottle = seconds(5);
83
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085// ----------------------------------------------------------------------------
86
87static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070088 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
89 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
90 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
91 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092}
93
94static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070095 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
96 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
97 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
98 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070099}
100
Gloria Wang9ee159b2011-02-24 14:51:45 -0800101// To collect the amplifier usage
102static void addBatteryData(uint32_t params) {
103 sp<IBinder> binder =
104 defaultServiceManager()->getService(String16("media.player"));
105 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
106 if (service.get() == NULL) {
107 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
108 return;
109 }
110
111 service->addBatteryData(params);
112}
113
Dima Zavin799a70e2011-04-18 16:57:27 -0700114static int load_audio_interface(const char *if_name, const hw_module_t **mod,
115 audio_hw_device_t **dev)
116{
117 int rc;
118
119 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
120 if (rc)
121 goto out;
122
123 rc = audio_hw_device_open(*mod, dev);
124 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
125 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
126 if (rc)
127 goto out;
128
129 return 0;
130
131out:
132 *mod = NULL;
133 *dev = NULL;
134 return rc;
135}
136
137static const char *audio_interfaces[] = {
138 "primary",
139 "a2dp",
140 "usb",
141};
142#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
143
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144// ----------------------------------------------------------------------------
145
146AudioFlinger::AudioFlinger()
147 : BnAudioFlinger(),
Dima Zavin799a70e2011-04-18 16:57:27 -0700148 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700150}
151
152void AudioFlinger::onFirstRef()
153{
Dima Zavin799a70e2011-04-18 16:57:27 -0700154 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700155
Eric Laurent93575202011-01-18 18:39:02 -0800156 Mutex::Autolock _l(mLock);
157
Dima Zavin799a70e2011-04-18 16:57:27 -0700158 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159 mHardwareStatus = AUDIO_HW_IDLE;
160
Dima Zavin799a70e2011-04-18 16:57:27 -0700161 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
162 const hw_module_t *mod;
163 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700164
Dima Zavin799a70e2011-04-18 16:57:27 -0700165 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
166 if (rc)
167 continue;
168
169 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
170 mod->name, mod->id);
171 mAudioHwDevs.push(dev);
172
173 if (!mPrimaryHardwareDev) {
174 mPrimaryHardwareDev = dev;
175 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700176 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 }
178 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700179
180 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700181
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
183 LOGE("Primary audio interface not found");
184 return;
185 }
186
187 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
188 audio_hw_device_t *dev = mAudioHwDevs[i];
189
190 mHardwareStatus = AUDIO_HW_INIT;
191 rc = dev->init_check(dev);
192 if (rc == 0) {
193 AutoMutex lock(mHardwareLock);
194
195 mMode = AUDIO_MODE_NORMAL;
196 mHardwareStatus = AUDIO_HW_SET_MODE;
197 dev->set_mode(dev, mMode);
198 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
199 dev->set_master_volume(dev, 1.0f);
200 mHardwareStatus = AUDIO_HW_IDLE;
201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700202 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700203}
204
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700205status_t AudioFlinger::initCheck() const
206{
207 Mutex::Autolock _l(mLock);
208 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
209 return NO_INIT;
210 return NO_ERROR;
211}
212
Mathias Agopian65ab4712010-07-14 17:59:35 -0700213AudioFlinger::~AudioFlinger()
214{
Dima Zavin799a70e2011-04-18 16:57:27 -0700215 int num_devs = mAudioHwDevs.size();
216
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217 while (!mRecordThreads.isEmpty()) {
218 // closeInput() will remove first entry from mRecordThreads
219 closeInput(mRecordThreads.keyAt(0));
220 }
221 while (!mPlaybackThreads.isEmpty()) {
222 // closeOutput() will remove first entry from mPlaybackThreads
223 closeOutput(mPlaybackThreads.keyAt(0));
224 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700225
226 for (int i = 0; i < num_devs; i++) {
227 audio_hw_device_t *dev = mAudioHwDevs[i];
228 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700230 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231}
232
Dima Zavin799a70e2011-04-18 16:57:27 -0700233audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
234{
235 /* first matching HW device is returned */
236 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
237 audio_hw_device_t *dev = mAudioHwDevs[i];
238 if ((dev->get_supported_devices(dev) & devices) == devices)
239 return dev;
240 }
241 return NULL;
242}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243
244status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
245{
246 const size_t SIZE = 256;
247 char buffer[SIZE];
248 String8 result;
249
250 result.append("Clients:\n");
251 for (size_t i = 0; i < mClients.size(); ++i) {
252 wp<Client> wClient = mClients.valueAt(i);
253 if (wClient != 0) {
254 sp<Client> client = wClient.promote();
255 if (client != 0) {
256 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
257 result.append(buffer);
258 }
259 }
260 }
261 write(fd, result.string(), result.size());
262 return NO_ERROR;
263}
264
265
266status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
267{
268 const size_t SIZE = 256;
269 char buffer[SIZE];
270 String8 result;
271 int hardwareStatus = mHardwareStatus;
272
273 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
274 result.append(buffer);
275 write(fd, result.string(), result.size());
276 return NO_ERROR;
277}
278
279status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
280{
281 const size_t SIZE = 256;
282 char buffer[SIZE];
283 String8 result;
284 snprintf(buffer, SIZE, "Permission Denial: "
285 "can't dump AudioFlinger from pid=%d, uid=%d\n",
286 IPCThreadState::self()->getCallingPid(),
287 IPCThreadState::self()->getCallingUid());
288 result.append(buffer);
289 write(fd, result.string(), result.size());
290 return NO_ERROR;
291}
292
293static bool tryLock(Mutex& mutex)
294{
295 bool locked = false;
296 for (int i = 0; i < kDumpLockRetries; ++i) {
297 if (mutex.tryLock() == NO_ERROR) {
298 locked = true;
299 break;
300 }
301 usleep(kDumpLockSleep);
302 }
303 return locked;
304}
305
306status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
307{
308 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
309 dumpPermissionDenial(fd, args);
310 } else {
311 // get state of hardware lock
312 bool hardwareLocked = tryLock(mHardwareLock);
313 if (!hardwareLocked) {
314 String8 result(kHardwareLockedString);
315 write(fd, result.string(), result.size());
316 } else {
317 mHardwareLock.unlock();
318 }
319
320 bool locked = tryLock(mLock);
321
322 // failed to lock - AudioFlinger is probably deadlocked
323 if (!locked) {
324 String8 result(kDeadlockedString);
325 write(fd, result.string(), result.size());
326 }
327
328 dumpClients(fd, args);
329 dumpInternals(fd, args);
330
331 // dump playback threads
332 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
333 mPlaybackThreads.valueAt(i)->dump(fd, args);
334 }
335
336 // dump record threads
337 for (size_t i = 0; i < mRecordThreads.size(); i++) {
338 mRecordThreads.valueAt(i)->dump(fd, args);
339 }
340
Dima Zavin799a70e2011-04-18 16:57:27 -0700341 // dump all hardware devs
342 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
343 audio_hw_device_t *dev = mAudioHwDevs[i];
344 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345 }
346 if (locked) mLock.unlock();
347 }
348 return NO_ERROR;
349}
350
351
352// IAudioFlinger interface
353
354
355sp<IAudioTrack> AudioFlinger::createTrack(
356 pid_t pid,
357 int streamType,
358 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700359 uint32_t format,
360 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361 int frameCount,
362 uint32_t flags,
363 const sp<IMemory>& sharedBuffer,
364 int output,
365 int *sessionId,
366 status_t *status)
367{
368 sp<PlaybackThread::Track> track;
369 sp<TrackHandle> trackHandle;
370 sp<Client> client;
371 wp<Client> wclient;
372 status_t lStatus;
373 int lSessionId;
374
Dima Zavinfce7a472011-04-19 22:30:36 -0700375 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 LOGE("invalid stream type");
377 lStatus = BAD_VALUE;
378 goto Exit;
379 }
380
381 {
382 Mutex::Autolock _l(mLock);
383 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700384 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 if (thread == NULL) {
386 LOGE("unknown output thread");
387 lStatus = BAD_VALUE;
388 goto Exit;
389 }
390
391 wclient = mClients.valueFor(pid);
392
393 if (wclient != NULL) {
394 client = wclient.promote();
395 } else {
396 client = new Client(this, pid);
397 mClients.add(pid, client);
398 }
399
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700401 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700402 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700403 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
404 if (mPlaybackThreads.keyAt(i) != output) {
405 // prevent same audio session on different output threads
406 uint32_t sessions = t->hasAudioSession(*sessionId);
407 if (sessions & PlaybackThread::TRACK_SESSION) {
408 lStatus = BAD_VALUE;
409 goto Exit;
410 }
411 // check if an effect with same session ID is waiting for a track to be created
412 if (sessions & PlaybackThread::EFFECT_SESSION) {
413 effectThread = t.get();
414 }
Eric Laurentde070132010-07-13 04:45:46 -0700415 }
416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417 lSessionId = *sessionId;
418 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700419 // if no audio session id is provided, create one here
Eric Laurentf5aafb22010-11-18 08:40:16 -0800420 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 if (sessionId != NULL) {
422 *sessionId = lSessionId;
423 }
424 }
425 LOGV("createTrack() lSessionId: %d", lSessionId);
426
427 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700428 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700429
430 // move effect chain to this output thread if an effect on same session was waiting
431 // for a track to be created
432 if (lStatus == NO_ERROR && effectThread != NULL) {
433 Mutex::Autolock _dl(thread->mLock);
434 Mutex::Autolock _sl(effectThread->mLock);
435 moveEffectChain_l(lSessionId, effectThread, thread, true);
436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 }
438 if (lStatus == NO_ERROR) {
439 trackHandle = new TrackHandle(track);
440 } else {
441 // remove local strong reference to Client before deleting the Track so that the Client
442 // destructor is called by the TrackBase destructor with mLock held
443 client.clear();
444 track.clear();
445 }
446
447Exit:
448 if(status) {
449 *status = lStatus;
450 }
451 return trackHandle;
452}
453
454uint32_t AudioFlinger::sampleRate(int output) const
455{
456 Mutex::Autolock _l(mLock);
457 PlaybackThread *thread = checkPlaybackThread_l(output);
458 if (thread == NULL) {
459 LOGW("sampleRate() unknown thread %d", output);
460 return 0;
461 }
462 return thread->sampleRate();
463}
464
465int AudioFlinger::channelCount(int output) const
466{
467 Mutex::Autolock _l(mLock);
468 PlaybackThread *thread = checkPlaybackThread_l(output);
469 if (thread == NULL) {
470 LOGW("channelCount() unknown thread %d", output);
471 return 0;
472 }
473 return thread->channelCount();
474}
475
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700476uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477{
478 Mutex::Autolock _l(mLock);
479 PlaybackThread *thread = checkPlaybackThread_l(output);
480 if (thread == NULL) {
481 LOGW("format() unknown thread %d", output);
482 return 0;
483 }
484 return thread->format();
485}
486
487size_t AudioFlinger::frameCount(int output) const
488{
489 Mutex::Autolock _l(mLock);
490 PlaybackThread *thread = checkPlaybackThread_l(output);
491 if (thread == NULL) {
492 LOGW("frameCount() unknown thread %d", output);
493 return 0;
494 }
495 return thread->frameCount();
496}
497
498uint32_t AudioFlinger::latency(int output) const
499{
500 Mutex::Autolock _l(mLock);
501 PlaybackThread *thread = checkPlaybackThread_l(output);
502 if (thread == NULL) {
503 LOGW("latency() unknown thread %d", output);
504 return 0;
505 }
506 return thread->latency();
507}
508
509status_t AudioFlinger::setMasterVolume(float value)
510{
511 // check calling permissions
512 if (!settingsAllowed()) {
513 return PERMISSION_DENIED;
514 }
515
516 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800517 { // scope for the lock
518 AutoMutex lock(mHardwareLock);
519 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700520 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800521 value = 1.0f;
522 }
523 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525
Eric Laurent93575202011-01-18 18:39:02 -0800526 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527 mMasterVolume = value;
528 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
529 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
530
531 return NO_ERROR;
532}
533
534status_t AudioFlinger::setMode(int mode)
535{
536 status_t ret;
537
538 // check calling permissions
539 if (!settingsAllowed()) {
540 return PERMISSION_DENIED;
541 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700542 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 LOGW("Illegal value: setMode(%d)", mode);
544 return BAD_VALUE;
545 }
546
547 { // scope for the lock
548 AutoMutex lock(mHardwareLock);
549 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700550 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551 mHardwareStatus = AUDIO_HW_IDLE;
552 }
553
554 if (NO_ERROR == ret) {
555 Mutex::Autolock _l(mLock);
556 mMode = mode;
557 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
558 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 }
560
561 return ret;
562}
563
564status_t AudioFlinger::setMicMute(bool state)
565{
566 // check calling permissions
567 if (!settingsAllowed()) {
568 return PERMISSION_DENIED;
569 }
570
571 AutoMutex lock(mHardwareLock);
572 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700573 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 mHardwareStatus = AUDIO_HW_IDLE;
575 return ret;
576}
577
578bool AudioFlinger::getMicMute() const
579{
Dima Zavinfce7a472011-04-19 22:30:36 -0700580 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700582 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 mHardwareStatus = AUDIO_HW_IDLE;
584 return state;
585}
586
587status_t AudioFlinger::setMasterMute(bool muted)
588{
589 // check calling permissions
590 if (!settingsAllowed()) {
591 return PERMISSION_DENIED;
592 }
593
Eric Laurent93575202011-01-18 18:39:02 -0800594 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595 mMasterMute = muted;
596 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
597 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
598
599 return NO_ERROR;
600}
601
602float AudioFlinger::masterVolume() const
603{
604 return mMasterVolume;
605}
606
607bool AudioFlinger::masterMute() const
608{
609 return mMasterMute;
610}
611
612status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
613{
614 // check calling permissions
615 if (!settingsAllowed()) {
616 return PERMISSION_DENIED;
617 }
618
Dima Zavinfce7a472011-04-19 22:30:36 -0700619 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700620 return BAD_VALUE;
621 }
622
623 AutoMutex lock(mLock);
624 PlaybackThread *thread = NULL;
625 if (output) {
626 thread = checkPlaybackThread_l(output);
627 if (thread == NULL) {
628 return BAD_VALUE;
629 }
630 }
631
632 mStreamTypes[stream].volume = value;
633
634 if (thread == NULL) {
635 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
636 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
637 }
638 } else {
639 thread->setStreamVolume(stream, value);
640 }
641
642 return NO_ERROR;
643}
644
645status_t AudioFlinger::setStreamMute(int stream, bool muted)
646{
647 // check calling permissions
648 if (!settingsAllowed()) {
649 return PERMISSION_DENIED;
650 }
651
Dima Zavinfce7a472011-04-19 22:30:36 -0700652 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
653 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654 return BAD_VALUE;
655 }
656
Eric Laurent93575202011-01-18 18:39:02 -0800657 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 mStreamTypes[stream].mute = muted;
659 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
660 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
661
662 return NO_ERROR;
663}
664
665float AudioFlinger::streamVolume(int stream, int output) const
666{
Dima Zavinfce7a472011-04-19 22:30:36 -0700667 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 return 0.0f;
669 }
670
671 AutoMutex lock(mLock);
672 float volume;
673 if (output) {
674 PlaybackThread *thread = checkPlaybackThread_l(output);
675 if (thread == NULL) {
676 return 0.0f;
677 }
678 volume = thread->streamVolume(stream);
679 } else {
680 volume = mStreamTypes[stream].volume;
681 }
682
683 return volume;
684}
685
686bool AudioFlinger::streamMute(int stream) const
687{
Dima Zavinfce7a472011-04-19 22:30:36 -0700688 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 return true;
690 }
691
692 return mStreamTypes[stream].mute;
693}
694
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
696{
697 status_t result;
698
699 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
700 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
701 // check calling permissions
702 if (!settingsAllowed()) {
703 return PERMISSION_DENIED;
704 }
705
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 // ioHandle == 0 means the parameters are global to the audio hardware interface
707 if (ioHandle == 0) {
708 AutoMutex lock(mHardwareLock);
709 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700710 status_t final_result = NO_ERROR;
711 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
712 audio_hw_device_t *dev = mAudioHwDevs[i];
713 result = dev->set_parameters(dev, keyValuePairs.string());
714 final_result = result ?: final_result;
715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700717 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 }
719
720 // hold a strong ref on thread in case closeOutput() or closeInput() is called
721 // and the thread is exited once the lock is released
722 sp<ThreadBase> thread;
723 {
724 Mutex::Autolock _l(mLock);
725 thread = checkPlaybackThread_l(ioHandle);
726 if (thread == NULL) {
727 thread = checkRecordThread_l(ioHandle);
728 }
729 }
730 if (thread != NULL) {
731 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 return result;
733 }
734 return BAD_VALUE;
735}
736
737String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
738{
739// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
740// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
741
742 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700743 String8 out_s8;
744
Dima Zavin799a70e2011-04-18 16:57:27 -0700745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
746 audio_hw_device_t *dev = mAudioHwDevs[i];
747 char *s = dev->get_parameters(dev, keys.string());
748 out_s8 += String8(s);
749 free(s);
750 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700751 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 }
753
754 Mutex::Autolock _l(mLock);
755
756 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
757 if (playbackThread != NULL) {
758 return playbackThread->getParameters(keys);
759 }
760 RecordThread *recordThread = checkRecordThread_l(ioHandle);
761 if (recordThread != NULL) {
762 return recordThread->getParameters(keys);
763 }
764 return String8("");
765}
766
767size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
768{
Dima Zavin799a70e2011-04-18 16:57:27 -0700769 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770}
771
772unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
773{
774 if (ioHandle == 0) {
775 return 0;
776 }
777
778 Mutex::Autolock _l(mLock);
779
780 RecordThread *recordThread = checkRecordThread_l(ioHandle);
781 if (recordThread != NULL) {
782 return recordThread->getInputFramesLost();
783 }
784 return 0;
785}
786
787status_t AudioFlinger::setVoiceVolume(float value)
788{
789 // check calling permissions
790 if (!settingsAllowed()) {
791 return PERMISSION_DENIED;
792 }
793
794 AutoMutex lock(mHardwareLock);
795 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700796 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 mHardwareStatus = AUDIO_HW_IDLE;
798
799 return ret;
800}
801
802status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
803{
804 status_t status;
805
806 Mutex::Autolock _l(mLock);
807
808 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
809 if (playbackThread != NULL) {
810 return playbackThread->getRenderPosition(halFrames, dspFrames);
811 }
812
813 return BAD_VALUE;
814}
815
816void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
817{
818
819 Mutex::Autolock _l(mLock);
820
821 int pid = IPCThreadState::self()->getCallingPid();
822 if (mNotificationClients.indexOfKey(pid) < 0) {
823 sp<NotificationClient> notificationClient = new NotificationClient(this,
824 client,
825 pid);
826 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
827
828 mNotificationClients.add(pid, notificationClient);
829
830 sp<IBinder> binder = client->asBinder();
831 binder->linkToDeath(notificationClient);
832
833 // the config change is always sent from playback or record threads to avoid deadlock
834 // with AudioSystem::gLock
835 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
836 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
837 }
838
839 for (size_t i = 0; i < mRecordThreads.size(); i++) {
840 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
841 }
842 }
843}
844
845void AudioFlinger::removeNotificationClient(pid_t pid)
846{
847 Mutex::Autolock _l(mLock);
848
849 int index = mNotificationClients.indexOfKey(pid);
850 if (index >= 0) {
851 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
852 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 mNotificationClients.removeItem(pid);
854 }
855}
856
857// audioConfigChanged_l() must be called with AudioFlinger::mLock held
858void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
859{
860 size_t size = mNotificationClients.size();
861 for (size_t i = 0; i < size; i++) {
862 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
863 }
864}
865
866// removeClient_l() must be called with AudioFlinger::mLock held
867void AudioFlinger::removeClient_l(pid_t pid)
868{
869 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
870 mClients.removeItem(pid);
871}
872
873
874// ----------------------------------------------------------------------------
875
876AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
877 : Thread(false),
878 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
879 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
880{
881}
882
883AudioFlinger::ThreadBase::~ThreadBase()
884{
885 mParamCond.broadcast();
886 mNewParameters.clear();
887}
888
889void AudioFlinger::ThreadBase::exit()
890{
891 // keep a strong ref on ourself so that we wont get
892 // destroyed in the middle of requestExitAndWait()
893 sp <ThreadBase> strongMe = this;
894
895 LOGV("ThreadBase::exit");
896 {
897 AutoMutex lock(&mLock);
898 mExiting = true;
899 requestExit();
900 mWaitWorkCV.signal();
901 }
902 requestExitAndWait();
903}
904
905uint32_t AudioFlinger::ThreadBase::sampleRate() const
906{
907 return mSampleRate;
908}
909
910int AudioFlinger::ThreadBase::channelCount() const
911{
912 return (int)mChannelCount;
913}
914
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700915uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916{
917 return mFormat;
918}
919
920size_t AudioFlinger::ThreadBase::frameCount() const
921{
922 return mFrameCount;
923}
924
925status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
926{
927 status_t status;
928
929 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
930 Mutex::Autolock _l(mLock);
931
932 mNewParameters.add(keyValuePairs);
933 mWaitWorkCV.signal();
934 // wait condition with timeout in case the thread loop has exited
935 // before the request could be processed
936 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
937 status = mParamStatus;
938 mWaitWorkCV.signal();
939 } else {
940 status = TIMED_OUT;
941 }
942 return status;
943}
944
945void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
946{
947 Mutex::Autolock _l(mLock);
948 sendConfigEvent_l(event, param);
949}
950
951// sendConfigEvent_l() must be called with ThreadBase::mLock held
952void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
953{
954 ConfigEvent *configEvent = new ConfigEvent();
955 configEvent->mEvent = event;
956 configEvent->mParam = param;
957 mConfigEvents.add(configEvent);
958 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
959 mWaitWorkCV.signal();
960}
961
962void AudioFlinger::ThreadBase::processConfigEvents()
963{
964 mLock.lock();
965 while(!mConfigEvents.isEmpty()) {
966 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
967 ConfigEvent *configEvent = mConfigEvents[0];
968 mConfigEvents.removeAt(0);
969 // release mLock before locking AudioFlinger mLock: lock order is always
970 // AudioFlinger then ThreadBase to avoid cross deadlock
971 mLock.unlock();
972 mAudioFlinger->mLock.lock();
973 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
974 mAudioFlinger->mLock.unlock();
975 delete configEvent;
976 mLock.lock();
977 }
978 mLock.unlock();
979}
980
981status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
982{
983 const size_t SIZE = 256;
984 char buffer[SIZE];
985 String8 result;
986
987 bool locked = tryLock(mLock);
988 if (!locked) {
989 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
990 write(fd, buffer, strlen(buffer));
991 }
992
993 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
994 result.append(buffer);
995 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
996 result.append(buffer);
997 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
998 result.append(buffer);
999 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1000 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001001 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1002 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1004 result.append(buffer);
1005 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1006 result.append(buffer);
1007
1008 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1009 result.append(buffer);
1010 result.append(" Index Command");
1011 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1012 snprintf(buffer, SIZE, "\n %02d ", i);
1013 result.append(buffer);
1014 result.append(mNewParameters[i]);
1015 }
1016
1017 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1018 result.append(buffer);
1019 snprintf(buffer, SIZE, " Index event param\n");
1020 result.append(buffer);
1021 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1022 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1023 result.append(buffer);
1024 }
1025 result.append("\n");
1026
1027 write(fd, result.string(), result.size());
1028
1029 if (locked) {
1030 mLock.unlock();
1031 }
1032 return NO_ERROR;
1033}
1034
1035
1036// ----------------------------------------------------------------------------
1037
Dima Zavin799a70e2011-04-18 16:57:27 -07001038AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039 : ThreadBase(audioFlinger, id),
1040 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
1041 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1042 mDevice(device)
1043{
1044 readOutputParameters();
1045
1046 mMasterVolume = mAudioFlinger->masterVolume();
1047 mMasterMute = mAudioFlinger->masterMute();
1048
Dima Zavinfce7a472011-04-19 22:30:36 -07001049 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1051 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1052 }
1053}
1054
1055AudioFlinger::PlaybackThread::~PlaybackThread()
1056{
1057 delete [] mMixBuffer;
1058}
1059
1060status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1061{
1062 dumpInternals(fd, args);
1063 dumpTracks(fd, args);
1064 dumpEffectChains(fd, args);
1065 return NO_ERROR;
1066}
1067
1068status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1069{
1070 const size_t SIZE = 256;
1071 char buffer[SIZE];
1072 String8 result;
1073
1074 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1075 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001076 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 for (size_t i = 0; i < mTracks.size(); ++i) {
1078 sp<Track> track = mTracks[i];
1079 if (track != 0) {
1080 track->dump(buffer, SIZE);
1081 result.append(buffer);
1082 }
1083 }
1084
1085 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1086 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001087 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1089 wp<Track> wTrack = mActiveTracks[i];
1090 if (wTrack != 0) {
1091 sp<Track> track = wTrack.promote();
1092 if (track != 0) {
1093 track->dump(buffer, SIZE);
1094 result.append(buffer);
1095 }
1096 }
1097 }
1098 write(fd, result.string(), result.size());
1099 return NO_ERROR;
1100}
1101
1102status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1103{
1104 const size_t SIZE = 256;
1105 char buffer[SIZE];
1106 String8 result;
1107
1108 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1109 write(fd, buffer, strlen(buffer));
1110
1111 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1112 sp<EffectChain> chain = mEffectChains[i];
1113 if (chain != 0) {
1114 chain->dump(fd, args);
1115 }
1116 }
1117 return NO_ERROR;
1118}
1119
1120status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1121{
1122 const size_t SIZE = 256;
1123 char buffer[SIZE];
1124 String8 result;
1125
1126 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1127 result.append(buffer);
1128 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1129 result.append(buffer);
1130 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1133 result.append(buffer);
1134 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1137 result.append(buffer);
1138 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1139 result.append(buffer);
1140 write(fd, result.string(), result.size());
1141
1142 dumpBase(fd, args);
1143
1144 return NO_ERROR;
1145}
1146
1147// Thread virtuals
1148status_t AudioFlinger::PlaybackThread::readyToRun()
1149{
1150 if (mSampleRate == 0) {
1151 LOGE("No working audio driver found.");
1152 return NO_INIT;
1153 }
1154 LOGI("AudioFlinger's thread %p ready to run", this);
1155 return NO_ERROR;
1156}
1157
1158void AudioFlinger::PlaybackThread::onFirstRef()
1159{
1160 const size_t SIZE = 256;
1161 char buffer[SIZE];
1162
1163 snprintf(buffer, SIZE, "Playback Thread %p", this);
1164
1165 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1166}
1167
1168// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1169sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1170 const sp<AudioFlinger::Client>& client,
1171 int streamType,
1172 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001173 uint32_t format,
1174 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 int frameCount,
1176 const sp<IMemory>& sharedBuffer,
1177 int sessionId,
1178 status_t *status)
1179{
1180 sp<Track> track;
1181 status_t lStatus;
1182
1183 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001184 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1185 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1186 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1187 "for output %p with format %d",
1188 sampleRate, format, channelMask, mOutput, mFormat);
1189 lStatus = BAD_VALUE;
1190 goto Exit;
1191 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 }
1193 } else {
1194 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1195 if (sampleRate > mSampleRate*2) {
1196 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1197 lStatus = BAD_VALUE;
1198 goto Exit;
1199 }
1200 }
1201
1202 if (mOutput == 0) {
1203 LOGE("Audio driver not initialized.");
1204 lStatus = NO_INIT;
1205 goto Exit;
1206 }
1207
1208 { // scope for mLock
1209 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001210
1211 // all tracks in same audio session must share the same routing strategy otherwise
1212 // conflicts will happen when tracks are moved from one output to another by audio policy
1213 // manager
1214 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001215 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001216 for (size_t i = 0; i < mTracks.size(); ++i) {
1217 sp<Track> t = mTracks[i];
1218 if (t != 0) {
1219 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001220 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001221 lStatus = BAD_VALUE;
1222 goto Exit;
1223 }
1224 }
1225 }
1226
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001228 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229 if (track->getCblk() == NULL || track->name() < 0) {
1230 lStatus = NO_MEMORY;
1231 goto Exit;
1232 }
1233 mTracks.add(track);
1234
1235 sp<EffectChain> chain = getEffectChain_l(sessionId);
1236 if (chain != 0) {
1237 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1238 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001239 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001240 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 }
1242 }
1243 lStatus = NO_ERROR;
1244
1245Exit:
1246 if(status) {
1247 *status = lStatus;
1248 }
1249 return track;
1250}
1251
1252uint32_t AudioFlinger::PlaybackThread::latency() const
1253{
1254 if (mOutput) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001255 return mOutput->stream->get_latency(mOutput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 }
1257 else {
1258 return 0;
1259 }
1260}
1261
1262status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1263{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 mMasterVolume = value;
1265 return NO_ERROR;
1266}
1267
1268status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1269{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 mMasterMute = muted;
1271 return NO_ERROR;
1272}
1273
1274float AudioFlinger::PlaybackThread::masterVolume() const
1275{
1276 return mMasterVolume;
1277}
1278
1279bool AudioFlinger::PlaybackThread::masterMute() const
1280{
1281 return mMasterMute;
1282}
1283
1284status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1285{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 mStreamTypes[stream].volume = value;
1287 return NO_ERROR;
1288}
1289
1290status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1291{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292 mStreamTypes[stream].mute = muted;
1293 return NO_ERROR;
1294}
1295
1296float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1297{
1298 return mStreamTypes[stream].volume;
1299}
1300
1301bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1302{
1303 return mStreamTypes[stream].mute;
1304}
1305
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306// addTrack_l() must be called with ThreadBase::mLock held
1307status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1308{
1309 status_t status = ALREADY_EXISTS;
1310
1311 // set retry count for buffer fill
1312 track->mRetryCount = kMaxTrackStartupRetries;
1313 if (mActiveTracks.indexOf(track) < 0) {
1314 // the track is newly added, make sure it fills up all its
1315 // buffers before playing. This is to ensure the client will
1316 // effectively get the latency it requested.
1317 track->mFillingUpStatus = Track::FS_FILLING;
1318 track->mResetDone = false;
1319 mActiveTracks.add(track);
1320 if (track->mainBuffer() != mMixBuffer) {
1321 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1322 if (chain != 0) {
1323 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001324 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325 }
1326 }
1327
1328 status = NO_ERROR;
1329 }
1330
1331 LOGV("mWaitWorkCV.broadcast");
1332 mWaitWorkCV.broadcast();
1333
1334 return status;
1335}
1336
1337// destroyTrack_l() must be called with ThreadBase::mLock held
1338void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1339{
1340 track->mState = TrackBase::TERMINATED;
1341 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001342 removeTrack_l(track);
1343 }
1344}
1345
1346void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1347{
1348 mTracks.remove(track);
1349 deleteTrackName_l(track->name());
1350 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1351 if (chain != 0) {
1352 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353 }
1354}
1355
1356String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1357{
Dima Zavinfce7a472011-04-19 22:30:36 -07001358 String8 out_s8;
1359 char *s;
1360
Dima Zavin799a70e2011-04-18 16:57:27 -07001361 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001362 out_s8 = String8(s);
1363 free(s);
1364 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365}
1366
1367// destroyTrack_l() must be called with AudioFlinger::mLock held
1368void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1369 AudioSystem::OutputDescriptor desc;
1370 void *param2 = 0;
1371
1372 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1373
1374 switch (event) {
1375 case AudioSystem::OUTPUT_OPENED:
1376 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001377 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378 desc.samplingRate = mSampleRate;
1379 desc.format = mFormat;
1380 desc.frameCount = mFrameCount;
1381 desc.latency = latency();
1382 param2 = &desc;
1383 break;
1384
1385 case AudioSystem::STREAM_CONFIG_CHANGED:
1386 param2 = &param;
1387 case AudioSystem::OUTPUT_CLOSED:
1388 default:
1389 break;
1390 }
1391 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1392}
1393
1394void AudioFlinger::PlaybackThread::readOutputParameters()
1395{
Dima Zavin799a70e2011-04-18 16:57:27 -07001396 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001397 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1398 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001399 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1400 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1401 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402
1403 // FIXME - Current mixer implementation only supports stereo output: Always
1404 // Allocate a stereo buffer even if HW output is mono.
1405 if (mMixBuffer != NULL) delete[] mMixBuffer;
1406 mMixBuffer = new int16_t[mFrameCount * 2];
1407 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1408
Eric Laurentde070132010-07-13 04:45:46 -07001409 // force reconfiguration of effect chains and engines to take new buffer size and audio
1410 // parameters into account
1411 // Note that mLock is not held when readOutputParameters() is called from the constructor
1412 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1413 // matter.
1414 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1415 Vector< sp<EffectChain> > effectChains = mEffectChains;
1416 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001417 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001419}
1420
1421status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1422{
1423 if (halFrames == 0 || dspFrames == 0) {
1424 return BAD_VALUE;
1425 }
1426 if (mOutput == 0) {
1427 return INVALID_OPERATION;
1428 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001429 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001430
Dima Zavin799a70e2011-04-18 16:57:27 -07001431 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432}
1433
Eric Laurent39e94f82010-07-28 01:32:47 -07001434uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001435{
1436 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001437 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001439 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 }
1441
1442 for (size_t i = 0; i < mTracks.size(); ++i) {
1443 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001444 if (sessionId == track->sessionId() &&
1445 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001446 result |= TRACK_SESSION;
1447 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448 }
1449 }
1450
Eric Laurent39e94f82010-07-28 01:32:47 -07001451 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452}
1453
Eric Laurentde070132010-07-13 04:45:46 -07001454uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1455{
Dima Zavinfce7a472011-04-19 22:30:36 -07001456 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001457 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001458 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1459 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001460 }
1461 for (size_t i = 0; i < mTracks.size(); i++) {
1462 sp<Track> track = mTracks[i];
1463 if (sessionId == track->sessionId() &&
1464 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001465 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001466 }
1467 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001468 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001469}
1470
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1472{
1473 Mutex::Autolock _l(mLock);
1474 return getEffectChain_l(sessionId);
1475}
1476
1477sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1478{
1479 sp<EffectChain> chain;
1480
1481 size_t size = mEffectChains.size();
1482 for (size_t i = 0; i < size; i++) {
1483 if (mEffectChains[i]->sessionId() == sessionId) {
1484 chain = mEffectChains[i];
1485 break;
1486 }
1487 }
1488 return chain;
1489}
1490
1491void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1492{
1493 Mutex::Autolock _l(mLock);
1494 size_t size = mEffectChains.size();
1495 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001496 mEffectChains[i]->setMode_l(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 }
1498}
1499
1500// ----------------------------------------------------------------------------
1501
Dima Zavin799a70e2011-04-18 16:57:27 -07001502AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 : PlaybackThread(audioFlinger, output, id, device),
1504 mAudioMixer(0)
1505{
1506 mType = PlaybackThread::MIXER;
1507 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1508
1509 // FIXME - Current mixer implementation only supports stereo output
1510 if (mChannelCount == 1) {
1511 LOGE("Invalid audio hardware channel count");
1512 }
1513}
1514
1515AudioFlinger::MixerThread::~MixerThread()
1516{
1517 delete mAudioMixer;
1518}
1519
1520bool AudioFlinger::MixerThread::threadLoop()
1521{
1522 Vector< sp<Track> > tracksToRemove;
1523 uint32_t mixerStatus = MIXER_IDLE;
1524 nsecs_t standbyTime = systemTime();
1525 size_t mixBufferSize = mFrameCount * mFrameSize;
1526 // FIXME: Relaxed timing because of a certain device that can't meet latency
1527 // Should be reduced to 2x after the vendor fixes the driver issue
1528 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1529 nsecs_t lastWarning = 0;
1530 bool longStandbyExit = false;
1531 uint32_t activeSleepTime = activeSleepTimeUs();
1532 uint32_t idleSleepTime = idleSleepTimeUs();
1533 uint32_t sleepTime = idleSleepTime;
1534 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001535#ifdef DEBUG_CPU_USAGE
1536 ThreadCpuUsage cpu;
1537 const CentralTendencyStatistics& stats = cpu.statistics();
1538#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539
1540 while (!exitPending())
1541 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001542#ifdef DEBUG_CPU_USAGE
1543 cpu.sampleAndEnable();
1544 unsigned n = stats.n();
1545 // cpu.elapsed() is expensive, so don't call it every loop
1546 if ((n & 127) == 1) {
1547 long long elapsed = cpu.elapsed();
1548 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1549 double perLoop = elapsed / (double) n;
1550 double perLoop100 = perLoop * 0.01;
1551 double mean = stats.mean();
1552 double stddev = stats.stddev();
1553 double minimum = stats.minimum();
1554 double maximum = stats.maximum();
1555 cpu.resetStatistics();
1556 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",
1557 elapsed * .000000001, n, perLoop * .000001,
1558 mean * .001,
1559 stddev * .001,
1560 minimum * .001,
1561 maximum * .001,
1562 mean / perLoop100,
1563 stddev / perLoop100,
1564 minimum / perLoop100,
1565 maximum / perLoop100);
1566 }
1567 }
1568#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 processConfigEvents();
1570
1571 mixerStatus = MIXER_IDLE;
1572 { // scope for mLock
1573
1574 Mutex::Autolock _l(mLock);
1575
1576 if (checkForNewParameters_l()) {
1577 mixBufferSize = mFrameCount * mFrameSize;
1578 // FIXME: Relaxed timing because of a certain device that can't meet latency
1579 // Should be reduced to 2x after the vendor fixes the driver issue
1580 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1581 activeSleepTime = activeSleepTimeUs();
1582 idleSleepTime = idleSleepTimeUs();
1583 }
1584
1585 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1586
1587 // put audio hardware into standby after short delay
1588 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1589 mSuspended) {
1590 if (!mStandby) {
1591 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001592 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 mStandby = true;
1594 mBytesWritten = 0;
1595 }
1596
1597 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1598 // we're about to wait, flush the binder command buffer
1599 IPCThreadState::self()->flushCommands();
1600
1601 if (exitPending()) break;
1602
1603 // wait until we have something to do...
1604 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1605 mWaitWorkCV.wait(mLock);
1606 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1607
1608 if (mMasterMute == false) {
1609 char value[PROPERTY_VALUE_MAX];
1610 property_get("ro.audio.silent", value, "0");
1611 if (atoi(value)) {
1612 LOGD("Silence is golden");
1613 setMasterMute(true);
1614 }
1615 }
1616
1617 standbyTime = systemTime() + kStandbyTimeInNsecs;
1618 sleepTime = idleSleepTime;
1619 continue;
1620 }
1621 }
1622
1623 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1624
1625 // prevent any changes in effect chain list and in each effect chain
1626 // during mixing and effect process as the audio buffers could be deleted
1627 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001628 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 }
1630
1631 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1632 // mix buffers...
1633 mAudioMixer->process();
1634 sleepTime = 0;
1635 standbyTime = systemTime() + kStandbyTimeInNsecs;
1636 //TODO: delay standby when effects have a tail
1637 } else {
1638 // If no tracks are ready, sleep once for the duration of an output
1639 // buffer size, then write 0s to the output
1640 if (sleepTime == 0) {
1641 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1642 sleepTime = activeSleepTime;
1643 } else {
1644 sleepTime = idleSleepTime;
1645 }
1646 } else if (mBytesWritten != 0 ||
1647 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1648 memset (mMixBuffer, 0, mixBufferSize);
1649 sleepTime = 0;
1650 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1651 }
1652 // TODO add standby time extension fct of effect tail
1653 }
1654
1655 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001656 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 }
1658 // sleepTime == 0 means we must write to audio hardware
1659 if (sleepTime == 0) {
1660 for (size_t i = 0; i < effectChains.size(); i ++) {
1661 effectChains[i]->process_l();
1662 }
1663 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001664 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 mLastWriteTime = systemTime();
1666 mInWrite = true;
1667 mBytesWritten += mixBufferSize;
1668
Dima Zavin799a70e2011-04-18 16:57:27 -07001669 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1671 mNumWrites++;
1672 mInWrite = false;
1673 nsecs_t now = systemTime();
1674 nsecs_t delta = now - mLastWriteTime;
1675 if (delta > maxPeriod) {
1676 mNumDelayedWrites++;
1677 if ((now - lastWarning) > kWarningThrottle) {
1678 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1679 ns2ms(delta), mNumDelayedWrites, this);
1680 lastWarning = now;
1681 }
1682 if (mStandby) {
1683 longStandbyExit = true;
1684 }
1685 }
1686 mStandby = false;
1687 } else {
1688 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001689 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 usleep(sleepTime);
1691 }
1692
1693 // finally let go of all our tracks, without the lock held
1694 // since we can't guarantee the destructors won't acquire that
1695 // same lock.
1696 tracksToRemove.clear();
1697
1698 // Effect chains will be actually deleted here if they were removed from
1699 // mEffectChains list during mixing or effects processing
1700 effectChains.clear();
1701 }
1702
1703 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001704 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 }
1706
1707 LOGV("MixerThread %p exiting", this);
1708 return false;
1709}
1710
1711// prepareTracks_l() must be called with ThreadBase::mLock held
1712uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1713{
1714
1715 uint32_t mixerStatus = MIXER_IDLE;
1716 // find out which tracks need to be processed
1717 size_t count = activeTracks.size();
1718 size_t mixedTracks = 0;
1719 size_t tracksWithEffect = 0;
1720
1721 float masterVolume = mMasterVolume;
1722 bool masterMute = mMasterMute;
1723
Eric Laurent571d49c2010-08-11 05:20:11 -07001724 if (masterMute) {
1725 masterVolume = 0;
1726 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07001728 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07001730 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07001731 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 masterVolume = (float)((v + (1 << 23)) >> 24);
1733 chain.clear();
1734 }
1735
1736 for (size_t i=0 ; i<count ; i++) {
1737 sp<Track> t = activeTracks[i].promote();
1738 if (t == 0) continue;
1739
1740 Track* const track = t.get();
1741 audio_track_cblk_t* cblk = track->cblk();
1742
1743 // The first time a track is added we wait
1744 // for all its buffers to be filled before processing it
1745 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07001746 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 !track->isPaused() && !track->isTerminated())
1748 {
1749 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1750
1751 mixedTracks++;
1752
1753 // track->mainBuffer() != mMixBuffer means there is an effect chain
1754 // connected to the track
1755 chain.clear();
1756 if (track->mainBuffer() != mMixBuffer) {
1757 chain = getEffectChain_l(track->sessionId());
1758 // Delegate volume control to effect in track effect chain if needed
1759 if (chain != 0) {
1760 tracksWithEffect++;
1761 } else {
1762 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1763 track->name(), track->sessionId());
1764 }
1765 }
1766
1767
1768 int param = AudioMixer::VOLUME;
1769 if (track->mFillingUpStatus == Track::FS_FILLED) {
1770 // no ramp for the first volume setting
1771 track->mFillingUpStatus = Track::FS_ACTIVE;
1772 if (track->mState == TrackBase::RESUMING) {
1773 track->mState = TrackBase::ACTIVE;
1774 param = AudioMixer::RAMP_VOLUME;
1775 }
Eric Laurent243f5f92011-02-28 16:52:51 -08001776 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777 } else if (cblk->server != 0) {
1778 // If the track is stopped before the first frame was mixed,
1779 // do not apply ramp
1780 param = AudioMixer::RAMP_VOLUME;
1781 }
1782
1783 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07001784 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07001785 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001787 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 if (track->isPausing()) {
1789 track->setPaused();
1790 }
1791 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001792
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 // read original volumes with volume control
1794 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07001796 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1797 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798
Eric Laurente0aed6d2010-09-10 17:44:44 -07001799 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07001801 // Delegate volume control to effect in track effect chain if needed
1802 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1803 // Do not ramp volume if volume is controlled by effect
1804 param = AudioMixer::VOLUME;
1805 track->mHasVolumeController = true;
1806 } else {
1807 // force no volume ramp when volume controller was just disabled or removed
1808 // from effect chain to avoid volume spike
1809 if (track->mHasVolumeController) {
1810 param = AudioMixer::VOLUME;
1811 }
1812 track->mHasVolumeController = false;
1813 }
1814
1815 // Convert volumes from 8.24 to 4.12 format
1816 int16_t left, right, aux;
1817 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1818 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1819 left = int16_t(v_clamped);
1820 v_clamped = (vr + (1 << 11)) >> 12;
1821 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1822 right = int16_t(v_clamped);
1823
1824 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1825 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827 // XXX: these things DON'T need to be done each time
1828 mAudioMixer->setBufferProvider(track);
1829 mAudioMixer->enable(AudioMixer::MIXING);
1830
1831 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1832 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1833 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
1834 mAudioMixer->setParameter(
1835 AudioMixer::TRACK,
1836 AudioMixer::FORMAT, (void *)track->format());
1837 mAudioMixer->setParameter(
1838 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001839 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840 mAudioMixer->setParameter(
1841 AudioMixer::RESAMPLE,
1842 AudioMixer::SAMPLE_RATE,
1843 (void *)(cblk->sampleRate));
1844 mAudioMixer->setParameter(
1845 AudioMixer::TRACK,
1846 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1847 mAudioMixer->setParameter(
1848 AudioMixer::TRACK,
1849 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
1850
1851 // reset retry count
1852 track->mRetryCount = kMaxTrackRetries;
1853 mixerStatus = MIXER_TRACKS_READY;
1854 } else {
1855 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
1856 if (track->isStopped()) {
1857 track->reset();
1858 }
1859 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1860 // We have consumed all the buffers of this track.
1861 // Remove it from the list of active tracks.
1862 tracksToRemove->add(track);
1863 } else {
1864 // No buffers for this track. Give it a few chances to
1865 // fill a buffer, then remove it from active list.
1866 if (--(track->mRetryCount) <= 0) {
1867 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
1868 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07001869 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07001870 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 } else if (mixerStatus != MIXER_TRACKS_READY) {
1872 mixerStatus = MIXER_TRACKS_ENABLED;
1873 }
1874 }
1875 mAudioMixer->disable(AudioMixer::MIXING);
1876 }
1877 }
1878
1879 // remove all the tracks that need to be...
1880 count = tracksToRemove->size();
1881 if (UNLIKELY(count)) {
1882 for (size_t i=0 ; i<count ; i++) {
1883 const sp<Track>& track = tracksToRemove->itemAt(i);
1884 mActiveTracks.remove(track);
1885 if (track->mainBuffer() != mMixBuffer) {
1886 chain = getEffectChain_l(track->sessionId());
1887 if (chain != 0) {
1888 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001889 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890 }
1891 }
1892 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07001893 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 }
1895 }
1896 }
1897
1898 // mix buffer must be cleared if all tracks are connected to an
1899 // effect chain as in this case the mixer will not write to
1900 // mix buffer and track effects will accumulate into it
1901 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1902 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1903 }
1904
1905 return mixerStatus;
1906}
1907
1908void AudioFlinger::MixerThread::invalidateTracks(int streamType)
1909{
Eric Laurentde070132010-07-13 04:45:46 -07001910 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1911 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001913
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 size_t size = mTracks.size();
1915 for (size_t i = 0; i < size; i++) {
1916 sp<Track> t = mTracks[i];
1917 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07001918 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920 }
1921 }
1922}
1923
1924
1925// getTrackName_l() must be called with ThreadBase::mLock held
1926int AudioFlinger::MixerThread::getTrackName_l()
1927{
1928 return mAudioMixer->getTrackName();
1929}
1930
1931// deleteTrackName_l() must be called with ThreadBase::mLock held
1932void AudioFlinger::MixerThread::deleteTrackName_l(int name)
1933{
1934 LOGV("remove track (%d) and delete from mixer", name);
1935 mAudioMixer->deleteTrackName(name);
1936}
1937
1938// checkForNewParameters_l() must be called with ThreadBase::mLock held
1939bool AudioFlinger::MixerThread::checkForNewParameters_l()
1940{
1941 bool reconfig = false;
1942
1943 while (!mNewParameters.isEmpty()) {
1944 status_t status = NO_ERROR;
1945 String8 keyValuePair = mNewParameters[0];
1946 AudioParameter param = AudioParameter(keyValuePair);
1947 int value;
1948
1949 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1950 reconfig = true;
1951 }
1952 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001953 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 status = BAD_VALUE;
1955 } else {
1956 reconfig = true;
1957 }
1958 }
1959 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001960 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 status = BAD_VALUE;
1962 } else {
1963 reconfig = true;
1964 }
1965 }
1966 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1967 // do not accept frame count changes if tracks are open as the track buffer
1968 // size depends on frame count and correct behavior would not be garantied
1969 // if frame count is changed after track creation
1970 if (!mTracks.isEmpty()) {
1971 status = INVALID_OPERATION;
1972 } else {
1973 reconfig = true;
1974 }
1975 }
1976 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001977 // when changing the audio output device, call addBatteryData to notify
1978 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07001979 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001980 uint32_t params = 0;
1981 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07001982 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001983 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1984 }
1985
1986 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07001987 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08001988 // check if any other device (except speaker) is on
1989 if (value & deviceWithoutSpeaker ) {
1990 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1991 }
1992
1993 if (params != 0) {
1994 addBatteryData(params);
1995 }
1996 }
1997
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 // forward device change to effects that have requested to be
1999 // aware of attached audio device.
2000 mDevice = (uint32_t)value;
2001 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002002 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 }
2004 }
2005
2006 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002007 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002008 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002010 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 mStandby = true;
2012 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002013 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002014 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 }
2016 if (status == NO_ERROR && reconfig) {
2017 delete mAudioMixer;
2018 readOutputParameters();
2019 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2020 for (size_t i = 0; i < mTracks.size() ; i++) {
2021 int name = getTrackName_l();
2022 if (name < 0) break;
2023 mTracks[i]->mName = name;
2024 // limit track sample rate to 2 x new output sample rate
2025 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2026 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2027 }
2028 }
2029 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2030 }
2031 }
2032
2033 mNewParameters.removeAt(0);
2034
2035 mParamStatus = status;
2036 mParamCond.signal();
2037 mWaitWorkCV.wait(mLock);
2038 }
2039 return reconfig;
2040}
2041
2042status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2043{
2044 const size_t SIZE = 256;
2045 char buffer[SIZE];
2046 String8 result;
2047
2048 PlaybackThread::dumpInternals(fd, args);
2049
2050 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2051 result.append(buffer);
2052 write(fd, result.string(), result.size());
2053 return NO_ERROR;
2054}
2055
2056uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2057{
Dima Zavin799a70e2011-04-18 16:57:27 -07002058 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059}
2060
2061uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2062{
Eric Laurent60e18242010-07-29 06:50:24 -07002063 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064}
2065
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002066uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2067{
2068 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2069}
2070
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002072AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 : PlaybackThread(audioFlinger, output, id, device)
2074{
2075 mType = PlaybackThread::DIRECT;
2076}
2077
2078AudioFlinger::DirectOutputThread::~DirectOutputThread()
2079{
2080}
2081
2082
2083static inline int16_t clamp16(int32_t sample)
2084{
2085 if ((sample>>15) ^ (sample>>31))
2086 sample = 0x7FFF ^ (sample>>31);
2087 return sample;
2088}
2089
2090static inline
2091int32_t mul(int16_t in, int16_t v)
2092{
2093#if defined(__arm__) && !defined(__thumb__)
2094 int32_t out;
2095 asm( "smulbb %[out], %[in], %[v] \n"
2096 : [out]"=r"(out)
2097 : [in]"%r"(in), [v]"r"(v)
2098 : );
2099 return out;
2100#else
2101 return in * int32_t(v);
2102#endif
2103}
2104
2105void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2106{
2107 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002108 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 return;
2110 }
2111
2112 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002113 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 size_t count = mFrameCount * mChannelCount;
2115 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2116 int16_t *dst = mMixBuffer + count-1;
2117 while(count--) {
2118 *dst-- = (int16_t)(*src--^0x80) << 8;
2119 }
2120 }
2121
2122 size_t frameCount = mFrameCount;
2123 int16_t *out = mMixBuffer;
2124 if (ramp) {
2125 if (mChannelCount == 1) {
2126 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2127 int32_t vlInc = d / (int32_t)frameCount;
2128 int32_t vl = ((int32_t)mLeftVolShort << 16);
2129 do {
2130 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2131 out++;
2132 vl += vlInc;
2133 } while (--frameCount);
2134
2135 } else {
2136 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2137 int32_t vlInc = d / (int32_t)frameCount;
2138 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2139 int32_t vrInc = d / (int32_t)frameCount;
2140 int32_t vl = ((int32_t)mLeftVolShort << 16);
2141 int32_t vr = ((int32_t)mRightVolShort << 16);
2142 do {
2143 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2144 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2145 out += 2;
2146 vl += vlInc;
2147 vr += vrInc;
2148 } while (--frameCount);
2149 }
2150 } else {
2151 if (mChannelCount == 1) {
2152 do {
2153 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2154 out++;
2155 } while (--frameCount);
2156 } else {
2157 do {
2158 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2159 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2160 out += 2;
2161 } while (--frameCount);
2162 }
2163 }
2164
2165 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002166 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 size_t count = mFrameCount * mChannelCount;
2168 int16_t *src = mMixBuffer;
2169 uint8_t *dst = (uint8_t *)mMixBuffer;
2170 while(count--) {
2171 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2172 }
2173 }
2174
2175 mLeftVolShort = leftVol;
2176 mRightVolShort = rightVol;
2177}
2178
2179bool AudioFlinger::DirectOutputThread::threadLoop()
2180{
2181 uint32_t mixerStatus = MIXER_IDLE;
2182 sp<Track> trackToRemove;
2183 sp<Track> activeTrack;
2184 nsecs_t standbyTime = systemTime();
2185 int8_t *curBuf;
2186 size_t mixBufferSize = mFrameCount*mFrameSize;
2187 uint32_t activeSleepTime = activeSleepTimeUs();
2188 uint32_t idleSleepTime = idleSleepTimeUs();
2189 uint32_t sleepTime = idleSleepTime;
2190 // use shorter standby delay as on normal output to release
2191 // hardware resources as soon as possible
2192 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2193
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 while (!exitPending())
2195 {
2196 bool rampVolume;
2197 uint16_t leftVol;
2198 uint16_t rightVol;
2199 Vector< sp<EffectChain> > effectChains;
2200
2201 processConfigEvents();
2202
2203 mixerStatus = MIXER_IDLE;
2204
2205 { // scope for the mLock
2206
2207 Mutex::Autolock _l(mLock);
2208
2209 if (checkForNewParameters_l()) {
2210 mixBufferSize = mFrameCount*mFrameSize;
2211 activeSleepTime = activeSleepTimeUs();
2212 idleSleepTime = idleSleepTimeUs();
2213 standbyDelay = microseconds(activeSleepTime*2);
2214 }
2215
2216 // put audio hardware into standby after short delay
2217 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2218 mSuspended) {
2219 // wait until we have something to do...
2220 if (!mStandby) {
2221 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002222 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 mStandby = true;
2224 mBytesWritten = 0;
2225 }
2226
2227 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2228 // we're about to wait, flush the binder command buffer
2229 IPCThreadState::self()->flushCommands();
2230
2231 if (exitPending()) break;
2232
2233 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2234 mWaitWorkCV.wait(mLock);
2235 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2236
2237 if (mMasterMute == false) {
2238 char value[PROPERTY_VALUE_MAX];
2239 property_get("ro.audio.silent", value, "0");
2240 if (atoi(value)) {
2241 LOGD("Silence is golden");
2242 setMasterMute(true);
2243 }
2244 }
2245
2246 standbyTime = systemTime() + standbyDelay;
2247 sleepTime = idleSleepTime;
2248 continue;
2249 }
2250 }
2251
2252 effectChains = mEffectChains;
2253
2254 // find out which tracks need to be processed
2255 if (mActiveTracks.size() != 0) {
2256 sp<Track> t = mActiveTracks[0].promote();
2257 if (t == 0) continue;
2258
2259 Track* const track = t.get();
2260 audio_track_cblk_t* cblk = track->cblk();
2261
2262 // The first time a track is added we wait
2263 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002264 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 !track->isPaused() && !track->isTerminated())
2266 {
2267 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2268
2269 if (track->mFillingUpStatus == Track::FS_FILLED) {
2270 track->mFillingUpStatus = Track::FS_ACTIVE;
2271 mLeftVolFloat = mRightVolFloat = 0;
2272 mLeftVolShort = mRightVolShort = 0;
2273 if (track->mState == TrackBase::RESUMING) {
2274 track->mState = TrackBase::ACTIVE;
2275 rampVolume = true;
2276 }
2277 } else if (cblk->server != 0) {
2278 // If the track is stopped before the first frame was mixed,
2279 // do not apply ramp
2280 rampVolume = true;
2281 }
2282 // compute volume for this track
2283 float left, right;
2284 if (track->isMuted() || mMasterMute || track->isPausing() ||
2285 mStreamTypes[track->type()].mute) {
2286 left = right = 0;
2287 if (track->isPausing()) {
2288 track->setPaused();
2289 }
2290 } else {
2291 float typeVolume = mStreamTypes[track->type()].volume;
2292 float v = mMasterVolume * typeVolume;
2293 float v_clamped = v * cblk->volume[0];
2294 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2295 left = v_clamped/MAX_GAIN;
2296 v_clamped = v * cblk->volume[1];
2297 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2298 right = v_clamped/MAX_GAIN;
2299 }
2300
2301 if (left != mLeftVolFloat || right != mRightVolFloat) {
2302 mLeftVolFloat = left;
2303 mRightVolFloat = right;
2304
2305 // If audio HAL implements volume control,
2306 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002307 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308 left = 1.0f;
2309 right = 1.0f;
2310 }
2311
2312 // Convert volumes from float to 8.24
2313 uint32_t vl = (uint32_t)(left * (1 << 24));
2314 uint32_t vr = (uint32_t)(right * (1 << 24));
2315
2316 // Delegate volume control to effect in track effect chain if needed
2317 // only one effect chain can be present on DirectOutputThread, so if
2318 // there is one, the track is connected to it
2319 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002320 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002321 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 rampVolume = false;
2323 }
2324 }
2325
2326 // Convert volumes from 8.24 to 4.12 format
2327 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2328 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2329 leftVol = (uint16_t)v_clamped;
2330 v_clamped = (vr + (1 << 11)) >> 12;
2331 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2332 rightVol = (uint16_t)v_clamped;
2333 } else {
2334 leftVol = mLeftVolShort;
2335 rightVol = mRightVolShort;
2336 rampVolume = false;
2337 }
2338
2339 // reset retry count
2340 track->mRetryCount = kMaxTrackRetriesDirect;
2341 activeTrack = t;
2342 mixerStatus = MIXER_TRACKS_READY;
2343 } else {
2344 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2345 if (track->isStopped()) {
2346 track->reset();
2347 }
2348 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2349 // We have consumed all the buffers of this track.
2350 // Remove it from the list of active tracks.
2351 trackToRemove = track;
2352 } else {
2353 // No buffers for this track. Give it a few chances to
2354 // fill a buffer, then remove it from active list.
2355 if (--(track->mRetryCount) <= 0) {
2356 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2357 trackToRemove = track;
2358 } else {
2359 mixerStatus = MIXER_TRACKS_ENABLED;
2360 }
2361 }
2362 }
2363 }
2364
2365 // remove all the tracks that need to be...
2366 if (UNLIKELY(trackToRemove != 0)) {
2367 mActiveTracks.remove(trackToRemove);
2368 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002369 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2370 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002371 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372 }
2373 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002374 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375 }
2376 }
2377
Eric Laurentde070132010-07-13 04:45:46 -07002378 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 }
2380
2381 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2382 AudioBufferProvider::Buffer buffer;
2383 size_t frameCount = mFrameCount;
2384 curBuf = (int8_t *)mMixBuffer;
2385 // output audio to hardware
2386 while (frameCount) {
2387 buffer.frameCount = frameCount;
2388 activeTrack->getNextBuffer(&buffer);
2389 if (UNLIKELY(buffer.raw == 0)) {
2390 memset(curBuf, 0, frameCount * mFrameSize);
2391 break;
2392 }
2393 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2394 frameCount -= buffer.frameCount;
2395 curBuf += buffer.frameCount * mFrameSize;
2396 activeTrack->releaseBuffer(&buffer);
2397 }
2398 sleepTime = 0;
2399 standbyTime = systemTime() + standbyDelay;
2400 } else {
2401 if (sleepTime == 0) {
2402 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2403 sleepTime = activeSleepTime;
2404 } else {
2405 sleepTime = idleSleepTime;
2406 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002407 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2409 sleepTime = 0;
2410 }
2411 }
2412
2413 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002414 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 }
2416 // sleepTime == 0 means we must write to audio hardware
2417 if (sleepTime == 0) {
2418 if (mixerStatus == MIXER_TRACKS_READY) {
2419 applyVolume(leftVol, rightVol, rampVolume);
2420 }
2421 for (size_t i = 0; i < effectChains.size(); i ++) {
2422 effectChains[i]->process_l();
2423 }
Eric Laurentde070132010-07-13 04:45:46 -07002424 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425
2426 mLastWriteTime = systemTime();
2427 mInWrite = true;
2428 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002429 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2431 mNumWrites++;
2432 mInWrite = false;
2433 mStandby = false;
2434 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002435 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 usleep(sleepTime);
2437 }
2438
2439 // finally let go of removed track, without the lock held
2440 // since we can't guarantee the destructors won't acquire that
2441 // same lock.
2442 trackToRemove.clear();
2443 activeTrack.clear();
2444
2445 // Effect chains will be actually deleted here if they were removed from
2446 // mEffectChains list during mixing or effects processing
2447 effectChains.clear();
2448 }
2449
2450 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002451 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 }
2453
2454 LOGV("DirectOutputThread %p exiting", this);
2455 return false;
2456}
2457
2458// getTrackName_l() must be called with ThreadBase::mLock held
2459int AudioFlinger::DirectOutputThread::getTrackName_l()
2460{
2461 return 0;
2462}
2463
2464// deleteTrackName_l() must be called with ThreadBase::mLock held
2465void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2466{
2467}
2468
2469// checkForNewParameters_l() must be called with ThreadBase::mLock held
2470bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2471{
2472 bool reconfig = false;
2473
2474 while (!mNewParameters.isEmpty()) {
2475 status_t status = NO_ERROR;
2476 String8 keyValuePair = mNewParameters[0];
2477 AudioParameter param = AudioParameter(keyValuePair);
2478 int value;
2479
2480 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2481 // do not accept frame count changes if tracks are open as the track buffer
2482 // size depends on frame count and correct behavior would not be garantied
2483 // if frame count is changed after track creation
2484 if (!mTracks.isEmpty()) {
2485 status = INVALID_OPERATION;
2486 } else {
2487 reconfig = true;
2488 }
2489 }
2490 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002491 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002492 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002494 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 mStandby = true;
2496 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002497 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002498 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 }
2500 if (status == NO_ERROR && reconfig) {
2501 readOutputParameters();
2502 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2503 }
2504 }
2505
2506 mNewParameters.removeAt(0);
2507
2508 mParamStatus = status;
2509 mParamCond.signal();
2510 mWaitWorkCV.wait(mLock);
2511 }
2512 return reconfig;
2513}
2514
2515uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2516{
2517 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002518 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002519 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 } else {
2521 time = 10000;
2522 }
2523 return time;
2524}
2525
2526uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2527{
2528 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002529 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002530 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 } else {
2532 time = 10000;
2533 }
2534 return time;
2535}
2536
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002537uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2538{
2539 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002540 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002541 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2542 } else {
2543 time = 10000;
2544 }
2545 return time;
2546}
2547
2548
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549// ----------------------------------------------------------------------------
2550
2551AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2552 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2553{
2554 mType = PlaybackThread::DUPLICATING;
2555 addOutputTrack(mainThread);
2556}
2557
2558AudioFlinger::DuplicatingThread::~DuplicatingThread()
2559{
2560 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2561 mOutputTracks[i]->destroy();
2562 }
2563 mOutputTracks.clear();
2564}
2565
2566bool AudioFlinger::DuplicatingThread::threadLoop()
2567{
2568 Vector< sp<Track> > tracksToRemove;
2569 uint32_t mixerStatus = MIXER_IDLE;
2570 nsecs_t standbyTime = systemTime();
2571 size_t mixBufferSize = mFrameCount*mFrameSize;
2572 SortedVector< sp<OutputTrack> > outputTracks;
2573 uint32_t writeFrames = 0;
2574 uint32_t activeSleepTime = activeSleepTimeUs();
2575 uint32_t idleSleepTime = idleSleepTimeUs();
2576 uint32_t sleepTime = idleSleepTime;
2577 Vector< sp<EffectChain> > effectChains;
2578
2579 while (!exitPending())
2580 {
2581 processConfigEvents();
2582
2583 mixerStatus = MIXER_IDLE;
2584 { // scope for the mLock
2585
2586 Mutex::Autolock _l(mLock);
2587
2588 if (checkForNewParameters_l()) {
2589 mixBufferSize = mFrameCount*mFrameSize;
2590 updateWaitTime();
2591 activeSleepTime = activeSleepTimeUs();
2592 idleSleepTime = idleSleepTimeUs();
2593 }
2594
2595 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2596
2597 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2598 outputTracks.add(mOutputTracks[i]);
2599 }
2600
2601 // put audio hardware into standby after short delay
2602 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2603 mSuspended) {
2604 if (!mStandby) {
2605 for (size_t i = 0; i < outputTracks.size(); i++) {
2606 outputTracks[i]->stop();
2607 }
2608 mStandby = true;
2609 mBytesWritten = 0;
2610 }
2611
2612 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2613 // we're about to wait, flush the binder command buffer
2614 IPCThreadState::self()->flushCommands();
2615 outputTracks.clear();
2616
2617 if (exitPending()) break;
2618
2619 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2620 mWaitWorkCV.wait(mLock);
2621 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2622 if (mMasterMute == false) {
2623 char value[PROPERTY_VALUE_MAX];
2624 property_get("ro.audio.silent", value, "0");
2625 if (atoi(value)) {
2626 LOGD("Silence is golden");
2627 setMasterMute(true);
2628 }
2629 }
2630
2631 standbyTime = systemTime() + kStandbyTimeInNsecs;
2632 sleepTime = idleSleepTime;
2633 continue;
2634 }
2635 }
2636
2637 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2638
2639 // prevent any changes in effect chain list and in each effect chain
2640 // during mixing and effect process as the audio buffers could be deleted
2641 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002642 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002643 }
2644
2645 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2646 // mix buffers...
2647 if (outputsReady(outputTracks)) {
2648 mAudioMixer->process();
2649 } else {
2650 memset(mMixBuffer, 0, mixBufferSize);
2651 }
2652 sleepTime = 0;
2653 writeFrames = mFrameCount;
2654 } else {
2655 if (sleepTime == 0) {
2656 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2657 sleepTime = activeSleepTime;
2658 } else {
2659 sleepTime = idleSleepTime;
2660 }
2661 } else if (mBytesWritten != 0) {
2662 // flush remaining overflow buffers in output tracks
2663 for (size_t i = 0; i < outputTracks.size(); i++) {
2664 if (outputTracks[i]->isActive()) {
2665 sleepTime = 0;
2666 writeFrames = 0;
2667 memset(mMixBuffer, 0, mixBufferSize);
2668 break;
2669 }
2670 }
2671 }
2672 }
2673
2674 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002675 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 }
2677 // sleepTime == 0 means we must write to audio hardware
2678 if (sleepTime == 0) {
2679 for (size_t i = 0; i < effectChains.size(); i ++) {
2680 effectChains[i]->process_l();
2681 }
2682 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002683 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684
2685 standbyTime = systemTime() + kStandbyTimeInNsecs;
2686 for (size_t i = 0; i < outputTracks.size(); i++) {
2687 outputTracks[i]->write(mMixBuffer, writeFrames);
2688 }
2689 mStandby = false;
2690 mBytesWritten += mixBufferSize;
2691 } else {
2692 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002693 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002694 usleep(sleepTime);
2695 }
2696
2697 // finally let go of all our tracks, without the lock held
2698 // since we can't guarantee the destructors won't acquire that
2699 // same lock.
2700 tracksToRemove.clear();
2701 outputTracks.clear();
2702
2703 // Effect chains will be actually deleted here if they were removed from
2704 // mEffectChains list during mixing or effects processing
2705 effectChains.clear();
2706 }
2707
2708 return false;
2709}
2710
2711void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2712{
2713 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2714 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2715 this,
2716 mSampleRate,
2717 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002718 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 frameCount);
2720 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002721 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 mOutputTracks.add(outputTrack);
2723 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2724 updateWaitTime();
2725 }
2726}
2727
2728void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2729{
2730 Mutex::Autolock _l(mLock);
2731 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2732 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2733 mOutputTracks[i]->destroy();
2734 mOutputTracks.removeAt(i);
2735 updateWaitTime();
2736 return;
2737 }
2738 }
2739 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2740}
2741
2742void AudioFlinger::DuplicatingThread::updateWaitTime()
2743{
2744 mWaitTimeMs = UINT_MAX;
2745 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2746 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2747 if (strong != NULL) {
2748 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2749 if (waitTimeMs < mWaitTimeMs) {
2750 mWaitTimeMs = waitTimeMs;
2751 }
2752 }
2753 }
2754}
2755
2756
2757bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2758{
2759 for (size_t i = 0; i < outputTracks.size(); i++) {
2760 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2761 if (thread == 0) {
2762 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2763 return false;
2764 }
2765 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2766 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2767 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2768 return false;
2769 }
2770 }
2771 return true;
2772}
2773
2774uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2775{
2776 return (mWaitTimeMs * 1000) / 2;
2777}
2778
2779// ----------------------------------------------------------------------------
2780
2781// TrackBase constructor must be called with AudioFlinger::mLock held
2782AudioFlinger::ThreadBase::TrackBase::TrackBase(
2783 const wp<ThreadBase>& thread,
2784 const sp<Client>& client,
2785 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002786 uint32_t format,
2787 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 int frameCount,
2789 uint32_t flags,
2790 const sp<IMemory>& sharedBuffer,
2791 int sessionId)
2792 : RefBase(),
2793 mThread(thread),
2794 mClient(client),
2795 mCblk(0),
2796 mFrameCount(0),
2797 mState(IDLE),
2798 mClientTid(-1),
2799 mFormat(format),
2800 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2801 mSessionId(sessionId)
2802{
2803 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2804
2805 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
2806 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002807 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2809 if (sharedBuffer == 0) {
2810 size += bufferSize;
2811 }
2812
2813 if (client != NULL) {
2814 mCblkMemory = client->heap()->allocate(size);
2815 if (mCblkMemory != 0) {
2816 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2817 if (mCblk) { // construct the shared structure in-place.
2818 new(mCblk) audio_track_cblk_t();
2819 // clear all buffers
2820 mCblk->frameCount = frameCount;
2821 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002822 mChannelCount = channelCount;
2823 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 if (sharedBuffer == 0) {
2825 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2826 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2827 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002828 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 mCblk->flags = CBLK_UNDERRUN_ON;
2830 } else {
2831 mBuffer = sharedBuffer->pointer();
2832 }
2833 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2834 }
2835 } else {
2836 LOGE("not enough memory for AudioTrack size=%u", size);
2837 client->heap()->dump("AudioTrack");
2838 return;
2839 }
2840 } else {
2841 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2842 if (mCblk) { // construct the shared structure in-place.
2843 new(mCblk) audio_track_cblk_t();
2844 // clear all buffers
2845 mCblk->frameCount = frameCount;
2846 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002847 mChannelCount = channelCount;
2848 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2850 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2851 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002852 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853 mCblk->flags = CBLK_UNDERRUN_ON;
2854 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2855 }
2856 }
2857}
2858
2859AudioFlinger::ThreadBase::TrackBase::~TrackBase()
2860{
2861 if (mCblk) {
2862 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2863 if (mClient == NULL) {
2864 delete mCblk;
2865 }
2866 }
2867 mCblkMemory.clear(); // and free the shared memory
2868 if (mClient != NULL) {
2869 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2870 mClient.clear();
2871 }
2872}
2873
2874void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2875{
2876 buffer->raw = 0;
2877 mFrameCount = buffer->frameCount;
2878 step();
2879 buffer->frameCount = 0;
2880}
2881
2882bool AudioFlinger::ThreadBase::TrackBase::step() {
2883 bool result;
2884 audio_track_cblk_t* cblk = this->cblk();
2885
2886 result = cblk->stepServer(mFrameCount);
2887 if (!result) {
2888 LOGV("stepServer failed acquiring cblk mutex");
2889 mFlags |= STEPSERVER_FAILED;
2890 }
2891 return result;
2892}
2893
2894void AudioFlinger::ThreadBase::TrackBase::reset() {
2895 audio_track_cblk_t* cblk = this->cblk();
2896
2897 cblk->user = 0;
2898 cblk->server = 0;
2899 cblk->userBase = 0;
2900 cblk->serverBase = 0;
2901 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
2902 LOGV("TrackBase::reset");
2903}
2904
2905sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
2906{
2907 return mCblkMemory;
2908}
2909
2910int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
2911 return (int)mCblk->sampleRate;
2912}
2913
2914int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002915 return (const int)mChannelCount;
2916}
2917
2918uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
2919 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920}
2921
2922void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
2923 audio_track_cblk_t* cblk = this->cblk();
2924 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2925 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
2926
2927 // Check validity of returned pointer in case the track control block would have been corrupted.
2928 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2929 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
2930 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002931 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002933 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 return 0;
2935 }
2936
2937 return bufferStart;
2938}
2939
2940// ----------------------------------------------------------------------------
2941
2942// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2943AudioFlinger::PlaybackThread::Track::Track(
2944 const wp<ThreadBase>& thread,
2945 const sp<Client>& client,
2946 int streamType,
2947 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002948 uint32_t format,
2949 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950 int frameCount,
2951 const sp<IMemory>& sharedBuffer,
2952 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002953 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07002954 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2955 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956{
2957 if (mCblk != NULL) {
2958 sp<ThreadBase> baseThread = thread.promote();
2959 if (baseThread != 0) {
2960 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2961 mName = playbackThread->getTrackName_l();
2962 mMainBuffer = playbackThread->mixBuffer();
2963 }
2964 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2965 if (mName < 0) {
2966 LOGE("no more track names available");
2967 }
2968 mVolume[0] = 1.0f;
2969 mVolume[1] = 1.0f;
2970 mStreamType = streamType;
2971 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2972 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent671a6362011-06-16 21:30:45 -07002973 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * audio_bytes_per_sample(format) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 }
2975}
2976
2977AudioFlinger::PlaybackThread::Track::~Track()
2978{
2979 LOGV("PlaybackThread::Track destructor");
2980 sp<ThreadBase> thread = mThread.promote();
2981 if (thread != 0) {
2982 Mutex::Autolock _l(thread->mLock);
2983 mState = TERMINATED;
2984 }
2985}
2986
2987void AudioFlinger::PlaybackThread::Track::destroy()
2988{
2989 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2990 // by removing it from mTracks vector, so there is a risk that this Tracks's
2991 // desctructor is called. As the destructor needs to lock mLock,
2992 // we must acquire a strong reference on this Track before locking mLock
2993 // here so that the destructor is called only when exiting this function.
2994 // On the other hand, as long as Track::destroy() is only called by
2995 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2996 // this Track with its member mTrack.
2997 sp<Track> keep(this);
2998 { // scope for mLock
2999 sp<ThreadBase> thread = mThread.promote();
3000 if (thread != 0) {
3001 if (!isOutputTrack()) {
3002 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003003 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003004 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003005 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003006
3007 // to track the speaker usage
3008 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 }
3010 AudioSystem::releaseOutput(thread->id());
3011 }
3012 Mutex::Autolock _l(thread->mLock);
3013 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3014 playbackThread->destroyTrack_l(this);
3015 }
3016 }
3017}
3018
3019void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3020{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003021 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",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 mName - AudioMixer::TRACK0,
3023 (mClient == NULL) ? getpid() : mClient->pid(),
3024 mStreamType,
3025 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003026 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 mSessionId,
3028 mFrameCount,
3029 mState,
3030 mMute,
3031 mFillingUpStatus,
3032 mCblk->sampleRate,
3033 mCblk->volume[0],
3034 mCblk->volume[1],
3035 mCblk->server,
3036 mCblk->user,
3037 (int)mMainBuffer,
3038 (int)mAuxBuffer);
3039}
3040
3041status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3042{
3043 audio_track_cblk_t* cblk = this->cblk();
3044 uint32_t framesReady;
3045 uint32_t framesReq = buffer->frameCount;
3046
3047 // Check if last stepServer failed, try to step now
3048 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3049 if (!step()) goto getNextBuffer_exit;
3050 LOGV("stepServer recovered");
3051 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3052 }
3053
3054 framesReady = cblk->framesReady();
3055
3056 if (LIKELY(framesReady)) {
3057 uint32_t s = cblk->server;
3058 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3059
3060 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3061 if (framesReq > framesReady) {
3062 framesReq = framesReady;
3063 }
3064 if (s + framesReq > bufferEnd) {
3065 framesReq = bufferEnd - s;
3066 }
3067
3068 buffer->raw = getBuffer(s, framesReq);
3069 if (buffer->raw == 0) goto getNextBuffer_exit;
3070
3071 buffer->frameCount = framesReq;
3072 return NO_ERROR;
3073 }
3074
3075getNextBuffer_exit:
3076 buffer->raw = 0;
3077 buffer->frameCount = 0;
3078 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3079 return NOT_ENOUGH_DATA;
3080}
3081
3082bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003083 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084
3085 if (mCblk->framesReady() >= mCblk->frameCount ||
3086 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3087 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003088 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 return true;
3090 }
3091 return false;
3092}
3093
3094status_t AudioFlinger::PlaybackThread::Track::start()
3095{
3096 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003097 LOGV("start(%d), calling thread %d session %d",
3098 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 sp<ThreadBase> thread = mThread.promote();
3100 if (thread != 0) {
3101 Mutex::Autolock _l(thread->mLock);
3102 int state = mState;
3103 // here the track could be either new, or restarted
3104 // in both cases "unstop" the track
3105 if (mState == PAUSED) {
3106 mState = TrackBase::RESUMING;
3107 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3108 } else {
3109 mState = TrackBase::ACTIVE;
3110 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3111 }
3112
3113 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3114 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003115 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003116 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003117 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003119
3120 // to track the speaker usage
3121 if (status == NO_ERROR) {
3122 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124 }
3125 if (status == NO_ERROR) {
3126 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3127 playbackThread->addTrack_l(this);
3128 } else {
3129 mState = state;
3130 }
3131 } else {
3132 status = BAD_VALUE;
3133 }
3134 return status;
3135}
3136
3137void AudioFlinger::PlaybackThread::Track::stop()
3138{
3139 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3140 sp<ThreadBase> thread = mThread.promote();
3141 if (thread != 0) {
3142 Mutex::Autolock _l(thread->mLock);
3143 int state = mState;
3144 if (mState > STOPPED) {
3145 mState = STOPPED;
3146 // If the track is not active (PAUSED and buffers full), flush buffers
3147 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3148 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3149 reset();
3150 }
3151 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3152 }
3153 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3154 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003155 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003156 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003157 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003159
3160 // to track the speaker usage
3161 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 }
3163 }
3164}
3165
3166void AudioFlinger::PlaybackThread::Track::pause()
3167{
3168 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3169 sp<ThreadBase> thread = mThread.promote();
3170 if (thread != 0) {
3171 Mutex::Autolock _l(thread->mLock);
3172 if (mState == ACTIVE || mState == RESUMING) {
3173 mState = PAUSING;
3174 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3175 if (!isOutputTrack()) {
3176 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003177 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003178 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003179 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003181
3182 // to track the speaker usage
3183 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 }
3185 }
3186 }
3187}
3188
3189void AudioFlinger::PlaybackThread::Track::flush()
3190{
3191 LOGV("flush(%d)", mName);
3192 sp<ThreadBase> thread = mThread.promote();
3193 if (thread != 0) {
3194 Mutex::Autolock _l(thread->mLock);
3195 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3196 return;
3197 }
3198 // No point remaining in PAUSED state after a flush => go to
3199 // STOPPED state
3200 mState = STOPPED;
3201
Eric Laurent38ccae22011-03-28 18:37:07 -07003202 // do not reset the track if it is still in the process of being stopped or paused.
3203 // this will be done by prepareTracks_l() when the track is stopped.
3204 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3205 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3206 reset();
3207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 }
3209}
3210
3211void AudioFlinger::PlaybackThread::Track::reset()
3212{
3213 // Do not reset twice to avoid discarding data written just after a flush and before
3214 // the audioflinger thread detects the track is stopped.
3215 if (!mResetDone) {
3216 TrackBase::reset();
3217 // Force underrun condition to avoid false underrun callback until first data is
3218 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003219 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3220 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003221 mFillingUpStatus = FS_FILLING;
3222 mResetDone = true;
3223 }
3224}
3225
3226void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3227{
3228 mMute = muted;
3229}
3230
3231void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3232{
3233 mVolume[0] = left;
3234 mVolume[1] = right;
3235}
3236
3237status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3238{
3239 status_t status = DEAD_OBJECT;
3240 sp<ThreadBase> thread = mThread.promote();
3241 if (thread != 0) {
3242 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3243 status = playbackThread->attachAuxEffect(this, EffectId);
3244 }
3245 return status;
3246}
3247
3248void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3249{
3250 mAuxEffectId = EffectId;
3251 mAuxBuffer = buffer;
3252}
3253
3254// ----------------------------------------------------------------------------
3255
3256// RecordTrack constructor must be called with AudioFlinger::mLock held
3257AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3258 const wp<ThreadBase>& thread,
3259 const sp<Client>& client,
3260 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003261 uint32_t format,
3262 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 int frameCount,
3264 uint32_t flags,
3265 int sessionId)
3266 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003267 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 mOverflow(false)
3269{
3270 if (mCblk != NULL) {
3271 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003272 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003273 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003274 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003275 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 } else {
3277 mCblk->frameSize = sizeof(int8_t);
3278 }
3279 }
3280}
3281
3282AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3283{
3284 sp<ThreadBase> thread = mThread.promote();
3285 if (thread != 0) {
3286 AudioSystem::releaseInput(thread->id());
3287 }
3288}
3289
3290status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3291{
3292 audio_track_cblk_t* cblk = this->cblk();
3293 uint32_t framesAvail;
3294 uint32_t framesReq = buffer->frameCount;
3295
3296 // Check if last stepServer failed, try to step now
3297 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3298 if (!step()) goto getNextBuffer_exit;
3299 LOGV("stepServer recovered");
3300 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3301 }
3302
3303 framesAvail = cblk->framesAvailable_l();
3304
3305 if (LIKELY(framesAvail)) {
3306 uint32_t s = cblk->server;
3307 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3308
3309 if (framesReq > framesAvail) {
3310 framesReq = framesAvail;
3311 }
3312 if (s + framesReq > bufferEnd) {
3313 framesReq = bufferEnd - s;
3314 }
3315
3316 buffer->raw = getBuffer(s, framesReq);
3317 if (buffer->raw == 0) goto getNextBuffer_exit;
3318
3319 buffer->frameCount = framesReq;
3320 return NO_ERROR;
3321 }
3322
3323getNextBuffer_exit:
3324 buffer->raw = 0;
3325 buffer->frameCount = 0;
3326 return NOT_ENOUGH_DATA;
3327}
3328
3329status_t AudioFlinger::RecordThread::RecordTrack::start()
3330{
3331 sp<ThreadBase> thread = mThread.promote();
3332 if (thread != 0) {
3333 RecordThread *recordThread = (RecordThread *)thread.get();
3334 return recordThread->start(this);
3335 } else {
3336 return BAD_VALUE;
3337 }
3338}
3339
3340void AudioFlinger::RecordThread::RecordTrack::stop()
3341{
3342 sp<ThreadBase> thread = mThread.promote();
3343 if (thread != 0) {
3344 RecordThread *recordThread = (RecordThread *)thread.get();
3345 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003346 TrackBase::reset();
3347 // Force overerrun condition to avoid false overrun callback until first data is
3348 // read from buffer
3349 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 }
3351}
3352
3353void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3354{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003355 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 (mClient == NULL) ? getpid() : mClient->pid(),
3357 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003358 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 mSessionId,
3360 mFrameCount,
3361 mState,
3362 mCblk->sampleRate,
3363 mCblk->server,
3364 mCblk->user);
3365}
3366
3367
3368// ----------------------------------------------------------------------------
3369
3370AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3371 const wp<ThreadBase>& thread,
3372 DuplicatingThread *sourceThread,
3373 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003374 uint32_t format,
3375 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003377 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 mActive(false), mSourceThread(sourceThread)
3379{
3380
3381 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3382 if (mCblk != NULL) {
3383 mCblk->flags |= CBLK_DIRECTION_OUT;
3384 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3385 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3386 mOutBuffer.frameCount = 0;
3387 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003388 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3389 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3390 mCblk, mBuffer, mCblk->buffers,
3391 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 } else {
3393 LOGW("Error creating output track on thread %p", playbackThread);
3394 }
3395}
3396
3397AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3398{
3399 clearBufferQueue();
3400}
3401
3402status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3403{
3404 status_t status = Track::start();
3405 if (status != NO_ERROR) {
3406 return status;
3407 }
3408
3409 mActive = true;
3410 mRetryCount = 127;
3411 return status;
3412}
3413
3414void AudioFlinger::PlaybackThread::OutputTrack::stop()
3415{
3416 Track::stop();
3417 clearBufferQueue();
3418 mOutBuffer.frameCount = 0;
3419 mActive = false;
3420}
3421
3422bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3423{
3424 Buffer *pInBuffer;
3425 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003426 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 bool outputBufferFull = false;
3428 inBuffer.frameCount = frames;
3429 inBuffer.i16 = data;
3430
3431 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3432
3433 if (!mActive && frames != 0) {
3434 start();
3435 sp<ThreadBase> thread = mThread.promote();
3436 if (thread != 0) {
3437 MixerThread *mixerThread = (MixerThread *)thread.get();
3438 if (mCblk->frameCount > frames){
3439 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3440 uint32_t startFrames = (mCblk->frameCount - frames);
3441 pInBuffer = new Buffer;
3442 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3443 pInBuffer->frameCount = startFrames;
3444 pInBuffer->i16 = pInBuffer->mBuffer;
3445 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3446 mBufferQueue.add(pInBuffer);
3447 } else {
3448 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3449 }
3450 }
3451 }
3452 }
3453
3454 while (waitTimeLeftMs) {
3455 // First write pending buffers, then new data
3456 if (mBufferQueue.size()) {
3457 pInBuffer = mBufferQueue.itemAt(0);
3458 } else {
3459 pInBuffer = &inBuffer;
3460 }
3461
3462 if (pInBuffer->frameCount == 0) {
3463 break;
3464 }
3465
3466 if (mOutBuffer.frameCount == 0) {
3467 mOutBuffer.frameCount = pInBuffer->frameCount;
3468 nsecs_t startTime = systemTime();
3469 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3470 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3471 outputBufferFull = true;
3472 break;
3473 }
3474 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3475 if (waitTimeLeftMs >= waitTimeMs) {
3476 waitTimeLeftMs -= waitTimeMs;
3477 } else {
3478 waitTimeLeftMs = 0;
3479 }
3480 }
3481
3482 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3483 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3484 mCblk->stepUser(outFrames);
3485 pInBuffer->frameCount -= outFrames;
3486 pInBuffer->i16 += outFrames * channelCount;
3487 mOutBuffer.frameCount -= outFrames;
3488 mOutBuffer.i16 += outFrames * channelCount;
3489
3490 if (pInBuffer->frameCount == 0) {
3491 if (mBufferQueue.size()) {
3492 mBufferQueue.removeAt(0);
3493 delete [] pInBuffer->mBuffer;
3494 delete pInBuffer;
3495 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3496 } else {
3497 break;
3498 }
3499 }
3500 }
3501
3502 // If we could not write all frames, allocate a buffer and queue it for next time.
3503 if (inBuffer.frameCount) {
3504 sp<ThreadBase> thread = mThread.promote();
3505 if (thread != 0 && !thread->standby()) {
3506 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3507 pInBuffer = new Buffer;
3508 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3509 pInBuffer->frameCount = inBuffer.frameCount;
3510 pInBuffer->i16 = pInBuffer->mBuffer;
3511 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3512 mBufferQueue.add(pInBuffer);
3513 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3514 } else {
3515 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3516 }
3517 }
3518 }
3519
3520 // Calling write() with a 0 length buffer, means that no more data will be written:
3521 // If no more buffers are pending, fill output track buffer to make sure it is started
3522 // by output mixer.
3523 if (frames == 0 && mBufferQueue.size() == 0) {
3524 if (mCblk->user < mCblk->frameCount) {
3525 frames = mCblk->frameCount - mCblk->user;
3526 pInBuffer = new Buffer;
3527 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3528 pInBuffer->frameCount = frames;
3529 pInBuffer->i16 = pInBuffer->mBuffer;
3530 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3531 mBufferQueue.add(pInBuffer);
3532 } else if (mActive) {
3533 stop();
3534 }
3535 }
3536
3537 return outputBufferFull;
3538}
3539
3540status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3541{
3542 int active;
3543 status_t result;
3544 audio_track_cblk_t* cblk = mCblk;
3545 uint32_t framesReq = buffer->frameCount;
3546
3547// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3548 buffer->frameCount = 0;
3549
3550 uint32_t framesAvail = cblk->framesAvailable();
3551
3552
3553 if (framesAvail == 0) {
3554 Mutex::Autolock _l(cblk->lock);
3555 goto start_loop_here;
3556 while (framesAvail == 0) {
3557 active = mActive;
3558 if (UNLIKELY(!active)) {
3559 LOGV("Not active and NO_MORE_BUFFERS");
3560 return AudioTrack::NO_MORE_BUFFERS;
3561 }
3562 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3563 if (result != NO_ERROR) {
3564 return AudioTrack::NO_MORE_BUFFERS;
3565 }
3566 // read the server count again
3567 start_loop_here:
3568 framesAvail = cblk->framesAvailable_l();
3569 }
3570 }
3571
3572// if (framesAvail < framesReq) {
3573// return AudioTrack::NO_MORE_BUFFERS;
3574// }
3575
3576 if (framesReq > framesAvail) {
3577 framesReq = framesAvail;
3578 }
3579
3580 uint32_t u = cblk->user;
3581 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3582
3583 if (u + framesReq > bufferEnd) {
3584 framesReq = bufferEnd - u;
3585 }
3586
3587 buffer->frameCount = framesReq;
3588 buffer->raw = (void *)cblk->buffer(u);
3589 return NO_ERROR;
3590}
3591
3592
3593void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3594{
3595 size_t size = mBufferQueue.size();
3596 Buffer *pBuffer;
3597
3598 for (size_t i = 0; i < size; i++) {
3599 pBuffer = mBufferQueue.itemAt(i);
3600 delete [] pBuffer->mBuffer;
3601 delete pBuffer;
3602 }
3603 mBufferQueue.clear();
3604}
3605
3606// ----------------------------------------------------------------------------
3607
3608AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3609 : RefBase(),
3610 mAudioFlinger(audioFlinger),
3611 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3612 mPid(pid)
3613{
3614 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3615}
3616
3617// Client destructor must be called with AudioFlinger::mLock held
3618AudioFlinger::Client::~Client()
3619{
3620 mAudioFlinger->removeClient_l(mPid);
3621}
3622
3623const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3624{
3625 return mMemoryDealer;
3626}
3627
3628// ----------------------------------------------------------------------------
3629
3630AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3631 const sp<IAudioFlingerClient>& client,
3632 pid_t pid)
3633 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3634{
3635}
3636
3637AudioFlinger::NotificationClient::~NotificationClient()
3638{
3639 mClient.clear();
3640}
3641
3642void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3643{
3644 sp<NotificationClient> keep(this);
3645 {
3646 mAudioFlinger->removeNotificationClient(mPid);
3647 }
3648}
3649
3650// ----------------------------------------------------------------------------
3651
3652AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3653 : BnAudioTrack(),
3654 mTrack(track)
3655{
3656}
3657
3658AudioFlinger::TrackHandle::~TrackHandle() {
3659 // just stop the track on deletion, associated resources
3660 // will be freed from the main thread once all pending buffers have
3661 // been played. Unless it's not in the active track list, in which
3662 // case we free everything now...
3663 mTrack->destroy();
3664}
3665
3666status_t AudioFlinger::TrackHandle::start() {
3667 return mTrack->start();
3668}
3669
3670void AudioFlinger::TrackHandle::stop() {
3671 mTrack->stop();
3672}
3673
3674void AudioFlinger::TrackHandle::flush() {
3675 mTrack->flush();
3676}
3677
3678void AudioFlinger::TrackHandle::mute(bool e) {
3679 mTrack->mute(e);
3680}
3681
3682void AudioFlinger::TrackHandle::pause() {
3683 mTrack->pause();
3684}
3685
3686void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3687 mTrack->setVolume(left, right);
3688}
3689
3690sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3691 return mTrack->getCblk();
3692}
3693
3694status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3695{
3696 return mTrack->attachAuxEffect(EffectId);
3697}
3698
3699status_t AudioFlinger::TrackHandle::onTransact(
3700 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3701{
3702 return BnAudioTrack::onTransact(code, data, reply, flags);
3703}
3704
3705// ----------------------------------------------------------------------------
3706
3707sp<IAudioRecord> AudioFlinger::openRecord(
3708 pid_t pid,
3709 int input,
3710 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003711 uint32_t format,
3712 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 int frameCount,
3714 uint32_t flags,
3715 int *sessionId,
3716 status_t *status)
3717{
3718 sp<RecordThread::RecordTrack> recordTrack;
3719 sp<RecordHandle> recordHandle;
3720 sp<Client> client;
3721 wp<Client> wclient;
3722 status_t lStatus;
3723 RecordThread *thread;
3724 size_t inFrameCount;
3725 int lSessionId;
3726
3727 // check calling permissions
3728 if (!recordingAllowed()) {
3729 lStatus = PERMISSION_DENIED;
3730 goto Exit;
3731 }
3732
3733 // add client to list
3734 { // scope for mLock
3735 Mutex::Autolock _l(mLock);
3736 thread = checkRecordThread_l(input);
3737 if (thread == NULL) {
3738 lStatus = BAD_VALUE;
3739 goto Exit;
3740 }
3741
3742 wclient = mClients.valueFor(pid);
3743 if (wclient != NULL) {
3744 client = wclient.promote();
3745 } else {
3746 client = new Client(this, pid);
3747 mClients.add(pid, client);
3748 }
3749
3750 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07003751 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 lSessionId = *sessionId;
3753 } else {
Eric Laurentf5aafb22010-11-18 08:40:16 -08003754 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755 if (sessionId != NULL) {
3756 *sessionId = lSessionId;
3757 }
3758 }
3759 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
3760 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003761 format, channelMask, frameCount, flags, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762 }
3763 if (recordTrack->getCblk() == NULL) {
3764 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3765 // destructor is called by the TrackBase destructor with mLock held
3766 client.clear();
3767 recordTrack.clear();
3768 lStatus = NO_MEMORY;
3769 goto Exit;
3770 }
3771
3772 // return to handle to client
3773 recordHandle = new RecordHandle(recordTrack);
3774 lStatus = NO_ERROR;
3775
3776Exit:
3777 if (status) {
3778 *status = lStatus;
3779 }
3780 return recordHandle;
3781}
3782
3783// ----------------------------------------------------------------------------
3784
3785AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3786 : BnAudioRecord(),
3787 mRecordTrack(recordTrack)
3788{
3789}
3790
3791AudioFlinger::RecordHandle::~RecordHandle() {
3792 stop();
3793}
3794
3795status_t AudioFlinger::RecordHandle::start() {
3796 LOGV("RecordHandle::start()");
3797 return mRecordTrack->start();
3798}
3799
3800void AudioFlinger::RecordHandle::stop() {
3801 LOGV("RecordHandle::stop()");
3802 mRecordTrack->stop();
3803}
3804
3805sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3806 return mRecordTrack->getCblk();
3807}
3808
3809status_t AudioFlinger::RecordHandle::onTransact(
3810 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3811{
3812 return BnAudioRecord::onTransact(code, data, reply, flags);
3813}
3814
3815// ----------------------------------------------------------------------------
3816
Dima Zavin799a70e2011-04-18 16:57:27 -07003817AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818 ThreadBase(audioFlinger, id),
3819 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
3820{
Dima Zavinfce7a472011-04-19 22:30:36 -07003821 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 mReqSampleRate = sampleRate;
3823 readInputParameters();
3824}
3825
3826
3827AudioFlinger::RecordThread::~RecordThread()
3828{
3829 delete[] mRsmpInBuffer;
3830 if (mResampler != 0) {
3831 delete mResampler;
3832 delete[] mRsmpOutBuffer;
3833 }
3834}
3835
3836void AudioFlinger::RecordThread::onFirstRef()
3837{
3838 const size_t SIZE = 256;
3839 char buffer[SIZE];
3840
3841 snprintf(buffer, SIZE, "Record Thread %p", this);
3842
3843 run(buffer, PRIORITY_URGENT_AUDIO);
3844}
3845
3846bool AudioFlinger::RecordThread::threadLoop()
3847{
3848 AudioBufferProvider::Buffer buffer;
3849 sp<RecordTrack> activeTrack;
3850
Eric Laurent44d98482010-09-30 16:12:31 -07003851 nsecs_t lastWarning = 0;
3852
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853 // start recording
3854 while (!exitPending()) {
3855
3856 processConfigEvents();
3857
3858 { // scope for mLock
3859 Mutex::Autolock _l(mLock);
3860 checkForNewParameters_l();
3861 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3862 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003863 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 mStandby = true;
3865 }
3866
3867 if (exitPending()) break;
3868
3869 LOGV("RecordThread: loop stopping");
3870 // go to sleep
3871 mWaitWorkCV.wait(mLock);
3872 LOGV("RecordThread: loop starting");
3873 continue;
3874 }
3875 if (mActiveTrack != 0) {
3876 if (mActiveTrack->mState == TrackBase::PAUSING) {
3877 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003878 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 mStandby = true;
3880 }
3881 mActiveTrack.clear();
3882 mStartStopCond.broadcast();
3883 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3884 if (mReqChannelCount != mActiveTrack->channelCount()) {
3885 mActiveTrack.clear();
3886 mStartStopCond.broadcast();
3887 } else if (mBytesRead != 0) {
3888 // record start succeeds only if first read from audio input
3889 // succeeds
3890 if (mBytesRead > 0) {
3891 mActiveTrack->mState = TrackBase::ACTIVE;
3892 } else {
3893 mActiveTrack.clear();
3894 }
3895 mStartStopCond.broadcast();
3896 }
3897 mStandby = false;
3898 }
3899 }
3900 }
3901
3902 if (mActiveTrack != 0) {
3903 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3904 mActiveTrack->mState != TrackBase::RESUMING) {
3905 usleep(5000);
3906 continue;
3907 }
3908 buffer.frameCount = mFrameCount;
3909 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3910 size_t framesOut = buffer.frameCount;
3911 if (mResampler == 0) {
3912 // no resampling
3913 while (framesOut) {
3914 size_t framesIn = mFrameCount - mRsmpInIndex;
3915 if (framesIn) {
3916 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3917 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3918 if (framesIn > framesOut)
3919 framesIn = framesOut;
3920 mRsmpInIndex += framesIn;
3921 framesOut -= framesIn;
3922 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07003923 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003924 memcpy(dst, src, framesIn * mFrameSize);
3925 } else {
3926 int16_t *src16 = (int16_t *)src;
3927 int16_t *dst16 = (int16_t *)dst;
3928 if (mChannelCount == 1) {
3929 while (framesIn--) {
3930 *dst16++ = *src16;
3931 *dst16++ = *src16++;
3932 }
3933 } else {
3934 while (framesIn--) {
3935 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3936 src16 += 2;
3937 }
3938 }
3939 }
3940 }
3941 if (framesOut && mFrameCount == mRsmpInIndex) {
3942 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07003943 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003944 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 framesOut = 0;
3946 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07003947 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948 mRsmpInIndex = 0;
3949 }
3950 if (mBytesRead < 0) {
3951 LOGE("Error reading audio input");
3952 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3953 // Force input into standby so that it tries to
3954 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07003955 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 usleep(5000);
3957 }
3958 mRsmpInIndex = mFrameCount;
3959 framesOut = 0;
3960 buffer.frameCount = 0;
3961 }
3962 }
3963 }
3964 } else {
3965 // resampling
3966
3967 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3968 // alter output frame count as if we were expecting stereo samples
3969 if (mChannelCount == 1 && mReqChannelCount == 1) {
3970 framesOut >>= 1;
3971 }
3972 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3973 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3974 // are 32 bit aligned which should be always true.
3975 if (mChannelCount == 2 && mReqChannelCount == 1) {
3976 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3977 // the resampler always outputs stereo samples: do post stereo to mono conversion
3978 int16_t *src = (int16_t *)mRsmpOutBuffer;
3979 int16_t *dst = buffer.i16;
3980 while (framesOut--) {
3981 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3982 src += 2;
3983 }
3984 } else {
3985 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3986 }
3987
3988 }
3989 mActiveTrack->releaseBuffer(&buffer);
3990 mActiveTrack->overflow();
3991 }
3992 // client isn't retrieving buffers fast enough
3993 else {
Eric Laurent44d98482010-09-30 16:12:31 -07003994 if (!mActiveTrack->setOverflow()) {
3995 nsecs_t now = systemTime();
3996 if ((now - lastWarning) > kWarningThrottle) {
3997 LOGW("RecordThread: buffer overflow");
3998 lastWarning = now;
3999 }
4000 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 // Release the processor for a while before asking for a new buffer.
4002 // This will give the application more chance to read from the buffer and
4003 // clear the overflow.
4004 usleep(5000);
4005 }
4006 }
4007 }
4008
4009 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004010 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011 }
4012 mActiveTrack.clear();
4013
4014 mStartStopCond.broadcast();
4015
4016 LOGV("RecordThread %p exiting", this);
4017 return false;
4018}
4019
4020status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4021{
4022 LOGV("RecordThread::start");
4023 sp <ThreadBase> strongMe = this;
4024 status_t status = NO_ERROR;
4025 {
4026 AutoMutex lock(&mLock);
4027 if (mActiveTrack != 0) {
4028 if (recordTrack != mActiveTrack.get()) {
4029 status = -EBUSY;
4030 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4031 mActiveTrack->mState = TrackBase::ACTIVE;
4032 }
4033 return status;
4034 }
4035
4036 recordTrack->mState = TrackBase::IDLE;
4037 mActiveTrack = recordTrack;
4038 mLock.unlock();
4039 status_t status = AudioSystem::startInput(mId);
4040 mLock.lock();
4041 if (status != NO_ERROR) {
4042 mActiveTrack.clear();
4043 return status;
4044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045 mRsmpInIndex = mFrameCount;
4046 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004047 if (mResampler != NULL) {
4048 mResampler->reset();
4049 }
4050 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 // signal thread to start
4052 LOGV("Signal record thread");
4053 mWaitWorkCV.signal();
4054 // do not wait for mStartStopCond if exiting
4055 if (mExiting) {
4056 mActiveTrack.clear();
4057 status = INVALID_OPERATION;
4058 goto startError;
4059 }
4060 mStartStopCond.wait(mLock);
4061 if (mActiveTrack == 0) {
4062 LOGV("Record failed to start");
4063 status = BAD_VALUE;
4064 goto startError;
4065 }
4066 LOGV("Record started OK");
4067 return status;
4068 }
4069startError:
4070 AudioSystem::stopInput(mId);
4071 return status;
4072}
4073
4074void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4075 LOGV("RecordThread::stop");
4076 sp <ThreadBase> strongMe = this;
4077 {
4078 AutoMutex lock(&mLock);
4079 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4080 mActiveTrack->mState = TrackBase::PAUSING;
4081 // do not wait for mStartStopCond if exiting
4082 if (mExiting) {
4083 return;
4084 }
4085 mStartStopCond.wait(mLock);
4086 // if we have been restarted, recordTrack == mActiveTrack.get() here
4087 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4088 mLock.unlock();
4089 AudioSystem::stopInput(mId);
4090 mLock.lock();
4091 LOGV("Record stopped OK");
4092 }
4093 }
4094 }
4095}
4096
4097status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4098{
4099 const size_t SIZE = 256;
4100 char buffer[SIZE];
4101 String8 result;
4102 pid_t pid = 0;
4103
4104 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4105 result.append(buffer);
4106
4107 if (mActiveTrack != 0) {
4108 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004109 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 mActiveTrack->dump(buffer, SIZE);
4111 result.append(buffer);
4112
4113 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4114 result.append(buffer);
4115 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4116 result.append(buffer);
4117 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4118 result.append(buffer);
4119 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4120 result.append(buffer);
4121 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4122 result.append(buffer);
4123
4124
4125 } else {
4126 result.append("No record client\n");
4127 }
4128 write(fd, result.string(), result.size());
4129
4130 dumpBase(fd, args);
4131
4132 return NO_ERROR;
4133}
4134
4135status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4136{
4137 size_t framesReq = buffer->frameCount;
4138 size_t framesReady = mFrameCount - mRsmpInIndex;
4139 int channelCount;
4140
4141 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004142 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 if (mBytesRead < 0) {
4144 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4145 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4146 // Force input into standby so that it tries to
4147 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004148 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 usleep(5000);
4150 }
4151 buffer->raw = 0;
4152 buffer->frameCount = 0;
4153 return NOT_ENOUGH_DATA;
4154 }
4155 mRsmpInIndex = 0;
4156 framesReady = mFrameCount;
4157 }
4158
4159 if (framesReq > framesReady) {
4160 framesReq = framesReady;
4161 }
4162
4163 if (mChannelCount == 1 && mReqChannelCount == 2) {
4164 channelCount = 1;
4165 } else {
4166 channelCount = 2;
4167 }
4168 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4169 buffer->frameCount = framesReq;
4170 return NO_ERROR;
4171}
4172
4173void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4174{
4175 mRsmpInIndex += buffer->frameCount;
4176 buffer->frameCount = 0;
4177}
4178
4179bool AudioFlinger::RecordThread::checkForNewParameters_l()
4180{
4181 bool reconfig = false;
4182
4183 while (!mNewParameters.isEmpty()) {
4184 status_t status = NO_ERROR;
4185 String8 keyValuePair = mNewParameters[0];
4186 AudioParameter param = AudioParameter(keyValuePair);
4187 int value;
4188 int reqFormat = mFormat;
4189 int reqSamplingRate = mReqSampleRate;
4190 int reqChannelCount = mReqChannelCount;
4191
4192 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4193 reqSamplingRate = value;
4194 reconfig = true;
4195 }
4196 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4197 reqFormat = value;
4198 reconfig = true;
4199 }
4200 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004201 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 reconfig = true;
4203 }
4204 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4205 // do not accept frame count changes if tracks are open as the track buffer
4206 // size depends on frame count and correct behavior would not be garantied
4207 // if frame count is changed after track creation
4208 if (mActiveTrack != 0) {
4209 status = INVALID_OPERATION;
4210 } else {
4211 reconfig = true;
4212 }
4213 }
4214 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004215 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004217 mInput->stream->common.standby(&mInput->stream->common);
4218 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 }
4220 if (reconfig) {
4221 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004222 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004223 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004224 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4225 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004226 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 status = NO_ERROR;
4228 }
4229 if (status == NO_ERROR) {
4230 readInputParameters();
4231 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4232 }
4233 }
4234 }
4235
4236 mNewParameters.removeAt(0);
4237
4238 mParamStatus = status;
4239 mParamCond.signal();
4240 mWaitWorkCV.wait(mLock);
4241 }
4242 return reconfig;
4243}
4244
4245String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4246{
Dima Zavinfce7a472011-04-19 22:30:36 -07004247 char *s;
4248 String8 out_s8;
4249
Dima Zavin799a70e2011-04-18 16:57:27 -07004250 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004251 out_s8 = String8(s);
4252 free(s);
4253 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254}
4255
4256void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4257 AudioSystem::OutputDescriptor desc;
4258 void *param2 = 0;
4259
4260 switch (event) {
4261 case AudioSystem::INPUT_OPENED:
4262 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004263 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 desc.samplingRate = mSampleRate;
4265 desc.format = mFormat;
4266 desc.frameCount = mFrameCount;
4267 desc.latency = 0;
4268 param2 = &desc;
4269 break;
4270
4271 case AudioSystem::INPUT_CLOSED:
4272 default:
4273 break;
4274 }
4275 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4276}
4277
4278void AudioFlinger::RecordThread::readInputParameters()
4279{
4280 if (mRsmpInBuffer) delete mRsmpInBuffer;
4281 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4282 if (mResampler) delete mResampler;
4283 mResampler = 0;
4284
Dima Zavin799a70e2011-04-18 16:57:27 -07004285 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004286 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4287 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004288 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4289 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4290 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 mFrameCount = mInputBytes / mFrameSize;
4292 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4293
4294 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4295 {
4296 int channelCount;
4297 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4298 // stereo to mono post process as the resampler always outputs stereo.
4299 if (mChannelCount == 1 && mReqChannelCount == 2) {
4300 channelCount = 1;
4301 } else {
4302 channelCount = 2;
4303 }
4304 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4305 mResampler->setSampleRate(mSampleRate);
4306 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4307 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4308
4309 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4310 if (mChannelCount == 1 && mReqChannelCount == 1) {
4311 mFrameCount >>= 1;
4312 }
4313
4314 }
4315 mRsmpInIndex = mFrameCount;
4316}
4317
4318unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4319{
Dima Zavin799a70e2011-04-18 16:57:27 -07004320 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321}
4322
4323// ----------------------------------------------------------------------------
4324
4325int AudioFlinger::openOutput(uint32_t *pDevices,
4326 uint32_t *pSamplingRate,
4327 uint32_t *pFormat,
4328 uint32_t *pChannels,
4329 uint32_t *pLatencyMs,
4330 uint32_t flags)
4331{
4332 status_t status;
4333 PlaybackThread *thread = NULL;
4334 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4335 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4336 uint32_t format = pFormat ? *pFormat : 0;
4337 uint32_t channels = pChannels ? *pChannels : 0;
4338 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004339 audio_stream_out_t *outStream;
4340 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341
4342 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4343 pDevices ? *pDevices : 0,
4344 samplingRate,
4345 format,
4346 channels,
4347 flags);
4348
4349 if (pDevices == NULL || *pDevices == 0) {
4350 return 0;
4351 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004352
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 Mutex::Autolock _l(mLock);
4354
Dima Zavin799a70e2011-04-18 16:57:27 -07004355 outHwDev = findSuitableHwDev_l(*pDevices);
4356 if (outHwDev == NULL)
4357 return 0;
4358
4359 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4360 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004362 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 samplingRate,
4364 format,
4365 channels,
4366 status);
4367
4368 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004369 if (outStream != NULL) {
4370 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurentf5aafb22010-11-18 08:40:16 -08004371 int id = nextUniqueId_l();
Dima Zavin799a70e2011-04-18 16:57:27 -07004372
Dima Zavinfce7a472011-04-19 22:30:36 -07004373 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4374 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4375 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376 thread = new DirectOutputThread(this, output, id, *pDevices);
4377 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4378 } else {
4379 thread = new MixerThread(this, output, id, *pDevices);
4380 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 }
4382 mPlaybackThreads.add(id, thread);
4383
4384 if (pSamplingRate) *pSamplingRate = samplingRate;
4385 if (pFormat) *pFormat = format;
4386 if (pChannels) *pChannels = channels;
4387 if (pLatencyMs) *pLatencyMs = thread->latency();
4388
4389 // notify client processes of the new output creation
4390 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4391 return id;
4392 }
4393
4394 return 0;
4395}
4396
4397int AudioFlinger::openDuplicateOutput(int output1, int output2)
4398{
4399 Mutex::Autolock _l(mLock);
4400 MixerThread *thread1 = checkMixerThread_l(output1);
4401 MixerThread *thread2 = checkMixerThread_l(output2);
4402
4403 if (thread1 == NULL || thread2 == NULL) {
4404 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4405 return 0;
4406 }
4407
Eric Laurentf5aafb22010-11-18 08:40:16 -08004408 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4410 thread->addOutputTrack(thread2);
4411 mPlaybackThreads.add(id, thread);
4412 // notify client processes of the new output creation
4413 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4414 return id;
4415}
4416
4417status_t AudioFlinger::closeOutput(int output)
4418{
4419 // keep strong reference on the playback thread so that
4420 // it is not destroyed while exit() is executed
4421 sp <PlaybackThread> thread;
4422 {
4423 Mutex::Autolock _l(mLock);
4424 thread = checkPlaybackThread_l(output);
4425 if (thread == NULL) {
4426 return BAD_VALUE;
4427 }
4428
4429 LOGV("closeOutput() %d", output);
4430
4431 if (thread->type() == PlaybackThread::MIXER) {
4432 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4433 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4434 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4435 dupThread->removeOutputTrack((MixerThread *)thread.get());
4436 }
4437 }
4438 }
4439 void *param2 = 0;
4440 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4441 mPlaybackThreads.removeItem(output);
4442 }
4443 thread->exit();
4444
4445 if (thread->type() != PlaybackThread::DUPLICATING) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004446 AudioStreamOut *out = thread->getOutput();
4447 out->hwDev->close_output_stream(out->hwDev, out->stream);
4448 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450 return NO_ERROR;
4451}
4452
4453status_t AudioFlinger::suspendOutput(int output)
4454{
4455 Mutex::Autolock _l(mLock);
4456 PlaybackThread *thread = checkPlaybackThread_l(output);
4457
4458 if (thread == NULL) {
4459 return BAD_VALUE;
4460 }
4461
4462 LOGV("suspendOutput() %d", output);
4463 thread->suspend();
4464
4465 return NO_ERROR;
4466}
4467
4468status_t AudioFlinger::restoreOutput(int output)
4469{
4470 Mutex::Autolock _l(mLock);
4471 PlaybackThread *thread = checkPlaybackThread_l(output);
4472
4473 if (thread == NULL) {
4474 return BAD_VALUE;
4475 }
4476
4477 LOGV("restoreOutput() %d", output);
4478
4479 thread->restore();
4480
4481 return NO_ERROR;
4482}
4483
4484int AudioFlinger::openInput(uint32_t *pDevices,
4485 uint32_t *pSamplingRate,
4486 uint32_t *pFormat,
4487 uint32_t *pChannels,
4488 uint32_t acoustics)
4489{
4490 status_t status;
4491 RecordThread *thread = NULL;
4492 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4493 uint32_t format = pFormat ? *pFormat : 0;
4494 uint32_t channels = pChannels ? *pChannels : 0;
4495 uint32_t reqSamplingRate = samplingRate;
4496 uint32_t reqFormat = format;
4497 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004498 audio_stream_in_t *inStream;
4499 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500
4501 if (pDevices == NULL || *pDevices == 0) {
4502 return 0;
4503 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004504
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505 Mutex::Autolock _l(mLock);
4506
Dima Zavin799a70e2011-04-18 16:57:27 -07004507 inHwDev = findSuitableHwDev_l(*pDevices);
4508 if (inHwDev == NULL)
4509 return 0;
4510
4511 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4512 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004513 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004514 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004516 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 samplingRate,
4518 format,
4519 channels,
4520 acoustics,
4521 status);
4522
4523 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4524 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4525 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07004526 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004527 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004529 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07004531 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4532 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004533 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004534 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 }
4536
Dima Zavin799a70e2011-04-18 16:57:27 -07004537 if (inStream != NULL) {
4538 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4539
Eric Laurentf5aafb22010-11-18 08:40:16 -08004540 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541 // Start record thread
4542 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4543 mRecordThreads.add(id, thread);
4544 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4545 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4546 if (pFormat) *pFormat = format;
4547 if (pChannels) *pChannels = reqChannels;
4548
Dima Zavin799a70e2011-04-18 16:57:27 -07004549 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550
4551 // notify client processes of the new input creation
4552 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4553 return id;
4554 }
4555
4556 return 0;
4557}
4558
4559status_t AudioFlinger::closeInput(int input)
4560{
4561 // keep strong reference on the record thread so that
4562 // it is not destroyed while exit() is executed
4563 sp <RecordThread> thread;
4564 {
4565 Mutex::Autolock _l(mLock);
4566 thread = checkRecordThread_l(input);
4567 if (thread == NULL) {
4568 return BAD_VALUE;
4569 }
4570
4571 LOGV("closeInput() %d", input);
4572 void *param2 = 0;
4573 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4574 mRecordThreads.removeItem(input);
4575 }
4576 thread->exit();
4577
Dima Zavin799a70e2011-04-18 16:57:27 -07004578 AudioStreamIn *in = thread->getInput();
4579 in->hwDev->close_input_stream(in->hwDev, in->stream);
4580 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581
4582 return NO_ERROR;
4583}
4584
4585status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4586{
4587 Mutex::Autolock _l(mLock);
4588 MixerThread *dstThread = checkMixerThread_l(output);
4589 if (dstThread == NULL) {
4590 LOGW("setStreamOutput() bad output id %d", output);
4591 return BAD_VALUE;
4592 }
4593
4594 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4595 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4596
4597 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4598 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4599 if (thread != dstThread &&
4600 thread->type() != PlaybackThread::DIRECT) {
4601 MixerThread *srcThread = (MixerThread *)thread;
4602 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 }
Eric Laurentde070132010-07-13 04:45:46 -07004604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605
4606 return NO_ERROR;
4607}
4608
4609
4610int AudioFlinger::newAudioSessionId()
4611{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004612 AutoMutex _l(mLock);
4613 return nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614}
4615
4616// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4617AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4618{
4619 PlaybackThread *thread = NULL;
4620 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4621 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4622 }
4623 return thread;
4624}
4625
4626// checkMixerThread_l() must be called with AudioFlinger::mLock held
4627AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4628{
4629 PlaybackThread *thread = checkPlaybackThread_l(output);
4630 if (thread != NULL) {
4631 if (thread->type() == PlaybackThread::DIRECT) {
4632 thread = NULL;
4633 }
4634 }
4635 return (MixerThread *)thread;
4636}
4637
4638// checkRecordThread_l() must be called with AudioFlinger::mLock held
4639AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4640{
4641 RecordThread *thread = NULL;
4642 if (mRecordThreads.indexOfKey(input) >= 0) {
4643 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4644 }
4645 return thread;
4646}
4647
Eric Laurentf5aafb22010-11-18 08:40:16 -08004648// nextUniqueId_l() must be called with AudioFlinger::mLock held
4649int AudioFlinger::nextUniqueId_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004651 return mNextUniqueId++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004652}
4653
4654// ----------------------------------------------------------------------------
4655// Effect management
4656// ----------------------------------------------------------------------------
4657
4658
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4660{
4661 Mutex::Autolock _l(mLock);
4662 return EffectQueryNumberEffects(numEffects);
4663}
4664
4665status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4666{
4667 Mutex::Autolock _l(mLock);
4668 return EffectQueryEffect(index, descriptor);
4669}
4670
4671status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4672{
4673 Mutex::Autolock _l(mLock);
4674 return EffectGetDescriptor(pUuid, descriptor);
4675}
4676
4677
4678// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4679static const effect_uuid_t VISUALIZATION_UUID_ =
4680 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4681
4682sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4683 effect_descriptor_t *pDesc,
4684 const sp<IEffectClient>& effectClient,
4685 int32_t priority,
4686 int output,
4687 int sessionId,
4688 status_t *status,
4689 int *id,
4690 int *enabled)
4691{
4692 status_t lStatus = NO_ERROR;
4693 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694 effect_descriptor_t desc;
4695 sp<Client> client;
4696 wp<Client> wclient;
4697
Eric Laurentde070132010-07-13 04:45:46 -07004698 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4699 pid, effectClient.get(), priority, sessionId, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700
4701 if (pDesc == NULL) {
4702 lStatus = BAD_VALUE;
4703 goto Exit;
4704 }
4705
Eric Laurent84e9a102010-09-23 16:10:16 -07004706 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07004707 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004708 lStatus = PERMISSION_DENIED;
4709 goto Exit;
4710 }
4711
Dima Zavinfce7a472011-04-19 22:30:36 -07004712 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07004713 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07004714 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004715 lStatus = PERMISSION_DENIED;
4716 goto Exit;
4717 }
4718
4719 // check recording permission for visualizer
4720 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4721 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4722 !recordingAllowed()) {
4723 lStatus = PERMISSION_DENIED;
4724 goto Exit;
4725 }
4726
4727 if (output == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004728 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004729 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07004730 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07004731 lStatus = BAD_VALUE;
4732 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07004733 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004734 // if the output returned by getOutputForEffect() is removed before we lock the
4735 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4736 // and we will exit safely
4737 output = AudioSystem::getOutputForEffect(&desc);
4738 }
4739 }
4740
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741 {
4742 Mutex::Autolock _l(mLock);
4743
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744
4745 if (!EffectIsNullUuid(&pDesc->uuid)) {
4746 // if uuid is specified, request effect descriptor
4747 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4748 if (lStatus < 0) {
4749 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4750 goto Exit;
4751 }
4752 } else {
4753 // if uuid is not specified, look for an available implementation
4754 // of the required type in effect factory
4755 if (EffectIsNullUuid(&pDesc->type)) {
4756 LOGW("createEffect() no effect type");
4757 lStatus = BAD_VALUE;
4758 goto Exit;
4759 }
4760 uint32_t numEffects = 0;
4761 effect_descriptor_t d;
4762 bool found = false;
4763
4764 lStatus = EffectQueryNumberEffects(&numEffects);
4765 if (lStatus < 0) {
4766 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4767 goto Exit;
4768 }
4769 for (uint32_t i = 0; i < numEffects; i++) {
4770 lStatus = EffectQueryEffect(i, &desc);
4771 if (lStatus < 0) {
4772 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4773 continue;
4774 }
4775 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4776 // If matching type found save effect descriptor. If the session is
4777 // 0 and the effect is not auxiliary, continue enumeration in case
4778 // an auxiliary version of this effect type is available
4779 found = true;
4780 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07004781 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004782 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4783 break;
4784 }
4785 }
4786 }
4787 if (!found) {
4788 lStatus = BAD_VALUE;
4789 LOGW("createEffect() effect not found");
4790 goto Exit;
4791 }
4792 // For same effect type, chose auxiliary version over insert version if
4793 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07004794 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004795 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4796 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4797 }
4798 }
4799
4800 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004801 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004802 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4803 lStatus = INVALID_OPERATION;
4804 goto Exit;
4805 }
4806
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807 // return effect descriptor
4808 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4809
4810 // If output is not specified try to find a matching audio session ID in one of the
4811 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004812 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4813 // because of code checking output when entering the function.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 if (output == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004815 // look for the thread where the specified audio session is present
4816 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4817 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4818 output = mPlaybackThreads.keyAt(i);
4819 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004822 // If no output thread contains the requested session ID, default to
4823 // first output. The effect chain will be moved to the correct output
4824 // thread when a track with the same session ID is created
4825 if (output == 0 && mPlaybackThreads.size()) {
4826 output = mPlaybackThreads.keyAt(0);
4827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004828 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004829 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004830 PlaybackThread *thread = checkPlaybackThread_l(output);
4831 if (thread == NULL) {
Eric Laurentde070132010-07-13 04:45:46 -07004832 LOGE("createEffect() unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004833 lStatus = BAD_VALUE;
4834 goto Exit;
4835 }
4836
Eric Laurent84e9a102010-09-23 16:10:16 -07004837 // TODO: allow attachment of effect to inputs
4838
Mathias Agopian65ab4712010-07-14 17:59:35 -07004839 wclient = mClients.valueFor(pid);
4840
4841 if (wclient != NULL) {
4842 client = wclient.promote();
4843 } else {
4844 client = new Client(this, pid);
4845 mClients.add(pid, client);
4846 }
4847
4848 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07004849 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4850 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004851 if (handle != 0 && id != NULL) {
4852 *id = handle->id();
4853 }
4854 }
4855
4856Exit:
4857 if(status) {
4858 *status = lStatus;
4859 }
4860 return handle;
4861}
4862
Eric Laurentde070132010-07-13 04:45:46 -07004863status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4864{
4865 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4866 session, srcOutput, dstOutput);
4867 Mutex::Autolock _l(mLock);
4868 if (srcOutput == dstOutput) {
4869 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4870 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004871 }
Eric Laurentde070132010-07-13 04:45:46 -07004872 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4873 if (srcThread == NULL) {
4874 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4875 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876 }
Eric Laurentde070132010-07-13 04:45:46 -07004877 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4878 if (dstThread == NULL) {
4879 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4880 return BAD_VALUE;
4881 }
4882
4883 Mutex::Autolock _dl(dstThread->mLock);
4884 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07004885 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07004886
Mathias Agopian65ab4712010-07-14 17:59:35 -07004887 return NO_ERROR;
4888}
4889
Eric Laurentde070132010-07-13 04:45:46 -07004890// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4891status_t AudioFlinger::moveEffectChain_l(int session,
4892 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07004893 AudioFlinger::PlaybackThread *dstThread,
4894 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07004895{
4896 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4897 session, srcThread, dstThread);
4898
4899 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4900 if (chain == 0) {
4901 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4902 session, srcThread);
4903 return INVALID_OPERATION;
4904 }
4905
Eric Laurent39e94f82010-07-28 01:32:47 -07004906 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004907 // so that a new chain is created with correct parameters when first effect is added. This is
4908 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4909 // removed.
4910 srcThread->removeEffectChain_l(chain);
4911
4912 // transfer all effects one by one so that new effect chain is created on new thread with
4913 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07004914 int dstOutput = dstThread->id();
4915 sp<EffectChain> dstChain;
4916 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07004917 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4918 while (effect != 0) {
4919 srcThread->removeEffect_l(effect);
4920 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07004921 // if the move request is not received from audio policy manager, the effect must be
4922 // re-registered with the new strategy and output
4923 if (dstChain == 0) {
4924 dstChain = effect->chain().promote();
4925 if (dstChain == 0) {
4926 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4927 srcThread->addEffect_l(effect);
4928 return NO_INIT;
4929 }
4930 strategy = dstChain->strategy();
4931 }
4932 if (reRegister) {
4933 AudioSystem::unregisterEffect(effect->id());
4934 AudioSystem::registerEffect(&effect->desc(),
4935 dstOutput,
4936 strategy,
4937 session,
4938 effect->id());
4939 }
Eric Laurentde070132010-07-13 04:45:46 -07004940 effect = chain->getEffectFromId_l(0);
4941 }
4942
4943 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004944}
4945
4946// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4947sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4948 const sp<AudioFlinger::Client>& client,
4949 const sp<IEffectClient>& effectClient,
4950 int32_t priority,
4951 int sessionId,
4952 effect_descriptor_t *desc,
4953 int *enabled,
4954 status_t *status
4955 )
4956{
4957 sp<EffectModule> effect;
4958 sp<EffectHandle> handle;
4959 status_t lStatus;
4960 sp<Track> track;
4961 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07004962 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 bool effectCreated = false;
4964 bool effectRegistered = false;
4965
4966 if (mOutput == 0) {
4967 LOGW("createEffect_l() Audio driver not initialized.");
4968 lStatus = NO_INIT;
4969 goto Exit;
4970 }
4971
4972 // Do not allow auxiliary effect on session other than 0
4973 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004974 sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -07004975 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4976 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 lStatus = BAD_VALUE;
4978 goto Exit;
4979 }
4980
4981 // Do not allow effects with session ID 0 on direct output or duplicating threads
4982 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07004983 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07004984 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4985 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 lStatus = BAD_VALUE;
4987 goto Exit;
4988 }
4989
4990 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4991
4992 { // scope for mLock
4993 Mutex::Autolock _l(mLock);
4994
4995 // check for existing effect chain with the requested audio session
4996 chain = getEffectChain_l(sessionId);
4997 if (chain == 0) {
4998 // create a new chain for this session
4999 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5000 chain = new EffectChain(this, sessionId);
5001 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005002 chain->setStrategy(getStrategyForSession_l(sessionId));
5003 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005004 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005005 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 }
5007
5008 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5009
5010 if (effect == 0) {
Eric Laurentf5aafb22010-11-18 08:40:16 -08005011 int id = mAudioFlinger->nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005012 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005013 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005014 if (lStatus != NO_ERROR) {
5015 goto Exit;
5016 }
5017 effectRegistered = true;
5018 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005019 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005020 lStatus = effect->status();
5021 if (lStatus != NO_ERROR) {
5022 goto Exit;
5023 }
Eric Laurentcab11242010-07-15 12:50:15 -07005024 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025 if (lStatus != NO_ERROR) {
5026 goto Exit;
5027 }
5028 effectCreated = true;
5029
5030 effect->setDevice(mDevice);
5031 effect->setMode(mAudioFlinger->getMode());
5032 }
5033 // create effect handle and connect it to effect module
5034 handle = new EffectHandle(effect, client, effectClient, priority);
5035 lStatus = effect->addHandle(handle);
5036 if (enabled) {
5037 *enabled = (int)effect->isEnabled();
5038 }
5039 }
5040
5041Exit:
5042 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005043 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005045 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005046 }
5047 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005048 AudioSystem::unregisterEffect(effect->id());
5049 }
5050 if (chainCreated) {
5051 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 }
5053 handle.clear();
5054 }
5055
5056 if(status) {
5057 *status = lStatus;
5058 }
5059 return handle;
5060}
5061
Eric Laurentde070132010-07-13 04:45:46 -07005062// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5063// PlaybackThread::mLock held
5064status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5065{
5066 // check for existing effect chain with the requested audio session
5067 int sessionId = effect->sessionId();
5068 sp<EffectChain> chain = getEffectChain_l(sessionId);
5069 bool chainCreated = false;
5070
5071 if (chain == 0) {
5072 // create a new chain for this session
5073 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5074 chain = new EffectChain(this, sessionId);
5075 addEffectChain_l(chain);
5076 chain->setStrategy(getStrategyForSession_l(sessionId));
5077 chainCreated = true;
5078 }
5079 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5080
5081 if (chain->getEffectFromId_l(effect->id()) != 0) {
5082 LOGW("addEffect_l() %p effect %s already present in chain %p",
5083 this, effect->desc().name, chain.get());
5084 return BAD_VALUE;
5085 }
5086
5087 status_t status = chain->addEffect_l(effect);
5088 if (status != NO_ERROR) {
5089 if (chainCreated) {
5090 removeEffectChain_l(chain);
5091 }
5092 return status;
5093 }
5094
5095 effect->setDevice(mDevice);
5096 effect->setMode(mAudioFlinger->getMode());
5097 return NO_ERROR;
5098}
5099
5100void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5101
5102 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005104 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5105 detachAuxEffect_l(effect->id());
5106 }
5107
5108 sp<EffectChain> chain = effect->chain().promote();
5109 if (chain != 0) {
5110 // remove effect chain if removing last effect
5111 if (chain->removeEffect_l(effect) == 0) {
5112 removeEffectChain_l(chain);
5113 }
5114 } else {
5115 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5116 }
5117}
5118
5119void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5120 const wp<EffectHandle>& handle) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005121 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005122 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 // delete the effect module if removing last handle on it
5124 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07005125 removeEffect_l(effect);
5126 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 }
5128}
5129
5130status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5131{
5132 int session = chain->sessionId();
5133 int16_t *buffer = mMixBuffer;
5134 bool ownsBuffer = false;
5135
5136 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5137 if (session > 0) {
5138 // Only one effect chain can be present in direct output thread and it uses
5139 // the mix buffer as input
5140 if (mType != DIRECT) {
5141 size_t numSamples = mFrameCount * mChannelCount;
5142 buffer = new int16_t[numSamples];
5143 memset(buffer, 0, numSamples * sizeof(int16_t));
5144 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5145 ownsBuffer = true;
5146 }
5147
5148 // Attach all tracks with same session ID to this chain.
5149 for (size_t i = 0; i < mTracks.size(); ++i) {
5150 sp<Track> track = mTracks[i];
5151 if (session == track->sessionId()) {
5152 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5153 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005154 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 }
5156 }
5157
5158 // indicate all active tracks in the chain
5159 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5160 sp<Track> track = mActiveTracks[i].promote();
5161 if (track == 0) continue;
5162 if (session == track->sessionId()) {
5163 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005164 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 }
5166 }
5167 }
5168
5169 chain->setInBuffer(buffer, ownsBuffer);
5170 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005171 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005172 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005173 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5174 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005176 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5177 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005178 // Effect chain for other sessions are inserted at beginning of effect
5179 // chains list to be processed before output mix effects. Relative order between other
5180 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005181 size_t size = mEffectChains.size();
5182 size_t i = 0;
5183 for (i = 0; i < size; i++) {
5184 if (mEffectChains[i]->sessionId() < session) break;
5185 }
5186 mEffectChains.insertAt(chain, i);
5187
5188 return NO_ERROR;
5189}
5190
5191size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5192{
5193 int session = chain->sessionId();
5194
5195 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5196
5197 for (size_t i = 0; i < mEffectChains.size(); i++) {
5198 if (chain == mEffectChains[i]) {
5199 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005200 // detach all active tracks from the chain
5201 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5202 sp<Track> track = mActiveTracks[i].promote();
5203 if (track == 0) continue;
5204 if (session == track->sessionId()) {
5205 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5206 chain.get(), session);
5207 chain->decActiveTrackCnt();
5208 }
5209 }
5210
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211 // detach all tracks with same session ID from this chain
5212 for (size_t i = 0; i < mTracks.size(); ++i) {
5213 sp<Track> track = mTracks[i];
5214 if (session == track->sessionId()) {
5215 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005216 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217 }
5218 }
Eric Laurentde070132010-07-13 04:45:46 -07005219 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005220 }
5221 }
5222 return mEffectChains.size();
5223}
5224
Eric Laurentde070132010-07-13 04:45:46 -07005225void AudioFlinger::PlaybackThread::lockEffectChains_l(
5226 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005227{
Eric Laurentde070132010-07-13 04:45:46 -07005228 effectChains = mEffectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005229 for (size_t i = 0; i < mEffectChains.size(); i++) {
5230 mEffectChains[i]->lock();
5231 }
5232}
5233
Eric Laurentde070132010-07-13 04:45:46 -07005234void AudioFlinger::PlaybackThread::unlockEffectChains(
5235 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005236{
Eric Laurentde070132010-07-13 04:45:46 -07005237 for (size_t i = 0; i < effectChains.size(); i++) {
5238 effectChains[i]->unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005239 }
5240}
5241
Eric Laurentde070132010-07-13 04:45:46 -07005242
Mathias Agopian65ab4712010-07-14 17:59:35 -07005243sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5244{
5245 sp<EffectModule> effect;
5246
5247 sp<EffectChain> chain = getEffectChain_l(sessionId);
5248 if (chain != 0) {
Eric Laurentcab11242010-07-15 12:50:15 -07005249 effect = chain->getEffectFromId_l(effectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005250 }
5251 return effect;
5252}
5253
Eric Laurentde070132010-07-13 04:45:46 -07005254status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5255 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005256{
5257 Mutex::Autolock _l(mLock);
5258 return attachAuxEffect_l(track, EffectId);
5259}
5260
Eric Laurentde070132010-07-13 04:45:46 -07005261status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5262 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005263{
5264 status_t status = NO_ERROR;
5265
5266 if (EffectId == 0) {
5267 track->setAuxBuffer(0, NULL);
5268 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005269 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5270 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005271 if (effect != 0) {
5272 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5273 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5274 } else {
5275 status = INVALID_OPERATION;
5276 }
5277 } else {
5278 status = BAD_VALUE;
5279 }
5280 }
5281 return status;
5282}
5283
5284void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5285{
5286 for (size_t i = 0; i < mTracks.size(); ++i) {
5287 sp<Track> track = mTracks[i];
5288 if (track->auxEffectId() == effectId) {
5289 attachAuxEffect_l(track, 0);
5290 }
5291 }
5292}
5293
5294// ----------------------------------------------------------------------------
5295// EffectModule implementation
5296// ----------------------------------------------------------------------------
5297
5298#undef LOG_TAG
5299#define LOG_TAG "AudioFlinger::EffectModule"
5300
5301AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5302 const wp<AudioFlinger::EffectChain>& chain,
5303 effect_descriptor_t *desc,
5304 int id,
5305 int sessionId)
5306 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5307 mStatus(NO_INIT), mState(IDLE)
5308{
5309 LOGV("Constructor %p", this);
5310 int lStatus;
5311 sp<ThreadBase> thread = mThread.promote();
5312 if (thread == 0) {
5313 return;
5314 }
5315 PlaybackThread *p = (PlaybackThread *)thread.get();
5316
5317 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5318
5319 // create effect engine from effect factory
5320 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5321
5322 if (mStatus != NO_ERROR) {
5323 return;
5324 }
5325 lStatus = init();
5326 if (lStatus < 0) {
5327 mStatus = lStatus;
5328 goto Error;
5329 }
5330
5331 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5332 return;
5333Error:
5334 EffectRelease(mEffectInterface);
5335 mEffectInterface = NULL;
5336 LOGV("Constructor Error %d", mStatus);
5337}
5338
5339AudioFlinger::EffectModule::~EffectModule()
5340{
5341 LOGV("Destructor %p", this);
5342 if (mEffectInterface != NULL) {
5343 // release effect engine
5344 EffectRelease(mEffectInterface);
5345 }
5346}
5347
5348status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5349{
5350 status_t status;
5351
5352 Mutex::Autolock _l(mLock);
5353 // First handle in mHandles has highest priority and controls the effect module
5354 int priority = handle->priority();
5355 size_t size = mHandles.size();
5356 sp<EffectHandle> h;
5357 size_t i;
5358 for (i = 0; i < size; i++) {
5359 h = mHandles[i].promote();
5360 if (h == 0) continue;
5361 if (h->priority() <= priority) break;
5362 }
5363 // if inserted in first place, move effect control from previous owner to this handle
5364 if (i == 0) {
5365 if (h != 0) {
5366 h->setControl(false, true);
5367 }
5368 handle->setControl(true, false);
5369 status = NO_ERROR;
5370 } else {
5371 status = ALREADY_EXISTS;
5372 }
5373 mHandles.insertAt(handle, i);
5374 return status;
5375}
5376
5377size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5378{
5379 Mutex::Autolock _l(mLock);
5380 size_t size = mHandles.size();
5381 size_t i;
5382 for (i = 0; i < size; i++) {
5383 if (mHandles[i] == handle) break;
5384 }
5385 if (i == size) {
5386 return size;
5387 }
5388 mHandles.removeAt(i);
5389 size = mHandles.size();
5390 // if removed from first place, move effect control from this handle to next in line
5391 if (i == 0 && size != 0) {
5392 sp<EffectHandle> h = mHandles[0].promote();
5393 if (h != 0) {
5394 h->setControl(true, true);
5395 }
5396 }
5397
Eric Laurentdac69112010-09-28 14:09:57 -07005398 // Release effect engine here so that it is done immediately. Otherwise it will be released
5399 // by the destructor when the last strong reference on the this object is released which can
5400 // happen after next process is called on this effect.
5401 if (size == 0 && mEffectInterface != NULL) {
5402 // release effect engine
5403 EffectRelease(mEffectInterface);
5404 mEffectInterface = NULL;
5405 }
5406
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407 return size;
5408}
5409
5410void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5411{
5412 // keep a strong reference on this EffectModule to avoid calling the
5413 // destructor before we exit
5414 sp<EffectModule> keep(this);
5415 {
5416 sp<ThreadBase> thread = mThread.promote();
5417 if (thread != 0) {
5418 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5419 playbackThread->disconnectEffect(keep, handle);
5420 }
5421 }
5422}
5423
5424void AudioFlinger::EffectModule::updateState() {
5425 Mutex::Autolock _l(mLock);
5426
5427 switch (mState) {
5428 case RESTART:
5429 reset_l();
5430 // FALL THROUGH
5431
5432 case STARTING:
5433 // clear auxiliary effect input buffer for next accumulation
5434 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5435 memset(mConfig.inputCfg.buffer.raw,
5436 0,
5437 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5438 }
5439 start_l();
5440 mState = ACTIVE;
5441 break;
5442 case STOPPING:
5443 stop_l();
5444 mDisableWaitCnt = mMaxDisableWaitCnt;
5445 mState = STOPPED;
5446 break;
5447 case STOPPED:
5448 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5449 // turn off sequence.
5450 if (--mDisableWaitCnt == 0) {
5451 reset_l();
5452 mState = IDLE;
5453 }
5454 break;
5455 default: //IDLE , ACTIVE
5456 break;
5457 }
5458}
5459
5460void AudioFlinger::EffectModule::process()
5461{
5462 Mutex::Autolock _l(mLock);
5463
5464 if (mEffectInterface == NULL ||
5465 mConfig.inputCfg.buffer.raw == NULL ||
5466 mConfig.outputCfg.buffer.raw == NULL) {
5467 return;
5468 }
5469
Eric Laurent8f45bd72010-08-31 13:50:07 -07005470 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5472 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5473 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5474 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005475 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 }
5477
5478 // do the actual processing in the effect engine
5479 int ret = (*mEffectInterface)->process(mEffectInterface,
5480 &mConfig.inputCfg.buffer,
5481 &mConfig.outputCfg.buffer);
5482
5483 // force transition to IDLE state when engine is ready
5484 if (mState == STOPPED && ret == -ENODATA) {
5485 mDisableWaitCnt = 1;
5486 }
5487
5488 // clear auxiliary effect input buffer for next accumulation
5489 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005490 memset(mConfig.inputCfg.buffer.raw, 0,
5491 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 }
5493 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005494 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5495 // If an insert effect is idle and input buffer is different from output buffer,
5496 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005497 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07005498 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005499 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5500 int16_t *in = mConfig.inputCfg.buffer.s16;
5501 int16_t *out = mConfig.outputCfg.buffer.s16;
5502 for (size_t i = 0; i < frameCnt; i++) {
5503 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 }
5506 }
5507}
5508
5509void AudioFlinger::EffectModule::reset_l()
5510{
5511 if (mEffectInterface == NULL) {
5512 return;
5513 }
5514 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5515}
5516
5517status_t AudioFlinger::EffectModule::configure()
5518{
5519 uint32_t channels;
5520 if (mEffectInterface == NULL) {
5521 return NO_INIT;
5522 }
5523
5524 sp<ThreadBase> thread = mThread.promote();
5525 if (thread == 0) {
5526 return DEAD_OBJECT;
5527 }
5528
5529 // TODO: handle configuration of effects replacing track process
5530 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005531 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07005533 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 }
5535
5536 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005537 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 } else {
5539 mConfig.inputCfg.channels = channels;
5540 }
5541 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07005542 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5543 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005544 mConfig.inputCfg.samplingRate = thread->sampleRate();
5545 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5546 mConfig.inputCfg.bufferProvider.cookie = NULL;
5547 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5548 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5549 mConfig.outputCfg.bufferProvider.cookie = NULL;
5550 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5551 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5552 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5553 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07005554 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07005555 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556 // - in other sessions:
5557 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5558 // other effect: overwrites output buffer: input buffer == output buffer
5559 // Auxiliary effect:
5560 // accumulates in output buffer: input buffer != output buffer
5561 // Therefore: accumulate <=> input buffer != output buffer
5562 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5563 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5564 } else {
5565 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5566 }
5567 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5568 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5569 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5570 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5571
Eric Laurentde070132010-07-13 04:45:46 -07005572 LOGV("configure() %p thread %p buffer %p framecount %d",
5573 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5574
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005576 uint32_t size = sizeof(int);
5577 status_t status = (*mEffectInterface)->command(mEffectInterface,
5578 EFFECT_CMD_CONFIGURE,
5579 sizeof(effect_config_t),
5580 &mConfig,
5581 &size,
5582 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 if (status == 0) {
5584 status = cmdStatus;
5585 }
5586
5587 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5588 (1000 * mConfig.outputCfg.buffer.frameCount);
5589
5590 return status;
5591}
5592
5593status_t AudioFlinger::EffectModule::init()
5594{
5595 Mutex::Autolock _l(mLock);
5596 if (mEffectInterface == NULL) {
5597 return NO_INIT;
5598 }
5599 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005600 uint32_t size = sizeof(status_t);
5601 status_t status = (*mEffectInterface)->command(mEffectInterface,
5602 EFFECT_CMD_INIT,
5603 0,
5604 NULL,
5605 &size,
5606 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005607 if (status == 0) {
5608 status = cmdStatus;
5609 }
5610 return status;
5611}
5612
5613status_t AudioFlinger::EffectModule::start_l()
5614{
5615 if (mEffectInterface == NULL) {
5616 return NO_INIT;
5617 }
5618 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005619 uint32_t size = sizeof(status_t);
5620 status_t status = (*mEffectInterface)->command(mEffectInterface,
5621 EFFECT_CMD_ENABLE,
5622 0,
5623 NULL,
5624 &size,
5625 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 if (status == 0) {
5627 status = cmdStatus;
5628 }
5629 return status;
5630}
5631
5632status_t AudioFlinger::EffectModule::stop_l()
5633{
5634 if (mEffectInterface == NULL) {
5635 return NO_INIT;
5636 }
5637 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005638 uint32_t size = sizeof(status_t);
5639 status_t status = (*mEffectInterface)->command(mEffectInterface,
5640 EFFECT_CMD_DISABLE,
5641 0,
5642 NULL,
5643 &size,
5644 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645 if (status == 0) {
5646 status = cmdStatus;
5647 }
5648 return status;
5649}
5650
Eric Laurent25f43952010-07-28 05:40:18 -07005651status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5652 uint32_t cmdSize,
5653 void *pCmdData,
5654 uint32_t *replySize,
5655 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656{
5657 Mutex::Autolock _l(mLock);
5658// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5659
5660 if (mEffectInterface == NULL) {
5661 return NO_INIT;
5662 }
Eric Laurent25f43952010-07-28 05:40:18 -07005663 status_t status = (*mEffectInterface)->command(mEffectInterface,
5664 cmdCode,
5665 cmdSize,
5666 pCmdData,
5667 replySize,
5668 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07005670 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671 for (size_t i = 1; i < mHandles.size(); i++) {
5672 sp<EffectHandle> h = mHandles[i].promote();
5673 if (h != 0) {
5674 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5675 }
5676 }
5677 }
5678 return status;
5679}
5680
5681status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5682{
5683 Mutex::Autolock _l(mLock);
5684 LOGV("setEnabled %p enabled %d", this, enabled);
5685
5686 if (enabled != isEnabled()) {
5687 switch (mState) {
5688 // going from disabled to enabled
5689 case IDLE:
5690 mState = STARTING;
5691 break;
5692 case STOPPED:
5693 mState = RESTART;
5694 break;
5695 case STOPPING:
5696 mState = ACTIVE;
5697 break;
5698
5699 // going from enabled to disabled
5700 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005701 mState = STOPPED;
5702 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703 case STARTING:
5704 mState = IDLE;
5705 break;
5706 case ACTIVE:
5707 mState = STOPPING;
5708 break;
5709 }
5710 for (size_t i = 1; i < mHandles.size(); i++) {
5711 sp<EffectHandle> h = mHandles[i].promote();
5712 if (h != 0) {
5713 h->setEnabled(enabled);
5714 }
5715 }
5716 }
5717 return NO_ERROR;
5718}
5719
5720bool AudioFlinger::EffectModule::isEnabled()
5721{
5722 switch (mState) {
5723 case RESTART:
5724 case STARTING:
5725 case ACTIVE:
5726 return true;
5727 case IDLE:
5728 case STOPPING:
5729 case STOPPED:
5730 default:
5731 return false;
5732 }
5733}
5734
Eric Laurent8f45bd72010-08-31 13:50:07 -07005735bool AudioFlinger::EffectModule::isProcessEnabled()
5736{
5737 switch (mState) {
5738 case RESTART:
5739 case ACTIVE:
5740 case STOPPING:
5741 case STOPPED:
5742 return true;
5743 case IDLE:
5744 case STARTING:
5745 default:
5746 return false;
5747 }
5748}
5749
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5751{
5752 Mutex::Autolock _l(mLock);
5753 status_t status = NO_ERROR;
5754
5755 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5756 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07005757 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07005758 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5759 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 status_t cmdStatus;
5761 uint32_t volume[2];
5762 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07005763 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 volume[0] = *left;
5765 volume[1] = *right;
5766 if (controller) {
5767 pVolume = volume;
5768 }
Eric Laurent25f43952010-07-28 05:40:18 -07005769 status = (*mEffectInterface)->command(mEffectInterface,
5770 EFFECT_CMD_SET_VOLUME,
5771 size,
5772 volume,
5773 &size,
5774 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5776 *left = volume[0];
5777 *right = volume[1];
5778 }
5779 }
5780 return status;
5781}
5782
5783status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5784{
5785 Mutex::Autolock _l(mLock);
5786 status_t status = NO_ERROR;
5787 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005789 uint32_t size = sizeof(status_t);
5790 status = (*mEffectInterface)->command(mEffectInterface,
5791 EFFECT_CMD_SET_DEVICE,
5792 sizeof(uint32_t),
5793 &device,
5794 &size,
5795 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796 if (status == NO_ERROR) {
5797 status = cmdStatus;
5798 }
5799 }
5800 return status;
5801}
5802
5803status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5804{
5805 Mutex::Autolock _l(mLock);
5806 status_t status = NO_ERROR;
5807 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005808 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005809 uint32_t size = sizeof(status_t);
5810 status = (*mEffectInterface)->command(mEffectInterface,
5811 EFFECT_CMD_SET_AUDIO_MODE,
5812 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07005813 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07005814 &size,
5815 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816 if (status == NO_ERROR) {
5817 status = cmdStatus;
5818 }
5819 }
5820 return status;
5821}
5822
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5824{
5825 const size_t SIZE = 256;
5826 char buffer[SIZE];
5827 String8 result;
5828
5829 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5830 result.append(buffer);
5831
5832 bool locked = tryLock(mLock);
5833 // failed to lock - AudioFlinger is probably deadlocked
5834 if (!locked) {
5835 result.append("\t\tCould not lock Fx mutex:\n");
5836 }
5837
5838 result.append("\t\tSession Status State Engine:\n");
5839 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5840 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5841 result.append(buffer);
5842
5843 result.append("\t\tDescriptor:\n");
5844 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5845 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5846 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5847 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5848 result.append(buffer);
5849 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5850 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5851 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5852 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5853 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07005854 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855 mDescriptor.apiVersion,
5856 mDescriptor.flags);
5857 result.append(buffer);
5858 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5859 mDescriptor.name);
5860 result.append(buffer);
5861 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5862 mDescriptor.implementor);
5863 result.append(buffer);
5864
5865 result.append("\t\t- Input configuration:\n");
5866 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5867 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5868 (uint32_t)mConfig.inputCfg.buffer.raw,
5869 mConfig.inputCfg.buffer.frameCount,
5870 mConfig.inputCfg.samplingRate,
5871 mConfig.inputCfg.channels,
5872 mConfig.inputCfg.format);
5873 result.append(buffer);
5874
5875 result.append("\t\t- Output configuration:\n");
5876 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5877 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5878 (uint32_t)mConfig.outputCfg.buffer.raw,
5879 mConfig.outputCfg.buffer.frameCount,
5880 mConfig.outputCfg.samplingRate,
5881 mConfig.outputCfg.channels,
5882 mConfig.outputCfg.format);
5883 result.append(buffer);
5884
5885 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5886 result.append(buffer);
5887 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5888 for (size_t i = 0; i < mHandles.size(); ++i) {
5889 sp<EffectHandle> handle = mHandles[i].promote();
5890 if (handle != 0) {
5891 handle->dump(buffer, SIZE);
5892 result.append(buffer);
5893 }
5894 }
5895
5896 result.append("\n");
5897
5898 write(fd, result.string(), result.length());
5899
5900 if (locked) {
5901 mLock.unlock();
5902 }
5903
5904 return NO_ERROR;
5905}
5906
5907// ----------------------------------------------------------------------------
5908// EffectHandle implementation
5909// ----------------------------------------------------------------------------
5910
5911#undef LOG_TAG
5912#define LOG_TAG "AudioFlinger::EffectHandle"
5913
5914AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5915 const sp<AudioFlinger::Client>& client,
5916 const sp<IEffectClient>& effectClient,
5917 int32_t priority)
5918 : BnEffect(),
5919 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5920{
5921 LOGV("constructor %p", this);
5922
5923 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5924 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5925 if (mCblkMemory != 0) {
5926 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5927
5928 if (mCblk) {
5929 new(mCblk) effect_param_cblk_t();
5930 mBuffer = (uint8_t *)mCblk + bufOffset;
5931 }
5932 } else {
5933 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5934 return;
5935 }
5936}
5937
5938AudioFlinger::EffectHandle::~EffectHandle()
5939{
5940 LOGV("Destructor %p", this);
5941 disconnect();
5942}
5943
5944status_t AudioFlinger::EffectHandle::enable()
5945{
5946 if (!mHasControl) return INVALID_OPERATION;
5947 if (mEffect == 0) return DEAD_OBJECT;
5948
5949 return mEffect->setEnabled(true);
5950}
5951
5952status_t AudioFlinger::EffectHandle::disable()
5953{
5954 if (!mHasControl) return INVALID_OPERATION;
5955 if (mEffect == NULL) return DEAD_OBJECT;
5956
5957 return mEffect->setEnabled(false);
5958}
5959
5960void AudioFlinger::EffectHandle::disconnect()
5961{
5962 if (mEffect == 0) {
5963 return;
5964 }
5965 mEffect->disconnect(this);
5966 // release sp on module => module destructor can be called now
5967 mEffect.clear();
5968 if (mCblk) {
5969 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5970 }
5971 mCblkMemory.clear(); // and free the shared memory
5972 if (mClient != 0) {
5973 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5974 mClient.clear();
5975 }
5976}
5977
Eric Laurent25f43952010-07-28 05:40:18 -07005978status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5979 uint32_t cmdSize,
5980 void *pCmdData,
5981 uint32_t *replySize,
5982 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983{
Eric Laurent25f43952010-07-28 05:40:18 -07005984// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5985// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986
5987 // only get parameter command is permitted for applications not controlling the effect
5988 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5989 return INVALID_OPERATION;
5990 }
5991 if (mEffect == 0) return DEAD_OBJECT;
5992
5993 // handle commands that are not forwarded transparently to effect engine
5994 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5995 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5996 // no risk to block the whole media server process or mixer threads is we are stuck here
5997 Mutex::Autolock _l(mCblk->lock);
5998 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5999 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6000 mCblk->serverIndex = 0;
6001 mCblk->clientIndex = 0;
6002 return BAD_VALUE;
6003 }
6004 status_t status = NO_ERROR;
6005 while (mCblk->serverIndex < mCblk->clientIndex) {
6006 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006007 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 int *p = (int *)(mBuffer + mCblk->serverIndex);
6009 int size = *p++;
6010 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6011 LOGW("command(): invalid parameter block size");
6012 break;
6013 }
6014 effect_param_t *param = (effect_param_t *)p;
6015 if (param->psize == 0 || param->vsize == 0) {
6016 LOGW("command(): null parameter or value size");
6017 mCblk->serverIndex += size;
6018 continue;
6019 }
Eric Laurent25f43952010-07-28 05:40:18 -07006020 uint32_t psize = sizeof(effect_param_t) +
6021 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6022 param->vsize;
6023 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6024 psize,
6025 p,
6026 &rsize,
6027 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006028 // stop at first error encountered
6029 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006031 *(int *)pReplyData = reply;
6032 break;
6033 } else if (reply != NO_ERROR) {
6034 *(int *)pReplyData = reply;
6035 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 }
6037 mCblk->serverIndex += size;
6038 }
6039 mCblk->serverIndex = 0;
6040 mCblk->clientIndex = 0;
6041 return status;
6042 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006043 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 return enable();
6045 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006046 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 return disable();
6048 }
6049
6050 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6051}
6052
6053sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6054 return mCblkMemory;
6055}
6056
6057void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6058{
6059 LOGV("setControl %p control %d", this, hasControl);
6060
6061 mHasControl = hasControl;
6062 if (signal && mEffectClient != 0) {
6063 mEffectClient->controlStatusChanged(hasControl);
6064 }
6065}
6066
Eric Laurent25f43952010-07-28 05:40:18 -07006067void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6068 uint32_t cmdSize,
6069 void *pCmdData,
6070 uint32_t replySize,
6071 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072{
6073 if (mEffectClient != 0) {
6074 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6075 }
6076}
6077
6078
6079
6080void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6081{
6082 if (mEffectClient != 0) {
6083 mEffectClient->enableStatusChanged(enabled);
6084 }
6085}
6086
6087status_t AudioFlinger::EffectHandle::onTransact(
6088 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6089{
6090 return BnEffect::onTransact(code, data, reply, flags);
6091}
6092
6093
6094void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6095{
6096 bool locked = tryLock(mCblk->lock);
6097
6098 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6099 (mClient == NULL) ? getpid() : mClient->pid(),
6100 mPriority,
6101 mHasControl,
6102 !locked,
6103 mCblk->clientIndex,
6104 mCblk->serverIndex
6105 );
6106
6107 if (locked) {
6108 mCblk->lock.unlock();
6109 }
6110}
6111
6112#undef LOG_TAG
6113#define LOG_TAG "AudioFlinger::EffectChain"
6114
6115AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6116 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006117 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6118 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6119 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120{
Dima Zavinfce7a472011-04-19 22:30:36 -07006121 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122}
6123
6124AudioFlinger::EffectChain::~EffectChain()
6125{
6126 if (mOwnInBuffer) {
6127 delete mInBuffer;
6128 }
6129
6130}
6131
Eric Laurentcab11242010-07-15 12:50:15 -07006132// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6133sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134{
6135 sp<EffectModule> effect;
6136 size_t size = mEffects.size();
6137
6138 for (size_t i = 0; i < size; i++) {
6139 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6140 effect = mEffects[i];
6141 break;
6142 }
6143 }
6144 return effect;
6145}
6146
Eric Laurentcab11242010-07-15 12:50:15 -07006147// getEffectFromId_l() must be called with PlaybackThread::mLock held
6148sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149{
6150 sp<EffectModule> effect;
6151 size_t size = mEffects.size();
6152
6153 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006154 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6155 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 effect = mEffects[i];
6157 break;
6158 }
6159 }
6160 return effect;
6161}
6162
6163// Must be called with EffectChain::mLock locked
6164void AudioFlinger::EffectChain::process_l()
6165{
Eric Laurentdac69112010-09-28 14:09:57 -07006166 sp<ThreadBase> thread = mThread.promote();
6167 if (thread == 0) {
6168 LOGW("process_l(): cannot promote mixer thread");
6169 return;
6170 }
6171 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Dima Zavinfce7a472011-04-19 22:30:36 -07006172 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6173 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07006174 bool tracksOnSession = false;
6175 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07006176 tracksOnSession = (trackCnt() != 0);
6177 }
6178
6179 // if no track is active, input buffer must be cleared here as the mixer process
6180 // will not do it
6181 if (tracksOnSession &&
6182 activeTrackCnt() == 0) {
6183 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6184 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07006185 }
6186
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006188 // do not process effect if no track is present in same audio session
6189 if (isGlobalSession || tracksOnSession) {
6190 for (size_t i = 0; i < size; i++) {
6191 mEffects[i]->process();
6192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 }
6194 for (size_t i = 0; i < size; i++) {
6195 mEffects[i]->updateState();
6196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197}
6198
Eric Laurentcab11242010-07-15 12:50:15 -07006199// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006200status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201{
6202 effect_descriptor_t desc = effect->desc();
6203 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6204
6205 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006206 effect->setChain(this);
6207 sp<ThreadBase> thread = mThread.promote();
6208 if (thread == 0) {
6209 return NO_INIT;
6210 }
6211 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212
6213 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6214 // Auxiliary effects are inserted at the beginning of mEffects vector as
6215 // they are processed first and accumulated in chain input buffer
6216 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006217
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218 // the input buffer for auxiliary effect contains mono samples in
6219 // 32 bit format. This is to avoid saturation in AudoMixer
6220 // accumulation stage. Saturation is done in EffectModule::process() before
6221 // calling the process in effect engine
6222 size_t numSamples = thread->frameCount();
6223 int32_t *buffer = new int32_t[numSamples];
6224 memset(buffer, 0, numSamples * sizeof(int32_t));
6225 effect->setInBuffer((int16_t *)buffer);
6226 // auxiliary effects output samples to chain input buffer for further processing
6227 // by insert effects
6228 effect->setOutBuffer(mInBuffer);
6229 } else {
6230 // Insert effects are inserted at the end of mEffects vector as they are processed
6231 // after track and auxiliary effects.
6232 // Insert effect order as a function of indicated preference:
6233 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6234 // another effect is present
6235 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6236 // last effect claiming first position
6237 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6238 // first effect claiming last position
6239 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6240 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6241 // already present
6242
6243 int size = (int)mEffects.size();
6244 int idx_insert = size;
6245 int idx_insert_first = -1;
6246 int idx_insert_last = -1;
6247
6248 for (int i = 0; i < size; i++) {
6249 effect_descriptor_t d = mEffects[i]->desc();
6250 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6251 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6252 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6253 // check invalid effect chaining combinations
6254 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6255 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006256 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006257 return INVALID_OPERATION;
6258 }
6259 // remember position of first insert effect and by default
6260 // select this as insert position for new effect
6261 if (idx_insert == size) {
6262 idx_insert = i;
6263 }
6264 // remember position of last insert effect claiming
6265 // first position
6266 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6267 idx_insert_first = i;
6268 }
6269 // remember position of first insert effect claiming
6270 // last position
6271 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6272 idx_insert_last == -1) {
6273 idx_insert_last = i;
6274 }
6275 }
6276 }
6277
6278 // modify idx_insert from first position if needed
6279 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6280 if (idx_insert_last != -1) {
6281 idx_insert = idx_insert_last;
6282 } else {
6283 idx_insert = size;
6284 }
6285 } else {
6286 if (idx_insert_first != -1) {
6287 idx_insert = idx_insert_first + 1;
6288 }
6289 }
6290
6291 // always read samples from chain input buffer
6292 effect->setInBuffer(mInBuffer);
6293
6294 // if last effect in the chain, output samples to chain
6295 // output buffer, otherwise to chain input buffer
6296 if (idx_insert == size) {
6297 if (idx_insert != 0) {
6298 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6299 mEffects[idx_insert-1]->configure();
6300 }
6301 effect->setOutBuffer(mOutBuffer);
6302 } else {
6303 effect->setOutBuffer(mInBuffer);
6304 }
6305 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306
Eric Laurentcab11242010-07-15 12:50:15 -07006307 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006308 }
6309 effect->configure();
6310 return NO_ERROR;
6311}
6312
Eric Laurentcab11242010-07-15 12:50:15 -07006313// removeEffect_l() must be called with PlaybackThread::mLock held
6314size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315{
6316 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 int size = (int)mEffects.size();
6318 int i;
6319 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6320
6321 for (i = 0; i < size; i++) {
6322 if (effect == mEffects[i]) {
6323 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6324 delete[] effect->inBuffer();
6325 } else {
6326 if (i == size - 1 && i != 0) {
6327 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6328 mEffects[i - 1]->configure();
6329 }
6330 }
6331 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006332 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006333 break;
6334 }
6335 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006336
6337 return mEffects.size();
6338}
6339
Eric Laurentcab11242010-07-15 12:50:15 -07006340// setDevice_l() must be called with PlaybackThread::mLock held
6341void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006342{
6343 size_t size = mEffects.size();
6344 for (size_t i = 0; i < size; i++) {
6345 mEffects[i]->setDevice(device);
6346 }
6347}
6348
Eric Laurentcab11242010-07-15 12:50:15 -07006349// setMode_l() must be called with PlaybackThread::mLock held
6350void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006351{
6352 size_t size = mEffects.size();
6353 for (size_t i = 0; i < size; i++) {
6354 mEffects[i]->setMode(mode);
6355 }
6356}
6357
Eric Laurentcab11242010-07-15 12:50:15 -07006358// setVolume_l() must be called with PlaybackThread::mLock held
6359bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360{
6361 uint32_t newLeft = *left;
6362 uint32_t newRight = *right;
6363 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006364 int ctrlIdx = -1;
6365 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366
Eric Laurentcab11242010-07-15 12:50:15 -07006367 // first update volume controller
6368 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006369 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006370 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6371 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006372 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006373 break;
6374 }
6375 }
6376
6377 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006378 if (hasControl) {
6379 *left = mNewLeftVolume;
6380 *right = mNewRightVolume;
6381 }
6382 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006383 }
6384
6385 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006386 mLeftVolume = newLeft;
6387 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006388
6389 // second get volume update from volume controller
6390 if (ctrlIdx >= 0) {
6391 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006392 mNewLeftVolume = newLeft;
6393 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394 }
6395 // then indicate volume to all other effects in chain.
6396 // Pass altered volume to effects before volume controller
6397 // and requested volume to effects after controller
6398 uint32_t lVol = newLeft;
6399 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006400
Mathias Agopian65ab4712010-07-14 17:59:35 -07006401 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006402 if ((int)i == ctrlIdx) continue;
6403 // this also works for ctrlIdx == -1 when there is no volume controller
6404 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405 lVol = *left;
6406 rVol = *right;
6407 }
6408 mEffects[i]->setVolume(&lVol, &rVol, false);
6409 }
6410 *left = newLeft;
6411 *right = newRight;
6412
6413 return hasControl;
6414}
6415
Mathias Agopian65ab4712010-07-14 17:59:35 -07006416status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6417{
6418 const size_t SIZE = 256;
6419 char buffer[SIZE];
6420 String8 result;
6421
6422 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6423 result.append(buffer);
6424
6425 bool locked = tryLock(mLock);
6426 // failed to lock - AudioFlinger is probably deadlocked
6427 if (!locked) {
6428 result.append("\tCould not lock mutex:\n");
6429 }
6430
Eric Laurentcab11242010-07-15 12:50:15 -07006431 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6432 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 mEffects.size(),
6434 (uint32_t)mInBuffer,
6435 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006436 mActiveTrackCnt);
6437 result.append(buffer);
6438 write(fd, result.string(), result.size());
6439
6440 for (size_t i = 0; i < mEffects.size(); ++i) {
6441 sp<EffectModule> effect = mEffects[i];
6442 if (effect != 0) {
6443 effect->dump(fd, args);
6444 }
6445 }
6446
6447 if (locked) {
6448 mLock.unlock();
6449 }
6450
6451 return NO_ERROR;
6452}
6453
6454#undef LOG_TAG
6455#define LOG_TAG "AudioFlinger"
6456
6457// ----------------------------------------------------------------------------
6458
6459status_t AudioFlinger::onTransact(
6460 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6461{
6462 return BnAudioFlinger::onTransact(code, data, reply, flags);
6463}
6464
Mathias Agopian65ab4712010-07-14 17:59:35 -07006465}; // namespace android